Debian Codegraph @

config/config.go

raw
1 // Package config contains the abstraction of multiple config files
2 package config
3
4 import (
5 "bytes"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "path/filepath"
11 "sort"
12 "strconv"
13
14 "github.com/go-git/go-billy/v5/osfs"
15 "github.com/go-git/go-git/v5/internal/url"
16 "github.com/go-git/go-git/v5/plumbing"
17 format "github.com/go-git/go-git/v5/plumbing/format/config"
18 )
19
20 const (
21 // DefaultFetchRefSpec is the default refspec used for fetch.
22 DefaultFetchRefSpec = "+refs/heads/*:refs/remotes/%s/*"
23 // DefaultPushRefSpec is the default refspec used for push.
24 DefaultPushRefSpec = "refs/heads/*:refs/heads/*"
25 )
26
27 // ConfigStorer generic storage of Config object
28 type ConfigStorer interface {
29 Config() (*Config, error)
30 SetConfig(*Config) error
31 }
32
33 var (
34 ErrInvalid = errors.New("config invalid key in remote or branch")
35 ErrRemoteConfigNotFound = errors.New("remote config not found")
36 ErrRemoteConfigEmptyURL = errors.New("remote config: empty URL")
37 ErrRemoteConfigEmptyName = errors.New("remote config: empty name")
38 )
39
40 // Scope defines the scope of a config file, such as local, global or system.
41 type Scope int
42
43 // Available ConfigScope's
44 const (
45 LocalScope Scope = iota
46 GlobalScope
47 SystemScope
48 )
49
50 // Config contains the repository configuration
51 // https://www.kernel.org/pub/software/scm/git/docs/git-config.html#FILES
52 type Config struct {
53 Core struct {
54 // IsBare if true this repository is assumed to be bare and has no
55 // working directory associated with it.
56 IsBare bool
57 // Worktree is the path to the root of the working tree.
58 Worktree string
59 // CommentChar is the character indicating the start of a
60 // comment for commands like commit and tag
61 CommentChar string
62 // RepositoryFormatVersion identifies the repository format and layout version.
63 RepositoryFormatVersion format.RepositoryFormatVersion
64 // ProtectNTFS controls whether NTFS-specific path protections are
65 // applied (e.g. rejecting .git trailing spaces/periods, alternate
66 // data streams, 8.3 short names). When unset, defaults to true on
67 // Windows.
68 ProtectNTFS OptBool
69 // ProtectHFS controls whether HFS+-specific path protections are
70 // applied (e.g. rejecting .git with Unicode zero-width or
71 // directional characters that HFS+ would normalize away).
72 // When unset, defaults to true on macOS.
73 ProtectHFS OptBool
74 }
75
76 User struct {
77 // Name is the personal name of the author and the committer of a commit.
78 Name string
79 // Email is the email of the author and the committer of a commit.
80 Email string
81 }
82
83 Author struct {
84 // Name is the personal name of the author of a commit.
85 Name string
86 // Email is the email of the author of a commit.
87 Email string
88 }
89
90 Committer struct {
91 // Name is the personal name of the committer of a commit.
92 Name string
93 // Email is the email of the committer of a commit.
94 Email string
95 }
96
97 Pack struct {
98 // Window controls the size of the sliding window for delta
99 // compression. The default is 10. A value of 0 turns off
100 // delta compression entirely.
101 Window uint
102 }
103
104 Init struct {
105 // DefaultBranch Allows overriding the default branch name
106 // e.g. when initializing a new repository or when cloning
107 // an empty repository.
108 DefaultBranch string
109 }
110
111 Extensions struct {
112 // ObjectFormat specifies the hash algorithm to use. The
113 // acceptable values are sha1 and sha256. If not specified,
114 // sha1 is assumed. It is an error to specify this key unless
115 // core.repositoryFormatVersion is 1.
116 //
117 // This setting must not be changed after repository initialization
118 // (e.g. clone or init).
119 ObjectFormat format.ObjectFormat
120 }
121
122 // Remotes list of repository remotes, the key of the map is the name
123 // of the remote, should equal to RemoteConfig.Name.
124 Remotes map[string]*RemoteConfig
125 // Submodules list of repository submodules, the key of the map is the name
126 // of the submodule, should equal to Submodule.Name.
127 Submodules map[string]*Submodule
128 // Branches list of branches, the key is the branch name and should
129 // equal Branch.Name
130 Branches map[string]*Branch
131 // URLs list of url rewrite rules, if repo url starts with URL.InsteadOf value, it will be replaced with the
132 // key instead.
133 URLs map[string]*URL
134 // Raw contains the raw information of a config file. The main goal is
135 // preserve the parsed information from the original format, to avoid
136 // dropping unsupported fields.
137 Raw *format.Config
138 }
139
140 // NewConfig returns a new empty Config.
141 func NewConfig() *Config {
142 config := &Config{
143 Remotes: make(map[string]*RemoteConfig),
144 Submodules: make(map[string]*Submodule),
145 Branches: make(map[string]*Branch),
146 URLs: make(map[string]*URL),
147 Raw: format.New(),
148 }
149
150 config.Pack.Window = DefaultPackWindow
151
152 return config
153 }
154
155 // ReadConfig reads a config file from a io.Reader.
156 func ReadConfig(r io.Reader) (*Config, error) {
157 b, err := io.ReadAll(r)
158 if err != nil {
159 return nil, err
160 }
161
162 cfg := NewConfig()
163 if err = cfg.Unmarshal(b); err != nil {
164 return nil, err
165 }
166
167 return cfg, nil
168 }
169
170 // LoadConfig loads a config file from a given scope. The returned Config,
171 // contains exclusively information from the given scope. If it couldn't find a
172 // config file to the given scope, an empty one is returned.
173 func LoadConfig(scope Scope) (*Config, error) {
174 if scope == LocalScope {
175 return nil, fmt.Errorf("LocalScope should be read from the a ConfigStorer")
176 }
177
178 files, err := Paths(scope)
179 if err != nil {
180 return nil, err
181 }
182
183 for _, file := range files {
184 f, err := osfs.Default.Open(file)
185 if err != nil {
186 if os.IsNotExist(err) {
187 continue
188 }
189
190 return nil, err
191 }
192
193 defer f.Close()
194 return ReadConfig(f)
195 }
196
197 return NewConfig(), nil
198 }
199
200 // Paths returns the config file location for a given scope.
201 func Paths(scope Scope) ([]string, error) {
202 var files []string
203 switch scope {
204 case GlobalScope:
205 xdg := os.Getenv("XDG_CONFIG_HOME")
206 if xdg != "" {
207 files = append(files, filepath.Join(xdg, "git/config"))
208 }
209
210 home, err := os.UserHomeDir()
211 if err != nil {
212 return nil, err
213 }
214
215 files = append(files,
216 filepath.Join(home, ".gitconfig"),
217 filepath.Join(home, ".config/git/config"),
218 )
219 case SystemScope:
220 files = append(files, "/etc/gitconfig")
221 }
222
223 return files, nil
224 }
225
226 // Validate validates the fields and sets the default values.
227 func (c *Config) Validate() error {
228 for name, r := range c.Remotes {
229 if r.Name != name {
230 return ErrInvalid
231 }
232
233 if err := r.Validate(); err != nil {
234 return err
235 }
236 }
237
238 for name, b := range c.Branches {
239 if b.Name != name {
240 return ErrInvalid
241 }
242
243 if err := b.Validate(); err != nil {
244 return err
245 }
246 }
247
248 return nil
249 }
250
251 const (
252 remoteSection = "remote"
253 submoduleSection = "submodule"
254 branchSection = "branch"
255 coreSection = "core"
256 packSection = "pack"
257 userSection = "user"
258 authorSection = "author"
259 committerSection = "committer"
260 initSection = "init"
261 urlSection = "url"
262 extensionsSection = "extensions"
263 fetchKey = "fetch"
264 urlKey = "url"
265 pushurlKey = "pushurl"
266 bareKey = "bare"
267 worktreeKey = "worktree"
268 commentCharKey = "commentChar"
269 windowKey = "window"
270 mergeKey = "merge"
271 rebaseKey = "rebase"
272 nameKey = "name"
273 emailKey = "email"
274 descriptionKey = "description"
275 defaultBranchKey = "defaultBranch"
276 repositoryFormatVersionKey = "repositoryformatversion"
277 objectFormat = "objectformat"
278 mirrorKey = "mirror"
279 protectNTFSKey = "protectNTFS"
280 protectHFSKey = "protectHFS"
281
282 // DefaultPackWindow holds the number of previous objects used to
283 // generate deltas. The value 10 is the same used by git command.
284 DefaultPackWindow = uint(10)
285 )
286
287 // Unmarshal parses a git-config file and stores it.
288 func (c *Config) Unmarshal(b []byte) error {
289 r := bytes.NewBuffer(b)
290 d := format.NewDecoder(r)
291
292 c.Raw = format.New()
293 if err := d.Decode(c.Raw); err != nil {
294 return err
295 }
296
297 c.unmarshalCore()
298 c.unmarshalUser()
299 c.unmarshalInit()
300 if err := c.unmarshalPack(); err != nil {
301 return err
302 }
303 unmarshalSubmodules(c.Raw, c.Submodules)
304
305 if err := c.unmarshalBranches(); err != nil {
306 return err
307 }
308
309 if err := c.unmarshalURLs(); err != nil {
310 return err
311 }
312
313 return c.unmarshalRemotes()
314 }
315
316 func (c *Config) unmarshalCore() {
317 s := c.Raw.Section(coreSection)
318 if s.Options.Get(bareKey) == "true" {
319 c.Core.IsBare = true
320 }
321
322 c.Core.Worktree = s.Options.Get(worktreeKey)
323 c.Core.CommentChar = s.Options.Get(commentCharKey)
324
325 if parsed := parseConfigBool(s.Options.Get(protectNTFSKey)); parsed.IsSet() {
326 c.Core.ProtectNTFS = parsed
327 }
328
329 if parsed := parseConfigBool(s.Options.Get(protectHFSKey)); parsed.IsSet() {
330 c.Core.ProtectHFS = parsed
331 }
332 }
333
334 func (c *Config) unmarshalUser() {
335 s := c.Raw.Section(userSection)
336 c.User.Name = s.Options.Get(nameKey)
337 c.User.Email = s.Options.Get(emailKey)
338
339 s = c.Raw.Section(authorSection)
340 c.Author.Name = s.Options.Get(nameKey)
341 c.Author.Email = s.Options.Get(emailKey)
342
343 s = c.Raw.Section(committerSection)
344 c.Committer.Name = s.Options.Get(nameKey)
345 c.Committer.Email = s.Options.Get(emailKey)
346 }
347
348 func (c *Config) unmarshalPack() error {
349 s := c.Raw.Section(packSection)
350 window := s.Options.Get(windowKey)
351 if window == "" {
352 c.Pack.Window = DefaultPackWindow
353 } else {
354 winUint, err := strconv.ParseUint(window, 10, 32)
355 if err != nil {
356 return err
357 }
358 c.Pack.Window = uint(winUint)
359 }
360 return nil
361 }
362
363 func (c *Config) unmarshalRemotes() error {
364 s := c.Raw.Section(remoteSection)
365 for _, sub := range s.Subsections {
366 r := &RemoteConfig{}
367 if err := r.unmarshal(sub); err != nil {
368 return err
369 }
370
371 c.Remotes[r.Name] = r
372 }
373
374 // Apply insteadOf url rules
375 for _, r := range c.Remotes {
376 r.applyURLRules(c.URLs)
377 }
378
379 return nil
380 }
381
382 func (c *Config) unmarshalURLs() error {
383 s := c.Raw.Section(urlSection)
384 for _, sub := range s.Subsections {
385 r := &URL{}
386 if err := r.unmarshal(sub); err != nil {
387 return err
388 }
389
390 c.URLs[r.Name] = r
391 }
392
393 return nil
394 }
395
396 func unmarshalSubmodules(fc *format.Config, submodules map[string]*Submodule) {
397 s := fc.Section(submoduleSection)
398 for _, sub := range s.Subsections {
399 m := &Submodule{}
400 m.unmarshal(sub)
401
402 if err := m.Validate(); errors.Is(err, ErrModuleBadPath) ||
403 errors.Is(err, ErrModuleBadName) {
404 continue
405 }
406
407 submodules[m.Name] = m
408 }
409 }
410
411 func (c *Config) unmarshalBranches() error {
412 bs := c.Raw.Section(branchSection)
413 for _, sub := range bs.Subsections {
414 b := &Branch{}
415
416 if err := b.unmarshal(sub); err != nil {
417 return err
418 }
419
420 c.Branches[b.Name] = b
421 }
422 return nil
423 }
424
425 func (c *Config) unmarshalInit() {
426 s := c.Raw.Section(initSection)
427 c.Init.DefaultBranch = s.Options.Get(defaultBranchKey)
428 }
429
430 // Marshal returns Config encoded as a git-config file.
431 func (c *Config) Marshal() ([]byte, error) {
432 c.marshalCore()
433 c.marshalExtensions()
434 c.marshalUser()
435 c.marshalPack()
436 c.marshalRemotes()
437 c.marshalSubmodules()
438 c.marshalBranches()
439 c.marshalURLs()
440 c.marshalInit()
441
442 buf := bytes.NewBuffer(nil)
443 if err := format.NewEncoder(buf).Encode(c.Raw); err != nil {
444 return nil, err
445 }
446
447 return buf.Bytes(), nil
448 }
449
450 func (c *Config) marshalCore() {
451 s := c.Raw.Section(coreSection)
452 s.SetOption(bareKey, fmt.Sprintf("%t", c.Core.IsBare))
453 if string(c.Core.RepositoryFormatVersion) != "" {
454 s.SetOption(repositoryFormatVersionKey, string(c.Core.RepositoryFormatVersion))
455 }
456
457 if c.Core.Worktree != "" {
458 s.SetOption(worktreeKey, c.Core.Worktree)
459 }
460
461 if c.Core.ProtectNTFS.IsSet() {
462 s.SetOption(protectNTFSKey, c.Core.ProtectNTFS.FormatBool())
463 }
464
465 if c.Core.ProtectHFS.IsSet() {
466 s.SetOption(protectHFSKey, c.Core.ProtectHFS.FormatBool())
467 }
468 }
469
470 func (c *Config) marshalExtensions() {
471 // Extensions are only supported on Version 1, therefore
472 // ignore them otherwise.
473 if c.Core.RepositoryFormatVersion == format.Version_1 {
474 s := c.Raw.Section(extensionsSection)
475 s.SetOption(objectFormat, string(c.Extensions.ObjectFormat))
476 }
477 }
478
479 func (c *Config) marshalUser() {
480 s := c.Raw.Section(userSection)
481 if c.User.Name != "" {
482 s.SetOption(nameKey, c.User.Name)
483 }
484
485 if c.User.Email != "" {
486 s.SetOption(emailKey, c.User.Email)
487 }
488
489 s = c.Raw.Section(authorSection)
490 if c.Author.Name != "" {
491 s.SetOption(nameKey, c.Author.Name)
492 }
493
494 if c.Author.Email != "" {
495 s.SetOption(emailKey, c.Author.Email)
496 }
497
498 s = c.Raw.Section(committerSection)
499 if c.Committer.Name != "" {
500 s.SetOption(nameKey, c.Committer.Name)
501 }
502
503 if c.Committer.Email != "" {
504 s.SetOption(emailKey, c.Committer.Email)
505 }
506 }
507
508 func (c *Config) marshalPack() {
509 s := c.Raw.Section(packSection)
510 if c.Pack.Window != DefaultPackWindow {
511 s.SetOption(windowKey, fmt.Sprintf("%d", c.Pack.Window))
512 }
513 }
514
515 func (c *Config) marshalRemotes() {
516 s := c.Raw.Section(remoteSection)
517 newSubsections := make(format.Subsections, 0, len(c.Remotes))
518 added := make(map[string]bool)
519 for _, subsection := range s.Subsections {
520 if remote, ok := c.Remotes[subsection.Name]; ok {
521 newSubsections = append(newSubsections, remote.marshal())
522 added[subsection.Name] = true
523 }
524 }
525
526 remoteNames := make([]string, 0, len(c.Remotes))
527 for name := range c.Remotes {
528 remoteNames = append(remoteNames, name)
529 }
530
531 sort.Strings(remoteNames)
532
533 for _, name := range remoteNames {
534 if !added[name] {
535 newSubsections = append(newSubsections, c.Remotes[name].marshal())
536 }
537 }
538
539 s.Subsections = newSubsections
540 }
541
542 func (c *Config) marshalSubmodules() {
543 s := c.Raw.Section(submoduleSection)
544 s.Subsections = make(format.Subsections, len(c.Submodules))
545
546 var i int
547 for _, r := range c.Submodules {
548 section := r.marshal()
549 // the submodule section at config is a subset of the .gitmodule file
550 // we should remove the non-valid options for the config file.
551 section.RemoveOption(pathKey)
552 s.Subsections[i] = section
553 i++
554 }
555 }
556
557 func (c *Config) marshalBranches() {
558 s := c.Raw.Section(branchSection)
559 newSubsections := make(format.Subsections, 0, len(c.Branches))
560 added := make(map[string]bool)
561 for _, subsection := range s.Subsections {
562 if branch, ok := c.Branches[subsection.Name]; ok {
563 newSubsections = append(newSubsections, branch.marshal())
564 added[subsection.Name] = true
565 }
566 }
567
568 branchNames := make([]string, 0, len(c.Branches))
569 for name := range c.Branches {
570 branchNames = append(branchNames, name)
571 }
572
573 sort.Strings(branchNames)
574
575 for _, name := range branchNames {
576 if !added[name] {
577 newSubsections = append(newSubsections, c.Branches[name].marshal())
578 }
579 }
580
581 s.Subsections = newSubsections
582 }
583
584 func (c *Config) marshalURLs() {
585 s := c.Raw.Section(urlSection)
586 s.Subsections = make(format.Subsections, len(c.URLs))
587
588 var i int
589 for _, r := range c.URLs {
590 section := r.marshal()
591 // the submodule section at config is a subset of the .gitmodule file
592 // we should remove the non-valid options for the config file.
593 s.Subsections[i] = section
594 i++
595 }
596 }
597
598 func (c *Config) marshalInit() {
599 s := c.Raw.Section(initSection)
600 if c.Init.DefaultBranch != "" {
601 s.SetOption(defaultBranchKey, c.Init.DefaultBranch)
602 }
603 }
604
605 // RemoteConfig contains the configuration for a given remote repository.
606 type RemoteConfig struct {
607 // Name of the remote
608 Name string
609 // URLs the URLs of a remote repository. It must be non-empty. Fetch will
610 // always use the first URL, while push will use all of them.
611 URLs []string
612 // Mirror indicates that the repository is a mirror of remote.
613 Mirror bool
614
615 // insteadOfRulesApplied have urls been modified
616 insteadOfRulesApplied bool
617 // originalURLs are the urls before applying insteadOf rules
618 originalURLs []string
619
620 // Fetch the default set of "refspec" for fetch operation
621 Fetch []RefSpec
622
623 // raw representation of the subsection, filled by marshal or unmarshal are
624 // called
625 raw *format.Subsection
626 }
627
628 // Validate validates the fields and sets the default values.
629 func (c *RemoteConfig) Validate() error {
630 if c.Name == "" {
631 return ErrRemoteConfigEmptyName
632 }
633
634 if len(c.URLs) == 0 {
635 return ErrRemoteConfigEmptyURL
636 }
637
638 for _, r := range c.Fetch {
639 if err := r.Validate(); err != nil {
640 return err
641 }
642 }
643
644 if len(c.Fetch) == 0 {
645 c.Fetch = []RefSpec{RefSpec(fmt.Sprintf(DefaultFetchRefSpec, c.Name))}
646 }
647
648 return plumbing.NewRemoteHEADReferenceName(c.Name).Validate()
649 }
650
651 func (c *RemoteConfig) unmarshal(s *format.Subsection) error {
652 c.raw = s
653
654 fetch := []RefSpec{}
655 for _, f := range c.raw.Options.GetAll(fetchKey) {
656 rs := RefSpec(f)
657 if err := rs.Validate(); err != nil {
658 return err
659 }
660
661 fetch = append(fetch, rs)
662 }
663
664 c.Name = c.raw.Name
665 c.URLs = append([]string(nil), c.raw.Options.GetAll(urlKey)...)
666 c.URLs = append(c.URLs, c.raw.Options.GetAll(pushurlKey)...)
667 c.Fetch = fetch
668 c.Mirror = c.raw.Options.Get(mirrorKey) == "true"
669
670 return nil
671 }
672
673 func (c *RemoteConfig) marshal() *format.Subsection {
674 if c.raw == nil {
675 c.raw = &format.Subsection{}
676 }
677
678 c.raw.Name = c.Name
679 if len(c.URLs) == 0 {
680 c.raw.RemoveOption(urlKey)
681 } else {
682 urls := c.URLs
683 if c.insteadOfRulesApplied {
684 urls = c.originalURLs
685 }
686
687 c.raw.SetOption(urlKey, urls...)
688 }
689
690 if len(c.Fetch) == 0 {
691 c.raw.RemoveOption(fetchKey)
692 } else {
693 var values []string
694 for _, rs := range c.Fetch {
695 values = append(values, rs.String())
696 }
697
698 c.raw.SetOption(fetchKey, values...)
699 }
700
701 if c.Mirror {
702 c.raw.SetOption(mirrorKey, strconv.FormatBool(c.Mirror))
703 }
704
705 return c.raw
706 }
707
708 func (c *RemoteConfig) IsFirstURLLocal() bool {
709 return url.IsLocalEndpoint(c.URLs[0])
710 }
711
712 func (c *RemoteConfig) applyURLRules(urlRules map[string]*URL) {
713 // save original urls
714 originalURLs := make([]string, len(c.URLs))
715 copy(originalURLs, c.URLs)
716
717 for i, url := range c.URLs {
718 if matchingURLRule := findLongestInsteadOfMatch(url, urlRules); matchingURLRule != nil {
719 c.URLs[i] = matchingURLRule.ApplyInsteadOf(c.URLs[i])
720 c.insteadOfRulesApplied = true
721 }
722 }
723
724 if c.insteadOfRulesApplied {
725 c.originalURLs = originalURLs
726 }
727 }