1 // Package config collects together all configuration settings
2 // NOTE: Subject to change, do not rely on this package from outside git-lfs source
12 "github.com/git-lfs/git-lfs/fs"
13 "github.com/git-lfs/git-lfs/git"
14 "github.com/git-lfs/git-lfs/tools"
15 "github.com/rubyist/tracerx"
19 ShowConfigWarnings = false
20 defaultRemote = "origin"
21 gitConfigWarningPrefix = "lfs."
24 type Configuration struct {
25 // Os provides a `*Environment` used to access to the system's
26 // environment through os.Getenv. It is the point of entry for all
27 // system environment configuration.
30 // Git provides a `*Environment` used to access to the various levels of
31 // `.gitconfig`'s. It is the point of entry for all Git environment
38 // gitConfig can fetch or modify the current Git config and track the Git
40 gitConfig *git.Configuration
47 loading sync.Mutex // guards initialization of gitConfig and remotes
48 loadingGit sync.Mutex // guards initialization of local git and working dirs
50 extensions map[string]Extension
53 func New() *Configuration {
57 func NewIn(workdir, gitdir string) *Configuration {
58 gitConf := git.NewConfig(workdir, gitdir)
60 Os: EnvironmentOf(NewOsFetcher()),
64 if len(gitConf.WorkDir) > 0 {
65 c.gitDir = &gitConf.GitDir
66 c.workDir = gitConf.WorkDir
69 c.Git = &delayedEnvironment{
70 callback: func() Environment {
71 sources, err := gitConf.Sources(filepath.Join(c.LocalWorkingDir(), ".lfsconfig"))
73 fmt.Fprintf(os.Stderr, "Error reading git config: %s\n", err)
75 return c.readGitConfig(sources...)
81 func (c *Configuration) readGitConfig(gitconfigs ...*git.ConfigurationSource) Environment {
82 gf, extensions, uniqRemotes := readGitConfig(gitconfigs...)
83 c.extensions = extensions
84 c.remotes = make([]string, 0, len(uniqRemotes))
85 for remote := range uniqRemotes {
86 c.remotes = append(c.remotes, remote)
89 return EnvironmentOf(gf)
92 // Values is a convenience type used to call the NewFromValues function. It
93 // specifies `Git` and `Env` maps to use as mock values, instead of calling out
94 // to real `.gitconfig`s and the `os.Getenv` function.
96 // Git and Os are the stand-in maps used to provide values for their
97 // respective environments.
98 Git, Os map[string][]string
101 // NewFrom returns a new `*config.Configuration` that reads both its Git
102 // and Enviornment-level values from the ones provided instead of the actual
103 // `.gitconfig` file or `os.Getenv`, respectively.
105 // This method should only be used during testing.
106 func NewFrom(v Values) *Configuration {
108 Os: EnvironmentOf(mapFetcher(v.Os)),
109 gitConfig: git.NewConfig("", ""),
111 c.Git = &delayedEnvironment{
112 callback: func() Environment {
113 source := &git.ConfigurationSource{
114 Lines: make([]string, 0, len(v.Git)),
117 for key, values := range v.Git {
118 for _, value := range values {
119 fmt.Printf("Config: %s=%s\n", key, value)
120 source.Lines = append(source.Lines, fmt.Sprintf("%s=%s", key, value))
124 return c.readGitConfig(source)
130 // BasicTransfersOnly returns whether to only allow "basic" HTTP transfers.
131 // Default is false, including if the lfs.basictransfersonly is invalid
132 func (c *Configuration) BasicTransfersOnly() bool {
133 return c.Git.Bool("lfs.basictransfersonly", false)
136 // TusTransfersAllowed returns whether to only use "tus.io" HTTP transfers.
137 // Default is false, including if the lfs.tustransfers is invalid
138 func (c *Configuration) TusTransfersAllowed() bool {
139 return c.Git.Bool("lfs.tustransfers", false)
142 func (c *Configuration) FetchIncludePaths() []string {
143 patterns, _ := c.Git.Get("lfs.fetchinclude")
144 return tools.CleanPaths(patterns, ",")
147 func (c *Configuration) FetchExcludePaths() []string {
148 patterns, _ := c.Git.Get("lfs.fetchexclude")
149 return tools.CleanPaths(patterns, ",")
152 func (c *Configuration) CurrentRef() *git.Ref {
154 defer c.loading.Unlock()
156 r, err := git.CurrentRef()
158 tracerx.Printf("Error loading current ref: %s", err)
167 func (c *Configuration) IsDefaultRemote() bool {
168 return c.Remote() == defaultRemote
171 // Remote returns the default remote based on:
172 // 1. The currently tracked remote branch, if present
173 // 2. Any other SINGLE remote defined in .git/config
174 // 3. Use "origin" as a fallback.
175 // Results are cached after the first hit.
176 func (c *Configuration) Remote() string {
177 ref := c.CurrentRef()
180 defer c.loading.Unlock()
182 if c.currentRemote == nil {
183 if len(ref.Name) == 0 {
184 c.currentRemote = &defaultRemote
188 if remote, ok := c.Git.Get(fmt.Sprintf("branch.%s.remote", ref.Name)); ok {
189 // try tracking remote
190 c.currentRemote = &remote
191 } else if remotes := c.Remotes(); len(remotes) == 1 {
192 // use only remote if there is only 1
193 c.currentRemote = &remotes[0]
195 // fall back to default :(
196 c.currentRemote = &defaultRemote
199 return *c.currentRemote
202 func (c *Configuration) PushRemote() string {
203 ref := c.CurrentRef()
205 defer c.loading.Unlock()
207 if c.pushRemote == nil {
208 if remote, ok := c.Git.Get(fmt.Sprintf("branch.%s.pushRemote", ref.Name)); ok {
209 c.pushRemote = &remote
210 } else if remote, ok := c.Git.Get("remote.pushDefault"); ok {
211 c.pushRemote = &remote
217 c.pushRemote = &remote
224 func (c *Configuration) SetValidRemote(name string) error {
225 if err := git.ValidateRemote(name); err != nil {
232 func (c *Configuration) SetValidPushRemote(name string) error {
233 if err := git.ValidateRemote(name); err != nil {
236 c.SetPushRemote(name)
240 func (c *Configuration) SetRemote(name string) {
241 c.currentRemote = &name
244 func (c *Configuration) SetPushRemote(name string) {
248 func (c *Configuration) Remotes() []string {
253 func (c *Configuration) Extensions() map[string]Extension {
258 // SortedExtensions gets the list of extensions ordered by Priority
259 func (c *Configuration) SortedExtensions() ([]Extension, error) {
260 return SortExtensions(c.Extensions())
263 func (c *Configuration) SkipDownloadErrors() bool {
264 return c.Os.Bool("GIT_LFS_SKIP_DOWNLOAD_ERRORS", false) || c.Git.Bool("lfs.skipdownloaderrors", false)
267 func (c *Configuration) SetLockableFilesReadOnly() bool {
268 return c.Os.Bool("GIT_LFS_SET_LOCKABLE_READONLY", true) && c.Git.Bool("lfs.setlockablereadonly", true)
271 func (c *Configuration) HookDir() string {
272 if git.IsGitVersionAtLeast("2.9.0") {
273 hp, ok := c.Git.Get("core.hooksPath")
278 return filepath.Join(c.LocalGitDir(), "hooks")
281 func (c *Configuration) InRepo() bool {
282 return len(c.LocalGitDir()) > 0
285 func (c *Configuration) LocalWorkingDir() string {
290 func (c *Configuration) LocalGitDir() string {
295 func (c *Configuration) loadGitDirs() {
297 defer c.loadingGit.Unlock()
303 gitdir, workdir, err := git.GitAndRootDirs()
305 errMsg := err.Error()
306 tracerx.Printf("Error running 'git rev-parse': %s", errMsg)
307 if !strings.Contains(strings.ToLower(errMsg),
308 "not a git repository") {
309 fmt.Fprintf(os.Stderr, "Error: %s\n", errMsg)
314 gitdir = tools.ResolveSymlinks(gitdir)
316 c.workDir = tools.ResolveSymlinks(workdir)
319 func (c *Configuration) LocalGitStorageDir() string {
320 return c.Filesystem().GitStorageDir
323 func (c *Configuration) LocalReferenceDirs() []string {
324 return c.Filesystem().ReferenceDirs
327 func (c *Configuration) LFSStorageDir() string {
328 return c.Filesystem().LFSStorageDir
331 func (c *Configuration) LFSObjectDir() string {
332 return c.Filesystem().LFSObjectDir()
335 func (c *Configuration) LFSObjectExists(oid string, size int64) bool {
336 return c.Filesystem().ObjectExists(oid, size)
339 func (c *Configuration) EachLFSObject(fn func(fs.Object) error) error {
340 return c.Filesystem().EachObject(fn)
343 func (c *Configuration) LocalLogDir() string {
344 return c.Filesystem().LogDir()
347 func (c *Configuration) TempDir() string {
348 return c.Filesystem().TempDir()
351 func (c *Configuration) Filesystem() *fs.Filesystem {
354 defer c.loading.Unlock()
357 lfsdir, _ := c.Git.Get("lfs.storage")
369 func (c *Configuration) Cleanup() error {
371 defer c.loading.Unlock()
372 return c.fs.Cleanup()
375 func (c *Configuration) OSEnv() Environment {
379 func (c *Configuration) GitEnv() Environment {
383 func (c *Configuration) GitConfig() *git.Configuration {
387 func (c *Configuration) FindGitGlobalKey(key string) string {
388 return c.gitConfig.FindGlobal(key)
391 func (c *Configuration) FindGitSystemKey(key string) string {
392 return c.gitConfig.FindSystem(key)
395 func (c *Configuration) FindGitLocalKey(key string) string {
396 return c.gitConfig.FindLocal(key)
399 func (c *Configuration) SetGitGlobalKey(key, val string) (string, error) {
400 return c.gitConfig.SetGlobal(key, val)
403 func (c *Configuration) SetGitSystemKey(key, val string) (string, error) {
404 return c.gitConfig.SetSystem(key, val)
407 func (c *Configuration) SetGitLocalKey(key, val string) (string, error) {
408 return c.gitConfig.SetLocal(key, val)
411 func (c *Configuration) UnsetGitGlobalSection(key string) (string, error) {
412 return c.gitConfig.UnsetGlobalSection(key)
415 func (c *Configuration) UnsetGitSystemSection(key string) (string, error) {
416 return c.gitConfig.UnsetSystemSection(key)
419 func (c *Configuration) UnsetGitLocalSection(key string) (string, error) {
420 return c.gitConfig.UnsetLocalSection(key)
423 func (c *Configuration) UnsetGitLocalKey(key string) (string, error) {
424 return c.gitConfig.UnsetLocalKey(key)
427 // loadGitConfig is a temporary measure to support legacy behavior dependent on
428 // accessing properties set by ReadGitConfig, namely:
433 // Since the *gitEnvironment is responsible for setting these values on the
434 // (*config.Configuration) instance, we must call that method, if it exists.
436 // loadGitConfig returns a bool returning whether or not `loadGitConfig` was
437 // called AND the method did not return early.
438 func (c *Configuration) loadGitConfig() {
439 if g, ok := c.Git.(*delayedEnvironment); ok {
444 // CurrentCommitter returns the name/email that would be used to author a commit
445 // with this configuration. In particular, the "user.name" and "user.email"
446 // configuration values are used
447 func (c *Configuration) CurrentCommitter() (name, email string) {
448 name, _ = c.Git.Get("user.name")
449 email, _ = c.Git.Get("user.email")