[SQUASHED] ignore-tracked-parent-dir-configs

This commit is contained in:
Stefan Haller committed 2026-11-15 18:07:56 +01:00
1 parent 23f18c1057
commit 1a92d4f816
12 files changed
+557 -7

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ If you want to change the config directory:
- MacOS: `export XDG_CONFIG_HOME="$HOME/.config"`
In addition to the global config file you can create repo-specific config files in `<repo>/.git/lazygit.yml`. Settings in these files override settings in the global config file. In addition, files called `.lazygit.yml` in any of the parent directories of a repo will also be loaded; this can be useful if you have settings that you want to apply to a group of repositories.
In addition to the global config file you can create repo-specific config files in `<repo>/.git/lazygit.yml`. Settings in these files override settings in the global config file. In addition, files called `.lazygit.yml` in any of the parent directories of a repo will also be loaded; this can be useful if you have settings that you want to apply to a group of repositories. Such a file is ignored if git tracks it in a repository that has a `.git` in one of the file's parent directories (including its own directory). For example, when you open a submodule, a `.lazygit.yml` that the superproject tracks is ignored. Otherwise, anybody who can commit to that repository could make lazygit run commands of their choosing.
JSON schema is available for `config.yml` so that IntelliSense in Visual Studio Code (completion and error checking) is automatically enabled when the [YAML Red Hat][yaml] extension is installed. However, note that automatic schema detection only works if your config file is in one of the standard paths mentioned above. If you override the path to the file, you can still make IntelliSense work by adding
@@ -0,0 +1,94 @@
package git_commands
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
)
// IsTrackedByEnclosingRepo reports whether git tracks the file at path in the
// repository whose working tree contains it. If neither the file's directory
// nor any directory above it has a .git, there is no such repository, and we
// don't run git at all.
//
// We can't ask git about path directly, because the index may spell it
// differently. On a case-insensitive file system, a tracked .LAZYGIT.YML is the
// file .lazygit.yml, and on macOS, the index may have a directory name in a
// different Unicode normalization form than path. So we ask git for all tracked
// files that have path's base name in any letter case, and check whether one of
// them is the same file as path. This only works if the base name has the same
// spelling in path and in the index, so it must consist of ASCII characters.
func IsTrackedByEnclosingRepo(cmd oscommands.ICmdObjBuilder, path string) (bool, error) {
repoDir, found := findDirWithGitEntry(filepath.Dir(path))
if !found {
return false, nil
}
baseName := filepath.Base(path)
if strings.ContainsFunc(baseName, func(r rune) bool { return r > unicode.MaxASCII }) {
return false, fmt.Errorf("can't tell whether git tracks %s, because its name isn't ASCII", path)
}
pathInfo, err := os.Lstat(path)
if err != nil {
return false, err
}
cmdObj := cmd.New(
NewGitCmd("ls-files").
Arg("-z", "--", ":(icase,glob)**/"+escapeGlob(baseName)).
Dir(repoDir).
ToArgv(),
).DontLog()
// With GIT_LITERAL_PATHSPECS set, git would look for a file whose name
// starts with ":(icase,glob)", and find nothing.
stdout, _, err := ForOtherRepo(cmdObj).RemoveEnvVar("GIT_LITERAL_PATHSPECS").RunWithOutputs()
if err != nil {
return false, err
}
for _, trackedPath := range strings.Split(stdout, "\x00") {
if trackedPath == "" {
continue
}
trackedInfo, err := os.Lstat(filepath.Join(repoDir, trackedPath))
if err == nil && os.SameFile(trackedInfo, pathInfo) {
return true, nil
}
}
return false, nil
}
// Returns the first directory from dir upwards that has a .git; this is the
// root of the working tree that dir is in.
func findDirWithGitEntry(dir string) (string, bool) {
for {
// If we can't tell whether there is a .git, we let git decide.
if _, err := os.Lstat(filepath.Join(dir, ".git")); !errors.Is(err, os.ErrNotExist) {
return dir, true
}
parent := filepath.Dir(dir)
if parent == dir {
return "", false
}
dir = parent
}
}
func escapeGlob(name string) string {
var result strings.Builder
for _, r := range name {
if strings.ContainsRune(`\*?[`, r) {
result.WriteRune('\\')
}
result.WriteRune(r)
}
return result.String()
}
@@ -0,0 +1,174 @@
package git_commands
import (
"os"
"os/exec"
"path/filepath"
"testing"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/stretchr/testify/assert"
)
func TestIsTrackedByEnclosingRepo(t *testing.T) {
scenarios := []struct {
testName string
// Sets up a repo (or not) in the fixture's dir, and returns the path to
// ask about
setup func(f repoFixture) string
expected bool
expectError bool
}{
{
testName: "Not in a repo",
setup: func(f repoFixture) string {
return f.writeFile(".lazygit.yml")
},
expected: false,
},
{
testName: "Untracked file",
setup: func(f repoFixture) string {
f.git("init")
return f.writeFile(".lazygit.yml")
},
expected: false,
},
{
testName: "Tracked file",
setup: func(f repoFixture) string {
f.git("init")
path := f.writeFile(".lazygit.yml")
f.git("add", ".lazygit.yml")
return path
},
expected: true,
},
{
testName: "Tracked file in a subdirectory",
setup: func(f repoFixture) string {
f.git("init")
path := f.writeFile("sub/dir/.lazygit.yml")
f.git("add", "sub/dir/.lazygit.yml")
return path
},
expected: true,
},
{
testName: "Tracked file whose name differs in case",
setup: func(f repoFixture) string {
f.git("init")
f.writeFile(".LAZYGIT.YML")
f.git("add", ".LAZYGIT.YML")
path := filepath.Join(f.dir, ".lazygit.yml")
if _, err := os.Lstat(path); err != nil {
f.t.Skip("the file system is case-sensitive")
}
return path
},
expected: true,
},
{
testName: "Tracked file in a directory whose name the index has in a different Unicode normalization",
setup: func(f repoFixture) string {
f.git("init")
// "Ü" as "U" plus a combining diaeresis (NFD); with precomposeunicode
// turned off, git add keeps this spelling in the index
f.writeFile("Ü/.lazygit.yml")
f.git("-c", "core.precomposeunicode=false", "add", ".")
// "Ü" as a single code point (NFC)
path := filepath.Join(f.dir, "Ü", ".lazygit.yml")
if _, err := os.Lstat(path); err != nil {
f.t.Skip("the file system treats the two spellings as different names")
}
return path
},
expected: true,
},
{
testName: "Tracked file with glob characters in its name",
setup: func(f repoFixture) string {
f.git("init")
path := f.writeFile("[x].yml")
f.git("add", "[x].yml")
return path
},
expected: true,
},
{
testName: "Name that isn't ASCII",
setup: func(f repoFixture) string {
f.git("init")
return f.writeFile("ü.yml")
},
expectError: true,
},
{
testName: "Tracked file with GIT_LITERAL_PATHSPECS set",
setup: func(f repoFixture) string {
f.git("init")
path := f.writeFile(".lazygit.yml")
f.git("add", ".lazygit.yml")
f.t.Setenv("GIT_LITERAL_PATHSPECS", "1")
return path
},
expected: true,
},
{
testName: "Tracked file with GIT_DIR pointing at another repo",
setup: func(f repoFixture) string {
f.git("init", "other")
f.git("init", "repo")
path := f.writeFile("repo/.lazygit.yml")
f.git("-C", "repo", "add", ".lazygit.yml")
f.t.Setenv("GIT_DIR", filepath.Join(f.dir, "other", ".git"))
return path
},
expected: true,
},
}
for _, s := range scenarios {
t.Run(s.testName, func(t *testing.T) {
// Keep the user's git config (e.g. a global gitignore) out of the test
globalConfig := repoFixture{t: t, dir: t.TempDir()}.writeFile("gitconfig")
t.Setenv("GIT_CONFIG_GLOBAL", globalConfig)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
path := s.setup(repoFixture{t: t, dir: t.TempDir()})
isTracked, err := IsTrackedByEnclosingRepo(oscommands.NewDummyOSCommand().Cmd, path)
if s.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, s.expected, isTracked)
})
}
}
type repoFixture struct {
t *testing.T
dir string
}
func (f repoFixture) git(args ...string) {
f.t.Helper()
output, err := exec.Command("git", append([]string{"-C", f.dir}, args...)...).CombinedOutput()
if !assert.NoError(f.t, err, string(output)) {
f.t.FailNow()
}
}
// Creates an empty file at relPath below the fixture's dir, and returns its
// absolute path
func (f repoFixture) writeFile(relPath string) string {
f.t.Helper()
path := filepath.Join(f.dir, relPath)
if !assert.NoError(f.t, os.MkdirAll(filepath.Dir(path), 0o755)) ||
!assert.NoError(f.t, os.WriteFile(path, []byte{}, 0o644)) {
f.t.FailNow()
}
return path
}
+24 -3
View File
@@ -46,6 +46,7 @@ type AppConfigurer interface {
GetUserConfig() *UserConfig
GetUserConfigPaths() []string
GetIgnoredUserConfigPaths() []string
GetUserConfigDir() string
ReloadUserConfigForRepo(repoConfigFiles []*ConfigFile) error
ReloadChangedUserConfigFiles() (error, bool)
@@ -66,10 +67,16 @@ const (
)
type ConfigFile struct {
Path string
Policy ConfigFilePolicy
Path string
Policy ConfigFilePolicy
// If set, it is called each time the file is about to be loaded (but not if
// it doesn't exist), and the file is not loaded if it returns true.
ShouldIgnore func(path string) bool
modDate time.Time
exists bool
ignored bool
}
// NewAppConfig makes a new app config
@@ -179,6 +186,7 @@ func loadUserConfig(configFiles []*ConfigFile, base *UserConfig, isGuiInitialize
case ConfigFilePolicySkipIfMissing:
configFile.exists = false
configFile.ignored = false
continue
case ConfigFilePolicyCreateIfMissing:
@@ -201,6 +209,11 @@ func loadUserConfig(configFiles []*ConfigFile, base *UserConfig, isGuiInitialize
}
}
configFile.ignored = configFile.ShouldIgnore != nil && configFile.ShouldIgnore(path)
if configFile.ignored {
continue
}
content, err := os.ReadFile(path)
if err != nil {
return nil, err
@@ -737,7 +750,15 @@ func (c *AppConfig) SaveCachedGithubPullRequests(repoPath string, pullRequests [
func (c *AppConfig) GetUserConfigPaths() []string {
return lo.FilterMap(c.userConfigFiles, func(f *ConfigFile, _ int) (string, bool) {
return f.Path, f.exists
return f.Path, f.exists && !f.ignored
})
}
// The paths of the config files that exist, but weren't loaded because their
// ShouldIgnore function returned true.
func (c *AppConfig) GetIgnoredUserConfigPaths() []string {
return lo.FilterMap(c.userConfigFiles, func(f *ConfigFile, _ int) (string, bool) {
return f.Path, f.ignored
})
}
+52
View File
@@ -1,6 +1,8 @@
package config
import (
"os"
"path/filepath"
"runtime"
"testing"
@@ -979,3 +981,53 @@ func TestBranchColorsMigration(t *testing.T) {
})
}
}
func TestIgnoredConfigFiles(t *testing.T) {
dir := t.TempDir()
loadedPath := filepath.Join(dir, "loaded.yml")
ignoredPath := filepath.Join(dir, "ignored.yml")
assert.NoError(t, os.WriteFile(loadedPath, []byte("os:\n edit: loaded-editor\n"), 0o644))
assert.NoError(t, os.WriteFile(ignoredPath, []byte("os:\n edit: ignored-editor\n"), 0o644))
shouldIgnore := func(path string) bool { return path == ignoredPath }
appConfig := NewDummyAppConfig()
err := appConfig.ReloadUserConfigForRepo([]*ConfigFile{
{Path: loadedPath, Policy: ConfigFilePolicySkipIfMissing, ShouldIgnore: shouldIgnore},
{Path: ignoredPath, Policy: ConfigFilePolicySkipIfMissing, ShouldIgnore: shouldIgnore},
})
assert.NoError(t, err)
assert.Equal(t, "loaded-editor", appConfig.GetUserConfig().OS.Edit)
assert.Equal(t, []string{loadedPath}, appConfig.GetUserConfigPaths())
assert.Equal(t, []string{ignoredPath}, appConfig.GetIgnoredUserConfigPaths())
}
func TestIgnoredConfigFileOnReload(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yml")
appConfig := NewDummyAppConfig()
err := appConfig.ReloadUserConfigForRepo([]*ConfigFile{
{Path: path, Policy: ConfigFilePolicySkipIfMissing, ShouldIgnore: func(string) bool { return true }},
})
assert.NoError(t, err)
assert.Empty(t, appConfig.GetIgnoredUserConfigPaths())
// A file that appears later is checked too
assert.NoError(t, os.WriteFile(path, []byte("os:\n edit: my-editor\n"), 0o644))
err, didChange := appConfig.ReloadChangedUserConfigFiles()
assert.NoError(t, err)
assert.True(t, didChange)
assert.NotEqual(t, "my-editor", appConfig.GetUserConfig().OS.Edit)
assert.Equal(t, []string{path}, appConfig.GetIgnoredUserConfigPaths())
// An ignored file that doesn't change doesn't cause a reload
err, didChange = appConfig.ReloadChangedUserConfigFiles()
assert.NoError(t, err)
assert.False(t, didChange)
// A deleted file is no longer reported as ignored
assert.NoError(t, os.Remove(path))
err, didChange = appConfig.ReloadChangedUserConfigFiles()
assert.NoError(t, err)
assert.True(t, didChange)
assert.Empty(t, appConfig.GetIgnoredUserConfigPaths())
}
+31 -2
View File
@@ -375,6 +375,7 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context
gui.resetHelpersAndControllers()
gui.resetKeybindings()
gui.toastIgnoredConfigFiles()
gui.g.SetFocusHandler(func(Focused bool) error {
if Focused {
@@ -387,6 +388,7 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context
reloadErr = gui.onUserConfigLoaded()
gui.reloadSidePanels()
gui.resetKeybindings()
gui.toastIgnoredConfigFiles()
if err := gui.checkForChangedConfigsThatDontAutoReload(oldConfig, gui.Config.GetUserConfig()); err != nil {
return err
@@ -488,8 +490,9 @@ func (gui *Gui) getPerRepoConfigFiles() []*config.ConfigFile {
dir := filepath.Dir(prevDir)
for dir != prevDir {
repoConfigFiles = utils.Prepend(repoConfigFiles, &config.ConfigFile{
Path: filepath.Join(dir, ".lazygit.yml"),
Policy: config.ConfigFilePolicySkipIfMissing,
Path: filepath.Join(dir, ".lazygit.yml"),
Policy: config.ConfigFilePolicySkipIfMissing,
ShouldIgnore: gui.isTrackedByEnclosingRepo,
})
prevDir = dir
dir = filepath.Dir(dir)
@@ -497,6 +500,32 @@ func (gui *Gui) getPerRepoConfigFiles() []*config.ConfigFile {
return repoConfigFiles
}
// A .lazygit.yml in a parent directory is for config that the user wants to
// apply to all repos below that directory. If git tracks the file, it comes
// from a repository's content instead; for example, the parent directories of
// a submodule include the superproject's working tree. Anybody who can commit
// to that repository could then make lazygit run commands of their choosing,
// so we don't load such a file.
func (gui *Gui) isTrackedByEnclosingRepo(path string) bool {
isTracked, err := git_commands.IsTrackedByEnclosingRepo(gui.os.Cmd, path)
if err != nil {
gui.c.Log.WithError(err).Warnf("Couldn't tell whether git tracks %s, so we don't load it", path)
return true
}
return isTracked
}
func (gui *Gui) toastIgnoredConfigFiles() {
paths := gui.Config.GetIgnoredUserConfigPaths()
if len(paths) == 0 {
return
}
gui.c.ErrorToast(utils.ResolvePlaceholderString(gui.c.Tr.IgnoredTrackedConfigFiles, map[string]string{
"paths": strings.Join(paths, ", "),
}))
}
func (gui *Gui) onUserConfigLoaded() error {
userConfig := gui.Config.GetUserConfig()
gui.Common.SetUserConfig(userConfig)
+9 -1
View File
@@ -82,7 +82,15 @@ func (self *StatusManager) GetStatusString(userConfig *config.UserConfig) (strin
if len(self.statuses) == 0 {
return "", gocui.ColorDefault
}
topStatus := self.statuses[0]
// A toast disappears after a few seconds, but a waiting status can stay for
// much longer. So a toast is shown above any waiting status; if it weren't,
// a toast that is added before a long operation starts would never be seen.
topStatus, found := lo.Find(self.statuses, func(status appStatus) bool {
return status.statusType == "toast"
})
if !found {
topStatus = self.statuses[0]
}
if topStatus.statusType == "waiting" {
return topStatus.message + " " + presentation.Loader(time.Now(), userConfig.Gui.Spinner), topStatus.color
}
+53
View File
@@ -0,0 +1,53 @@
package status
import (
"testing"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/types"
"github.com/stretchr/testify/assert"
)
func TestStatusStringShowsNewestToast(t *testing.T) {
statusManager := NewStatusManager()
statusManager.AddToastStatus("first toast", types.ToastKindStatus)
statusManager.AddToastStatus("second toast", types.ToastKindStatus)
message, _ := statusManager.GetStatusString(config.GetDefaultConfig())
assert.Equal(t, "second toast", message)
}
func TestStatusStringShowsToastAboveLaterWaitingStatus(t *testing.T) {
statusManager := NewStatusManager()
statusManager.AddToastStatus("toast", types.ToastKindError)
_ = statusManager.WithWaitingStatus("Fetching", func() {}, func(*WaitingStatusHandle) error {
message, _ := statusManager.GetStatusString(config.GetDefaultConfig())
assert.Equal(t, "toast", message)
return nil
})
}
func TestStatusStringShowsToastAboveEarlierWaitingStatus(t *testing.T) {
statusManager := NewStatusManager()
_ = statusManager.WithWaitingStatus("Fetching", func() {}, func(*WaitingStatusHandle) error {
statusManager.AddToastStatus("toast", types.ToastKindError)
message, _ := statusManager.GetStatusString(config.GetDefaultConfig())
assert.Equal(t, "toast", message)
return nil
})
}
func TestStatusStringShowsNewestWaitingStatusWithoutToasts(t *testing.T) {
statusManager := NewStatusManager()
_ = statusManager.WithWaitingStatus("Fetching", func() {}, func(*WaitingStatusHandle) error {
return statusManager.WithWaitingStatus("Rebasing", func() {}, func(*WaitingStatusHandle) error {
message, _ := statusManager.GetStatusString(config.GetDefaultConfig())
assert.Regexp(t, "^Rebasing ", message)
return nil
})
})
}
+2
View File
@@ -283,6 +283,7 @@ type TranslationSet struct {
IntroPopupMessage string
NonReloadableConfigWarningTitle string
NonReloadableConfigWarning string
IgnoredTrackedConfigFiles string
GitconfigParseErr string
EditFile string
EditFileTooltip string
@@ -1512,6 +1513,7 @@ func EnglishTranslationSet() *TranslationSet {
IntroPopupMessage: englishIntroPopupMessage,
NonReloadableConfigWarningTitle: "Config changed",
NonReloadableConfigWarning: englishNonReloadableConfigWarning,
IgnoredTrackedConfigFiles: "Ignored config tracked by git: {{.paths}}",
GitconfigParseErr: `Gogit failed to parse your gitconfig file due to the presence of unquoted '\' characters. Removing these should fix the issue.`,
EditFile: `Edit file`,
EditFileTooltip: "Open file in external editor.",
@@ -0,0 +1,55 @@
package config
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var IgnoreTrackedConfigInParentDir = NewIntegrationTest(NewIntegrationTestArgs{
Description: "When entering a submodule, a .lazygit.yml in a parent directory is ignored if the superproject tracks it",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CloneIntoSubmodule("sub", "modules/sub")
shell.Commit("add submodule")
shell.CreateFileAndAdd(".lazygit.yml", `
customCommands:
- key: X
context: global
command: "true"
description: Command from a tracked config in a parent dir`)
shell.Commit("add config")
shell.CreateFile("modules/.lazygit.yml", `
customCommands:
- key: Y
context: global
command: "true"
description: Command from an untracked config in a parent dir`)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Submodules().Focus().
Lines(
Contains("sub").IsSelected(),
).
PressEnter()
t.Views().Status().Content(Contains("sub"))
t.ExpectToast(MatchesRegexp(`^Ignored config tracked by git: .*repo.\.lazygit\.yml$`))
t.Views().Files().IsFocused().
Press(keys.Universal.OptionMenu)
t.ExpectPopup().Menu().
Title(Equals("Keybindings")).
Filter("in a parent dir").
Lines(
Contains("─── Global"),
Contains("Command from an untracked config in a parent dir").IsSelected(),
)
},
})
@@ -0,0 +1,60 @@
package config
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var IgnoreTrackedConfigInParentDirOnReload = NewIntegrationTest(NewIntegrationTestArgs{
Description: "While lazygit is in a submodule, checking out a branch of the superproject that tracks a .lazygit.yml doesn't load that file on the next config reload",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CloneIntoSubmodule("sub", "modules/sub")
shell.Commit("add submodule")
shell.NewBranch("other-branch")
shell.CreateFileAndAdd(".lazygit.yml", `
customCommands:
- key: X
context: global
command: "true"
description: Command from a tracked config in a parent dir`)
shell.Commit("add config")
shell.Checkout("master")
shell.CreateFile("modules/.lazygit.yml", `
customCommands:
- key: Y
context: global
command: "true"
description: Command from an untracked config in a parent dir`)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Submodules().Focus().
Lines(
Contains("sub").IsSelected(),
).
PressEnter()
t.Views().Status().Content(Contains("sub"))
t.Shell().Checkout("other-branch")
t.FocusIn()
t.ExpectToast(MatchesRegexp(`^Ignored config tracked by git: .*repo.\.lazygit\.yml$`))
t.Views().Files().IsFocused().
Press(keys.Universal.OptionMenu)
t.ExpectPopup().Menu().
Title(Equals("Keybindings")).
Filter("in a parent dir").
Lines(
Contains("─── Global"),
Contains("Command from an untracked config in a parent dir").IsSelected(),
)
},
})
+2
View File
@@ -219,6 +219,8 @@ var tests = []*components.IntegrationTest{
commit.StagedWithoutHooks,
commit.Unstaged,
config.CustomCommandsInPerRepoConfig,
config.IgnoreTrackedConfigInParentDir,
config.IgnoreTrackedConfigInParentDirOnReload,
config.NegativeRefspec,
config.RemoteNamedStar,
config.SidePanelsInPerRepoConfig,