diff --git a/src/segments/git.go b/src/segments/git.go index 7450dc34..cb77876c 100644 --- a/src/segments/git.go +++ b/src/segments/git.go @@ -778,6 +778,30 @@ func (g *Git) getRemoteURL() string { return g.getGitCommandOutput("remote", "get-url", upstream) } +func (g *Git) Remotes() map[string]string { + var remotes = make(map[string]string) + + location := filepath.Join(g.rootDir, "config") + config := g.env.FileContent(location) + cfg, err := ini.Load([]byte(config)) + if err != nil { + return remotes + } + + for _, section := range cfg.Sections() { + if !strings.HasPrefix(section.Name(), "remote ") { + continue + } + + name := strings.TrimPrefix(section.Name(), "remote ") + name = strings.Trim(name, "\"") + url := section.Key("url").String() + url = g.cleanUpstreamURL(url) + remotes[name] = url + } + return remotes +} + func (g *Git) getUntrackedFilesMode() string { return g.getSwitchMode(UntrackedModes, "-u", "normal") } diff --git a/src/segments/git_test.go b/src/segments/git_test.go index e6f179dd..80710927 100644 --- a/src/segments/git_test.go +++ b/src/segments/git_test.go @@ -1050,3 +1050,58 @@ func TestGitCommit(t *testing.T) { assert.Equal(t, tc.Expected, got, tc.Case) } } + +func TestGitRemotes(t *testing.T) { + cases := []struct { + Case string + Expected int + Config string + }{ + { + Case: "Empty config file", + Expected: 0, + }, + { + Case: "Two remotes", + Expected: 2, + Config: ` +[remote "origin"] + url = git@github.com:JanDeDobbeleer/test.git + fetch = +refs/heads/*:refs/remotes/origin/* +[remote "upstream"] + url = git@github.com:microsoft/test.git + fetch = +refs/heads/*:refs/remotes/upstream/* +`, + }, + { + Case: "One remote", + Expected: 1, + Config: ` +[remote "origin"] + url = git@github.com:JanDeDobbeleer/test.git + fetch = +refs/heads/*:refs/remotes/origin/* +`, + }, + { + Case: "Broken config", + Expected: 0, + Config: "{{}}", + }, + } + + for _, tc := range cases { + env := new(mock.MockedEnvironment) + env.On("FileContent", "config").Return(tc.Config) + + g := &Git{ + scm: scm{ + props: properties.Map{}, + realDir: "foo", + env: env, + }, + } + + got := g.Remotes() + assert.Equal(t, tc.Expected, len(got), tc.Case) + } +}