Debian Codegraph @

internal/command/config.go

raw symbols SCIP
1 package command
2
3 import (
4 "fmt"
5
6 "github.com/isacikgoz/gitbatch/internal/git"
7 )
8
9 // ConfigOptions defines the rules for commit operation
10 type ConfigOptions struct {
11 // Section
12 Section string
13 // Option
14 Option string
15 // Site should be Global or Local
16 Site ConfigSite
17 // Mode is the command mode
18 CommandMode Mode
19 }
20
21 // ConfigSite defines a string type for the site.
22 type ConfigSite string
23
24 const (
25 // ConfigSiteLocal defines a local config.
26 ConfigSiteLocal ConfigSite = "local"
27
28 // ConfigSiteGlobal defines a global config.
29 ConfigSiteGlobal ConfigSite = "global"
30 )
31
32 // Config adds or reads config of a repository
33 func Config(r *git.Repository, o *ConfigOptions) (value string, err error) {
34 // here we configure config operation
35
36 switch o.CommandMode {
37 case ModeLegacy:
38 return configWithGit(r, o)
39 case ModeNative:
40 return configWithGoGit(r, o)
41 }
42 return value, fmt.Errorf("unhandled config operation")
43 }
44
45 // configWithGit is simply a bare git config --site <option>.<section> command which is flexible
46 func configWithGit(r *git.Repository, options *ConfigOptions) (value string, err error) {
47 args := make([]string, 0)
48 args = append(args, "config")
49 if len(string(options.Site)) > 0 {
50 args = append(args, "--"+string(options.Site))
51 }
52 args = append(args, "--get")
53 args = append(args, options.Section+"."+options.Option)
54 // parse options to command line arguments
55 out, err := Run(r.AbsPath, "git", args)
56 if err != nil {
57 return out, err
58 }
59 // till this step everything should be ok
60 return out, nil
61 }
62
63 // commitWithGoGit is the primary commit method
64 func configWithGoGit(r *git.Repository, options *ConfigOptions) (value string, err error) {
65 // TODO: add global search
66 config, err := r.Repo.Config()
67 if err != nil {
68 return value, err
69 }
70 return config.Raw.Section(options.Section).Option(options.Option), nil
71 }
72
73 // AddConfig adds an entry on the ConfigOptions field.
74 func AddConfig(r *git.Repository, options *ConfigOptions, value string) (err error) {
75 return addConfigWithGit(r, options, value)
76
77 }
78
79 // addConfigWithGit is simply a bare git config --add <option> command which is flexible
80 func addConfigWithGit(r *git.Repository, options *ConfigOptions, value string) (err error) {
81 args := make([]string, 0)
82 args = append(args, "config")
83 if len(string(options.Site)) > 0 {
84 args = append(args, "--"+string(options.Site))
85 }
86 args = append(args, "--add")
87 args = append(args, options.Section+"."+options.Option)
88 if len(value) > 0 {
89 args = append(args, value)
90 }
91 if _, err := Run(r.AbsPath, "git", args); err != nil {
92 return err
93 }
94 // till this step everything should be ok
95 return r.Refresh()
96 }