gitea源码

config_submodule.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package git
  4. import (
  5. "bufio"
  6. "fmt"
  7. "io"
  8. "strings"
  9. )
  10. // SubModule is a reference on git repository
  11. type SubModule struct {
  12. Path string
  13. URL string
  14. Branch string // this field is newly added but not really used
  15. }
  16. // configParseSubModules this is not a complete parse for gitmodules file, it only
  17. // parses the url and path of submodules. At the moment it only parses well-formed gitmodules files.
  18. // In the future, there should be a complete implementation of https://git-scm.com/docs/git-config#_syntax
  19. func configParseSubModules(r io.Reader) (*ObjectCache[*SubModule], error) {
  20. var subModule *SubModule
  21. subModules := newObjectCache[*SubModule]()
  22. scanner := bufio.NewScanner(r)
  23. for scanner.Scan() {
  24. line := strings.TrimSpace(scanner.Text())
  25. // Skip empty lines and comments
  26. if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
  27. continue
  28. }
  29. // Section header [section]
  30. if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
  31. if subModule != nil {
  32. subModules.Set(subModule.Path, subModule)
  33. }
  34. if strings.HasPrefix(line, "[submodule") {
  35. subModule = &SubModule{}
  36. } else {
  37. subModule = nil
  38. }
  39. continue
  40. }
  41. if subModule == nil {
  42. continue
  43. }
  44. parts := strings.SplitN(line, "=", 2)
  45. if len(parts) != 2 {
  46. continue
  47. }
  48. key := strings.TrimSpace(parts[0])
  49. value := strings.TrimSpace(parts[1])
  50. switch key {
  51. case "path":
  52. subModule.Path = value
  53. case "url":
  54. subModule.URL = value
  55. case "branch":
  56. subModule.Branch = value
  57. }
  58. }
  59. if err := scanner.Err(); err != nil {
  60. return nil, fmt.Errorf("error reading file: %w", err)
  61. }
  62. if subModule != nil {
  63. subModules.Set(subModule.Path, subModule)
  64. }
  65. return subModules, nil
  66. }