1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2024-12-16 11:37:01 +02:00
lazygit/pkg/commands/loaders/remotes.go

78 lines
1.9 KiB
Go
Raw Normal View History

package loaders
import (
2019-11-17 01:04:06 +02:00
"fmt"
"regexp"
2019-11-17 01:23:06 +02:00
"strings"
2020-09-29 10:41:06 +02:00
2022-03-19 06:36:46 +02:00
"github.com/jesseduffield/generics/slices"
gogit "github.com/jesseduffield/go-git/v5"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/common"
)
type RemoteLoader struct {
*common.Common
cmd oscommands.ICmdObjBuilder
getGoGitRemotes func() ([]*gogit.Remote, error)
}
func NewRemoteLoader(
common *common.Common,
cmd oscommands.ICmdObjBuilder,
getGoGitRemotes func() ([]*gogit.Remote, error),
) *RemoteLoader {
return &RemoteLoader{
Common: common,
cmd: cmd,
getGoGitRemotes: getGoGitRemotes,
}
}
func (self *RemoteLoader) GetRemotes() ([]*models.Remote, error) {
2022-01-05 02:57:32 +02:00
remoteBranchesStr, err := self.cmd.New("git branch -r").DontLog().RunWithOutput()
if err != nil {
return nil, err
}
goGitRemotes, err := self.getGoGitRemotes()
if err != nil {
return nil, err
}
// first step is to get our remotes from go-git
remotes := slices.Map(goGitRemotes, func(goGitRemote *gogit.Remote) *models.Remote {
remoteName := goGitRemote.Config().Name
re := regexp.MustCompile(fmt.Sprintf(`(?m)^\s*%s\/([\S]+)`, remoteName))
2019-11-17 01:04:06 +02:00
matches := re.FindAllStringSubmatch(remoteBranchesStr, -1)
branches := slices.Map(matches, func(match []string) *models.RemoteBranch {
2022-03-19 06:36:46 +02:00
return &models.RemoteBranch{
Name: match[1],
RemoteName: remoteName,
2019-11-17 01:04:06 +02:00
}
2022-03-19 06:36:46 +02:00
})
2022-03-19 06:36:46 +02:00
return &models.Remote{
Name: goGitRemote.Config().Name,
Urls: goGitRemote.Config().URLs,
Branches: branches,
}
2022-03-19 06:36:46 +02:00
})
2019-11-17 01:23:06 +02:00
// now lets sort our remotes by name alphabetically
2022-03-19 06:36:46 +02:00
slices.SortFunc(remotes, func(a, b *models.Remote) bool {
2019-11-17 01:23:06 +02:00
// we want origin at the top because we'll be most likely to want it
2022-03-19 06:36:46 +02:00
if a.Name == "origin" {
2019-11-17 01:23:06 +02:00
return true
}
2022-03-19 06:36:46 +02:00
if b.Name == "origin" {
2019-11-17 01:23:06 +02:00
return false
}
2022-03-19 06:36:46 +02:00
return strings.ToLower(a.Name) < strings.ToLower(b.Name)
2019-11-17 01:23:06 +02:00
})
return remotes, nil
}