doSingleImport lexes the individual file at importFile and returns its tokens or an error, if any.
(importFile string)
| 586 | // doSingleImport lexes the individual file at importFile and returns |
| 587 | // its tokens or an error, if any. |
| 588 | func (p *parser) doSingleImport(importFile string) ([]Token, error) { |
| 589 | file, err := os.Open(importFile) |
| 590 | if err != nil { |
| 591 | return nil, p.Errf("Could not import %s: %v", importFile, err) |
| 592 | } |
| 593 | defer file.Close() |
| 594 | |
| 595 | if info, err := file.Stat(); err != nil { |
| 596 | return nil, p.Errf("Could not import %s: %v", importFile, err) |
| 597 | } else if info.IsDir() { |
| 598 | return nil, p.Errf("Could not import %s: is a directory", importFile) |
| 599 | } |
| 600 | |
| 601 | input, err := io.ReadAll(file) |
| 602 | if err != nil { |
| 603 | return nil, p.Errf("Could not read imported file %s: %v", importFile, err) |
| 604 | } |
| 605 | |
| 606 | // only warning in case of empty files |
| 607 | if len(input) == 0 || len(strings.TrimSpace(string(input))) == 0 { |
| 608 | caddy.Log().Warn("Import file is empty", zap.String("file", importFile)) |
| 609 | return []Token{}, nil |
| 610 | } |
| 611 | |
| 612 | importedTokens, err := allTokens(importFile, input) |
| 613 | if err != nil { |
| 614 | return nil, p.Errf("Could not read tokens while importing %s: %v", importFile, err) |
| 615 | } |
| 616 | |
| 617 | // Tack the file path onto these tokens so errors show the imported file's name |
| 618 | // (we use full, absolute path to avoid bugs: issue #1892) |
| 619 | filename, err := caddy.FastAbs(importFile) |
| 620 | if err != nil { |
| 621 | return nil, p.Errf("Failed to get absolute path of file: %s: %v", importFile, err) |
| 622 | } |
| 623 | for i := range importedTokens { |
| 624 | importedTokens[i].File = filename |
| 625 | } |
| 626 | |
| 627 | return importedTokens, nil |
| 628 | } |
| 629 | |
| 630 | // directive collects tokens until the directive's scope |
| 631 | // closes (either end of line or end of curly brace block). |