1package config
2
3import (
4	"errors"
5
6	"github.com/go-git/go-git/v5/plumbing"
7	format "github.com/go-git/go-git/v5/plumbing/format/config"
8)
9
10var (
11	errBranchEmptyName     = errors.New("branch config: empty name")
12	errBranchInvalidMerge  = errors.New("branch config: invalid merge")
13	errBranchInvalidRebase = errors.New("branch config: rebase must be one of 'true' or 'interactive'")
14)
15
16// Branch contains information on the
17// local branches and which remote to track
18type Branch struct {
19	// Name of branch
20	Name string
21	// Remote name of remote to track
22	Remote string
23	// Merge is the local refspec for the branch
24	Merge plumbing.ReferenceName
25	// Rebase instead of merge when pulling. Valid values are
26	// "true" and "interactive".  "false" is undocumented and
27	// typically represented by the non-existence of this field
28	Rebase string
29
30	raw *format.Subsection
31}
32
33// Validate validates fields of branch
34func (b *Branch) Validate() error {
35	if b.Name == "" {
36		return errBranchEmptyName
37	}
38
39	if b.Merge != "" && !b.Merge.IsBranch() {
40		return errBranchInvalidMerge
41	}
42
43	if b.Rebase != "" &&
44		b.Rebase != "true" &&
45		b.Rebase != "interactive" &&
46		b.Rebase != "false" {
47		return errBranchInvalidRebase
48	}
49
50	return nil
51}
52
53func (b *Branch) marshal() *format.Subsection {
54	if b.raw == nil {
55		b.raw = &format.Subsection{}
56	}
57
58	b.raw.Name = b.Name
59
60	if b.Remote == "" {
61		b.raw.RemoveOption(remoteSection)
62	} else {
63		b.raw.SetOption(remoteSection, b.Remote)
64	}
65
66	if b.Merge == "" {
67		b.raw.RemoveOption(mergeKey)
68	} else {
69		b.raw.SetOption(mergeKey, string(b.Merge))
70	}
71
72	if b.Rebase == "" {
73		b.raw.RemoveOption(rebaseKey)
74	} else {
75		b.raw.SetOption(rebaseKey, b.Rebase)
76	}
77
78	return b.raw
79}
80
81func (b *Branch) unmarshal(s *format.Subsection) error {
82	b.raw = s
83
84	b.Name = b.raw.Name
85	b.Remote = b.raw.Options.Get(remoteSection)
86	b.Merge = plumbing.ReferenceName(b.raw.Options.Get(mergeKey))
87	b.Rebase = b.raw.Options.Get(rebaseKey)
88
89	return b.Validate()
90}
91