db.go 987 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2023 The Knuth Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package kpath
  5. import (
  6. "bufio"
  7. "fmt"
  8. "io"
  9. stdpath "path"
  10. "strings"
  11. )
  12. func parseDB(root string, r io.Reader) (Context, error) {
  13. db := make(map[string][]string)
  14. sc := bufio.NewScanner(r)
  15. dir := root
  16. for sc.Scan() {
  17. txt := strings.TrimSpace(sc.Text())
  18. if txt == "" {
  19. continue
  20. }
  21. if txt[0] == '%' {
  22. continue
  23. }
  24. switch {
  25. case isDirDB(txt):
  26. dir = stdpath.Join(root, strings.TrimRight(txt, ":"))
  27. default:
  28. db[txt] = append(db[txt], stdpath.Join(dir, txt))
  29. }
  30. }
  31. err := sc.Err()
  32. if err != nil && err != io.EOF {
  33. return Context{}, fmt.Errorf("could not scan db file: %w", err)
  34. }
  35. return Context{db: db}, nil
  36. }
  37. func isDirDB(name string) bool {
  38. return strings.HasSuffix(name, ":") && (strings.HasPrefix(name, "/") ||
  39. strings.HasPrefix(name, "./") ||
  40. strings.HasPrefix(name, "../"))
  41. }