6
0
mirror of https://github.com/grdl/git-get.git synced 2026-02-04 22:04:41 +00:00

Refactor pkg directory back

This commit is contained in:
Grzegorz Dlugoszewski
2020-06-12 20:19:05 +02:00
parent 823a522a97
commit 33ca245d3a
16 changed files with 15 additions and 16 deletions

129
pkg/cfg/config.go Normal file
View File

@@ -0,0 +1,129 @@
package cfg
import (
"path"
"strings"
"github.com/go-git/go-git/v5/config"
plumbing "github.com/go-git/go-git/v5/plumbing/format/config"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
// Gitconfig section name and env var prefix
const GitgetPrefix = "gitget"
// Flag keys and their default values
const (
KeyBranch = "branch"
DefBranch = "master"
KeyBundle = "bundle"
KeyDefaultHost = "defaultHost"
DefDefaultHost = "github.com"
KeyFetch = "fetch"
KeyList = "list"
KeyOutput = "out"
DefOutput = OutFlat
KeyPrivateKey = "privateKey"
DefPrivateKey = "id_rsa"
KeyReposRoot = "reposRoot"
DefReposRoot = "repositories"
)
// Allowed values for the --out flag
const (
OutFlat = "flat"
OutSmart = "smart"
OutSimple = "simple"
)
// gitconfig provides methods for looking up configiration values inside .gitconfig file
type gitconfig struct {
*config.Config
}
// InitConfig initializes viper config registry. Values are looked up in the following order: cli flag, env variable, gitconfig file, default value
// Viper doesn't support gitconfig file format so it can't find missing values there automatically. They need to be specified in setMissingValues func.
//
// Because it reads the cli flags it needs to be called after the cmd.Execute().
func InitConfig() {
viper.SetEnvPrefix(strings.ToUpper(GitgetPrefix))
viper.AutomaticEnv()
cfg := loadGitconfig()
setMissingValues(cfg)
}
// loadGitconfig loads configuration from a gitconfig file.
// We ignore errors when gitconfig file can't be found, opened or parsed. In those cases viper will provide default config values.
func loadGitconfig() *gitconfig {
// TODO: load system scope
cfg, _ := config.LoadConfig(config.GlobalScope)
return &gitconfig{
Config: cfg,
}
}
// setMissingValues checks if config values are provided by flags or env vars. If not, it tries loading them from gitconfig file.
// If that fails, the default values are used.
func setMissingValues(cfg *gitconfig) {
if isUnsetOrEmpty(KeyReposRoot) {
viper.Set(KeyReposRoot, cfg.get(KeyReposRoot, path.Join(home(), DefReposRoot)))
}
if isUnsetOrEmpty(KeyDefaultHost) {
viper.Set(KeyDefaultHost, cfg.get(KeyDefaultHost, DefDefaultHost))
}
if isUnsetOrEmpty(KeyPrivateKey) {
viper.Set(KeyPrivateKey, cfg.get(KeyPrivateKey, path.Join(home(), ".ssh", DefPrivateKey)))
}
}
// get looks up the value for a given key in gitconfig file.
// It returns the default value when gitconfig is missing, or it doesn't contain a gitget section,
// or if the section is empty, or if it doesn't contain a valid value for the key.
func (c *gitconfig) get(key string, def string) string {
if c == nil || c.Config == nil {
return def
}
gitget := c.findGitconfigSection(GitgetPrefix)
if gitget == nil {
return def
}
opt := gitget.Option(key)
if strings.TrimSpace(opt) == "" {
return def
}
return opt
}
func (c *gitconfig) findGitconfigSection(name string) *plumbing.Section {
for _, s := range c.Raw.Sections {
if strings.ToLower(s.Name) == strings.ToLower(name) {
return s
}
}
return nil
}
// home returns path to a home directory or empty string if can't be found.
// Using empty string means that in the unlikely situation where home dir can't be found
// and there's no reposRoot specified by any of the config methods, the current dir will be used as repos root.
func home() string {
home, err := homedir.Dir()
if err != nil {
return ""
}
return home
}
func isUnsetOrEmpty(key string) bool {
return !viper.IsSet(key) || strings.TrimSpace(viper.GetString(key)) == ""
}

164
pkg/cfg/config_test.go Normal file
View File

@@ -0,0 +1,164 @@
package cfg
import (
"os"
"path"
"strings"
"testing"
"github.com/go-git/go-git/v5/config"
"github.com/spf13/viper"
)
const (
EnvDefaultHost = "GITGET_DEFAULTHOST"
EnvReposRoot = "GITGET_REPOSROOT"
)
func newConfigWithFullGitconfig() *gitconfig {
cfg := config.NewConfig()
gitget := cfg.Raw.Section(GitgetPrefix)
gitget.AddOption(KeyReposRoot, "file.root")
gitget.AddOption(KeyDefaultHost, "file.host")
return &gitconfig{
Config: cfg,
}
}
func newConfigWithEmptyGitgetSection() *gitconfig {
cfg := config.NewConfig()
_ = cfg.Raw.Section(GitgetPrefix)
return &gitconfig{
Config: cfg,
}
}
func newConfigWithEmptyValues() *gitconfig {
cfg := config.NewConfig()
gitget := cfg.Raw.Section(GitgetPrefix)
gitget.AddOption(KeyReposRoot, "")
gitget.AddOption(KeyDefaultHost, " ")
return &gitconfig{
Config: cfg,
}
}
func newConfigWithoutGitgetSection() *gitconfig {
cfg := config.NewConfig()
return &gitconfig{
Config: cfg,
}
}
func newConfigWithEmptyGitconfig() *gitconfig {
return &gitconfig{
Config: nil,
}
}
func newConfigWithEnvVars() *gitconfig {
_ = os.Setenv(EnvDefaultHost, "env.host")
_ = os.Setenv(EnvReposRoot, "env.root")
return &gitconfig{
Config: nil,
}
}
func newConfigWithGitconfigAndEnvVars() *gitconfig {
cfg := config.NewConfig()
gitget := cfg.Raw.Section(GitgetPrefix)
gitget.AddOption(KeyReposRoot, "file.root")
gitget.AddOption(KeyDefaultHost, "file.host")
_ = os.Setenv(EnvDefaultHost, "env.host")
_ = os.Setenv(EnvReposRoot, "env.root")
return &gitconfig{
Config: cfg,
}
}
func newConfigWithEmptySectionAndEnvVars() *gitconfig {
cfg := config.NewConfig()
_ = cfg.Raw.Section(GitgetPrefix)
_ = os.Setenv(EnvDefaultHost, "env.host")
_ = os.Setenv(EnvReposRoot, "env.root")
return &gitconfig{
Config: cfg,
}
}
func newConfigWithMixed() *gitconfig {
cfg := config.NewConfig()
gitget := cfg.Raw.Section(GitgetPrefix)
gitget.AddOption(KeyReposRoot, "file.root")
gitget.AddOption(KeyDefaultHost, "file.host")
_ = os.Setenv(EnvDefaultHost, "env.host")
return &gitconfig{
Config: cfg,
}
}
func TestConfig(t *testing.T) {
defReposRoot := path.Join(home(), DefReposRoot)
var tests = []struct {
makeConfig func() *gitconfig
wantReposRoot string
wantDefaultHost string
}{
{newConfigWithFullGitconfig, "file.root", "file.host"},
{newConfigWithoutGitgetSection, defReposRoot, DefDefaultHost},
{newConfigWithEmptyGitconfig, defReposRoot, DefDefaultHost},
{newConfigWithEnvVars, "env.root", "env.host"},
{newConfigWithGitconfigAndEnvVars, "env.root", "env.host"},
{newConfigWithEmptySectionAndEnvVars, "env.root", "env.host"},
{newConfigWithEmptyGitgetSection, defReposRoot, DefDefaultHost},
{newConfigWithEmptyValues, defReposRoot, DefDefaultHost},
{newConfigWithMixed, "file.root", "env.host"},
}
for _, test := range tests {
viper.SetEnvPrefix(strings.ToUpper(GitgetPrefix))
viper.AutomaticEnv()
cfg := test.makeConfig()
setMissingValues(cfg)
if viper.GetString(KeyDefaultHost) != test.wantDefaultHost {
t.Errorf("Wrong %s value, got: %s; want: %s", KeyDefaultHost, viper.GetString(KeyDefaultHost), test.wantDefaultHost)
}
if viper.GetString(KeyReposRoot) != test.wantReposRoot {
t.Errorf("Wrong %s value, got: %s; want: %s", KeyReposRoot, viper.GetString(KeyReposRoot), test.wantReposRoot)
}
// Unset env variables and reset viper registry after each test
viper.Reset()
err := os.Unsetenv(EnvDefaultHost)
checkFatal(t, err)
err = os.Unsetenv(EnvReposRoot)
checkFatal(t, err)
}
}
func checkFatal(t *testing.T, err error) {
if err != nil {
t.Fatalf("%+v", err)
}
}

145
pkg/git/repo.go Normal file
View File

@@ -0,0 +1,145 @@
package git
import (
"fmt"
"git-get/pkg/cfg"
"github.com/go-git/go-git/v5/plumbing"
"io"
"io/ioutil"
"net/url"
"os"
"github.com/pkg/errors"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport"
go_git_ssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
)
type Repo struct {
*git.Repository
Path string
Status *RepoStatus
}
// CloneOpts specify details about repository to clone.
type CloneOpts struct {
URL *url.URL
Path string // TODO: should Path be a part of clone opts?
Branch string
Quiet bool
IgnoreExisting bool // TODO: implement!
}
func CloneRepo(opts *CloneOpts) (*Repo, error) {
var progress io.Writer
if !opts.Quiet {
progress = os.Stdout
fmt.Printf("Cloning into '%s'...\n", opts.Path)
}
// TODO: can this be cleaner?
var auth transport.AuthMethod
var err error
if opts.URL.Scheme == "ssh" {
if auth, err = sshKeyAuth(); err != nil {
return nil, err
}
}
// If branch name is actually a tag (ie. is prefixed with refs/tags) - check out that tag.
// Otherwise, assume it's a branch name and check it out.
refName := plumbing.ReferenceName(opts.Branch)
if !refName.IsTag() {
refName = plumbing.NewBranchReferenceName(opts.Branch)
}
gitOpts := &git.CloneOptions{
URL: opts.URL.String(),
Auth: auth,
RemoteName: git.DefaultRemoteName,
ReferenceName: refName,
SingleBranch: false,
NoCheckout: false,
Depth: 0,
RecurseSubmodules: git.NoRecurseSubmodules,
Progress: progress,
Tags: git.AllTags,
}
repo, err := git.PlainClone(opts.Path, false, gitOpts)
if err != nil {
return nil, errors.Wrap(err, "Failed cloning repo")
}
return NewRepo(repo, opts.Path), nil
}
func OpenRepo(repoPath string) (*Repo, error) {
repo, err := git.PlainOpen(repoPath)
if err != nil {
return nil, errors.Wrap(err, "Failed opening repo")
}
return NewRepo(repo, repoPath), nil
}
func NewRepo(repo *git.Repository, repoPath string) *Repo {
return &Repo{
Repository: repo,
Path: repoPath,
Status: &RepoStatus{},
}
}
// Fetch performs a git fetch on all remotes
func (r *Repo) Fetch() error {
remotes, err := r.Remotes()
if err != nil {
return errors.Wrap(err, "Failed getting remotes")
}
for _, remote := range remotes {
err = remote.Fetch(&git.FetchOptions{})
if err != nil {
return errors.Wrapf(err, "Failed fetching remote %s", remote.Config().Name)
}
}
return nil
}
func sshKeyAuth() (transport.AuthMethod, error) {
privateKey := viper.GetString(cfg.KeyPrivateKey)
sshKey, err := ioutil.ReadFile(privateKey)
if err != nil {
return nil, errors.Wrapf(err, "Failed to open ssh private key %s", privateKey)
}
signer, err := ssh.ParsePrivateKey([]byte(sshKey))
if err != nil {
return nil, errors.Wrapf(err, "Failed to parse ssh private key %s", privateKey)
}
// TODO: can it ba a different user
auth := &go_git_ssh.PublicKeys{User: "git", Signer: signer}
return auth, nil
}
func (r *Repo) CurrentBranchStatus() *BranchStatus {
if r.Status.CurrentBranch == StatusDetached || r.Status.CurrentBranch == StatusUnknown {
return nil
}
for _, b := range r.Status.Branches {
if b.Name == r.Status.CurrentBranch {
return b
}
}
return nil
}

294
pkg/git/repo_test.go Normal file
View File

@@ -0,0 +1,294 @@
package git
import (
"net/url"
"io/ioutil"
"os"
"testing"
"time"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5"
"github.com/pkg/errors"
)
const (
testUser = "Test User"
testEmail = "testuser@example.com"
)
func newRepoEmpty(t *testing.T) *Repo {
dir := newTempDir(t)
repo, err := git.PlainInit(dir, false)
checkFatal(t, err)
return NewRepo(repo, dir)
}
func newRepoWithUntracked(t *testing.T) *Repo {
r := newRepoEmpty(t)
r.writeFile(t, "README", "I'm a README file")
return r
}
func newRepoWithStaged(t *testing.T) *Repo {
r := newRepoEmpty(t)
r.writeFile(t, "README", "I'm a README file")
r.addFile(t, "README")
return r
}
func newRepoWithCommit(t *testing.T) *Repo {
r := newRepoEmpty(t)
r.writeFile(t, "README", "I'm a README file")
r.addFile(t, "README")
r.newCommit(t, "Initial commit")
return r
}
func newRepoWithModified(t *testing.T) *Repo {
r := newRepoEmpty(t)
r.writeFile(t, "README", "I'm a README file")
r.addFile(t, "README")
r.newCommit(t, "Initial commit")
r.writeFile(t, "README", "I'm modified")
return r
}
func newRepoWithIgnored(t *testing.T) *Repo {
r := newRepoEmpty(t)
r.writeFile(t, ".gitignore", "ignoreme")
r.addFile(t, ".gitignore")
r.newCommit(t, "Initial commit")
r.writeFile(t, "ignoreme", "I'm being ignored")
return r
}
func newRepoWithLocalBranch(t *testing.T) *Repo {
r := newRepoWithCommit(t)
r.newBranch(t, "local")
return r
}
func newRepoWithClonedBranch(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
r := origin.clone(t, "master")
r.newBranch(t, "local")
r.checkoutBranch(t, "local")
return r
}
func newRepoWithDetachedHead(t *testing.T) *Repo {
r := newRepoWithCommit(t)
r.writeFile(t, "new", "I'm a new file")
r.addFile(t, "new")
hash := r.newCommit(t, "new commit")
r.checkoutHash(t, hash)
return r
}
func newRepoWithBranchAhead(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
r := origin.clone(t, "master")
r.writeFile(t, "new", "I'm a new file")
r.addFile(t, "new")
r.newCommit(t, "new commit")
return r
}
func newRepoWithBranchBehind(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
r := origin.clone(t, "master")
origin.writeFile(t, "origin.new", "I'm a new file on origin")
origin.addFile(t, "origin.new")
origin.newCommit(t, "new origin commit")
r.fetch(t)
return r
}
// generate repo with 2 commits ahead and 3 behind the origin
func newRepoWithBranchAheadAndBehind(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
r := origin.clone(t, "master")
r.writeFile(t, "local.new", "local 1")
r.addFile(t, "local.new")
r.newCommit(t, "1st local commit")
r.writeFile(t, "local.new", "local 2")
r.addFile(t, "local.new")
r.newCommit(t, "2nd local commit")
origin.writeFile(t, "origin.new", "origin 1")
origin.addFile(t, "origin.new")
origin.newCommit(t, "1st origin commit")
origin.writeFile(t, "origin.new", "origin 2")
origin.addFile(t, "origin.new")
origin.newCommit(t, "2nd origin commit")
origin.writeFile(t, "origin.new", "origin 3")
origin.addFile(t, "origin.new")
origin.newCommit(t, "3rd origin commit")
r.fetch(t)
return r
}
func newRepoWithCheckedOutBranch(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
origin.newBranch(t, "feature/branch1")
r := origin.clone(t, "feature/branch1")
return r
}
func newRepoWithCheckedOutTag(t *testing.T) *Repo {
origin := newRepoWithCommit(t)
origin.newTag(t, "v1.0.0")
r := origin.clone(t, "refs/tags/v1.0.0")
return r
}
func newTempDir(t *testing.T) string {
dir, err := ioutil.TempDir("", "git-get-repo-")
checkFatal(t, errors.Wrap(err, "Failed creating test repo directory"))
// Automatically remove repo when test is over
t.Cleanup(func() {
err := os.RemoveAll(dir)
if err != nil {
t.Errorf("failed cleaning up repo")
}
})
return dir
}
func (r *Repo) writeFile(t *testing.T, name string, content string) {
wt, err := r.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting worktree"))
file, err := wt.Filesystem.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
checkFatal(t, errors.Wrap(err, "Failed opening a file"))
_, err = file.Write([]byte(content))
checkFatal(t, errors.Wrap(err, "Failed writing a file"))
}
func (r *Repo) addFile(t *testing.T, name string) {
wt, err := r.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting worktree"))
_, err = wt.Add(name)
checkFatal(t, errors.Wrap(err, "Failed adding file to index"))
}
func (r *Repo) newCommit(t *testing.T, msg string) plumbing.Hash {
wt, err := r.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting worktree"))
opts := &git.CommitOptions{
Author: &object.Signature{
Name: testUser,
Email: testEmail,
When: time.Date(2000, 01, 01, 16, 00, 00, 0, time.UTC),
},
}
hash, err := wt.Commit(msg, opts)
checkFatal(t, errors.Wrap(err, "Failed creating commit"))
return hash
}
func (r *Repo) newBranch(t *testing.T, name string) {
head, err := r.Head()
checkFatal(t, err)
ref := plumbing.NewHashReference(plumbing.NewBranchReferenceName(name), head.Hash())
err = r.Storer.SetReference(ref)
checkFatal(t, err)
}
func (r *Repo) newTag(t *testing.T, name string) {
head, err := r.Head()
checkFatal(t, err)
ref := plumbing.NewHashReference(plumbing.NewTagReferenceName(name), head.Hash())
err = r.Storer.SetReference(ref)
checkFatal(t, err)
}
func (r *Repo) clone(t *testing.T, branch string) *Repo {
dir := newTempDir(t)
repoURL, err := url.Parse("file://" + r.Path)
checkFatal(t, err)
cloneOpts := &CloneOpts{
URL: repoURL,
Path: dir,
Branch: branch,
Quiet: true,
}
repo, err := CloneRepo(cloneOpts)
checkFatal(t, err)
return repo
}
func (r *Repo) fetch(t *testing.T) {
err := r.Fetch()
checkFatal(t, err)
}
func (r *Repo) checkoutBranch(t *testing.T, name string) {
wt, err := r.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting worktree"))
opts := &git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(name),
}
err = wt.Checkout(opts)
checkFatal(t, errors.Wrap(err, "Failed checking out branch"))
}
func (r *Repo) checkoutHash(t *testing.T, hash plumbing.Hash) {
wt, err := r.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting worktree"))
opts := &git.CheckoutOptions{
Hash: hash,
}
err = wt.Checkout(opts)
checkFatal(t, errors.Wrap(err, "Failed checking out hash"))
}
func checkFatal(t *testing.T, err error) {
if err != nil {
t.Fatalf("%+v", err)
}
}

266
pkg/git/status.go Normal file
View File

@@ -0,0 +1,266 @@
package git
import (
"git-get/pkg/cfg"
"sort"
"strings"
"github.com/go-git/go-git/v5/plumbing/revlist"
"github.com/spf13/viper"
"github.com/go-git/go-billy/v5/osfs"
"github.com/go-git/go-git/v5/plumbing/format/gitignore"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/pkg/errors"
)
const (
StatusUnknown = "unknown"
StatusDetached = "detached HEAD"
StatusNoUpstream = "no upstream"
StatusAhead = "ahead"
StatusBehind = "behind"
StatusOk = "ok"
StatusUncommitted = "uncommitted"
StatusUntracked = "untracked"
)
type RepoStatus struct {
HasUntrackedFiles bool
HasUncommittedChanges bool
CurrentBranch string
Branches []*BranchStatus
}
type BranchStatus struct {
Name string
Upstream string
Ahead int
Behind int
}
func (r *Repo) LoadStatus() error {
// Fetch from remotes if executed with --fetch flag. Ignore the "already up-to-date" errors.
if viper.GetBool(cfg.KeyFetch) {
err := r.Fetch()
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
return errors.Wrap(err, "Failed fetching from remotes")
}
}
wt, err := r.Worktree()
if err != nil {
return errors.Wrap(err, "Failed getting worktree")
}
// worktree.Status doesn't load gitignore patterns that are defined outside of .gitignore file using excludesfile.
// We need to load them explicitly here
// TODO: variables are not expanded so if excludesfile is declared like "~/gitignore_global" or "$HOME/gitignore_global", this will fail to open it
globalPatterns, err := gitignore.LoadGlobalPatterns(osfs.New(""))
if err != nil {
return errors.Wrap(err, "Failed loading global gitignore patterns")
}
wt.Excludes = append(wt.Excludes, globalPatterns...)
systemPatterns, err := gitignore.LoadSystemPatterns(osfs.New(""))
if err != nil {
return errors.Wrap(err, "Failed loading system gitignore patterns")
}
wt.Excludes = append(wt.Excludes, systemPatterns...)
status, err := wt.Status()
if err != nil {
return errors.Wrap(err, "Failed getting worktree status")
}
r.Status.HasUncommittedChanges = hasUncommitted(status)
r.Status.HasUntrackedFiles = hasUntracked(status)
r.Status.CurrentBranch = currentBranch(r)
err = r.loadBranchesStatus()
if err != nil {
return err
}
return nil
}
// hasUntracked returns true if there are any untracked files in the worktree
func hasUntracked(status git.Status) bool {
for _, fs := range status {
if fs.Worktree == git.Untracked || fs.Staging == git.Untracked {
return true
}
}
return false
}
// hasUncommitted returns true if there are any uncommitted (but tracked) files in the worktree
func hasUncommitted(status git.Status) bool {
// If repo is clean it means every file in worktree and staging has 'Unmodified' state
if status.IsClean() {
return false
}
// If repo is not clean, check if any file has state different than 'Untracked' - it means they are tracked and have uncommitted modifications
for _, fs := range status {
if fs.Worktree != git.Untracked || fs.Staging != git.Untracked {
return true
}
}
return false
}
func currentBranch(r *Repo) string {
head, err := r.Head()
if err != nil {
return StatusUnknown
}
if head.Name().Short() == plumbing.HEAD.String() {
return StatusDetached
}
return head.Name().Short()
}
func (r *Repo) loadBranchesStatus() error {
iter, err := r.Branches()
if err != nil {
return errors.Wrap(err, "Failed getting branches iterator")
}
err = iter.ForEach(func(reference *plumbing.Reference) error {
bs, err := r.newBranchStatus(reference.Name().Short())
if err != nil {
return err
}
r.Status.Branches = append(r.Status.Branches, bs)
return nil
})
if err != nil {
return errors.Wrap(err, "Failed iterating over branches")
}
// Sort branches by name (but with "master" always at the top). It's useful to have them sorted for printing and testing.
sort.Slice(r.Status.Branches, func(i, j int) bool {
if r.Status.Branches[i].Name == "master" {
return true
}
return strings.Compare(r.Status.Branches[i].Name, r.Status.Branches[j].Name) < 0
})
return nil
}
func (r *Repo) newBranchStatus(branch string) (*BranchStatus, error) {
bs := &BranchStatus{
Name: branch,
}
upstream, err := r.upstream(branch)
if err != nil {
return nil, err
}
if upstream == "" {
return bs, nil
}
ahead, behind, err := r.aheadBehind(branch, upstream)
if err != nil {
return nil, err
}
bs.Upstream = upstream
bs.Ahead = ahead
bs.Behind = behind
return bs, nil
}
// upstream finds if a given branch tracks an upstream.
// Returns found upstream branch name (eg, origin/master) or empty string if branch doesn't track an upstream.
//
// Information about upstream is taken from .git/config file.
// If a branch has an upstream, there's a [branch] section in the file with two fields:
// "remote" - name of the remote containing upstream branch (or "." if upstream is a local branch)
// "merge" - full ref name of the upstream branch (eg, ref/heads/master)
func (r *Repo) upstream(branch string) (string, error) {
cfg, err := r.Config()
if err != nil {
return "", errors.Wrap(err, "Failed getting repo config")
}
// Check if our branch exists in "branch" config sections. If not, it doesn't have an upstream configured.
bcfg := cfg.Branches[branch]
if bcfg == nil {
return "", nil
}
remote := bcfg.Remote
if remote == "" {
return "", nil
}
merge := bcfg.Merge.Short()
if merge == "" {
return "", nil
}
return remote + "/" + merge, nil
}
func (r *Repo) aheadBehind(localBranch string, upstreamBranch string) (ahead int, behind int, err error) {
localHash, err := r.ResolveRevision(plumbing.Revision(localBranch))
if err != nil {
return 0, 0, errors.Wrapf(err, "Failed resolving revision %s", localBranch)
}
upstreamHash, err := r.ResolveRevision(plumbing.Revision(upstreamBranch))
if err != nil {
return 0, 0, errors.Wrapf(err, "Failed resolving revision %s", upstreamBranch)
}
behind, err = r.revlistCount(*localHash, *upstreamHash)
if err != nil {
return 0, 0, errors.Wrapf(err, "Failed counting commits behind %s", upstreamBranch)
}
ahead, err = r.revlistCount(*upstreamHash, *localHash)
if err != nil {
return 0, 0, errors.Wrapf(err, "Failed counting commits ahead of %s", upstreamBranch)
}
return ahead, behind, nil
}
// revlistCount counts the number of commits between two hashes.
// https://github.com/src-d/go-git/issues/757#issuecomment-452697701
// TODO: See if this can be optimized. Running the loop twice feels wrong.
func (r *Repo) revlistCount(hash1, hash2 plumbing.Hash) (int, error) {
ref1hist, err := revlist.Objects(r.Storer, []plumbing.Hash{hash1}, nil)
if err != nil {
return 0, err
}
ref2hist, err := revlist.Objects(r.Storer, []plumbing.Hash{hash2}, ref1hist)
if err != nil {
return 0, err
}
count := 0
for _, h := range ref2hist {
if _, err = r.CommitObject(h); err == nil {
count++
}
}
return count, nil
}

195
pkg/git/status_test.go Normal file
View File

@@ -0,0 +1,195 @@
package git
import (
"reflect"
"testing"
)
func TestStatus(t *testing.T) {
var tests = []struct {
makeTestRepo func(*testing.T) *Repo
want *RepoStatus
}{
{newRepoEmpty, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: StatusUnknown,
Branches: nil,
}},
{newRepoWithUntracked, &RepoStatus{
HasUntrackedFiles: true,
HasUncommittedChanges: false,
CurrentBranch: StatusUnknown,
Branches: nil,
}},
{newRepoWithStaged, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
CurrentBranch: StatusUnknown,
Branches: nil,
}},
{newRepoWithCommit, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithModified, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithIgnored, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithLocalBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
Behind: 0,
Ahead: 0,
}, {
Name: "local",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithClonedBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "local",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
Behind: 0,
Ahead: 0,
}, {
Name: "local",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithDetachedHead, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: StatusDetached,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithBranchAhead, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
Behind: 0,
Ahead: 1,
},
},
}},
{newRepoWithBranchBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
Behind: 1,
Ahead: 0,
},
},
}},
{newRepoWithBranchAheadAndBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "master",
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
Behind: 3,
Ahead: 2,
},
},
}},
{newRepoWithCheckedOutBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
CurrentBranch: "feature/branch1",
Branches: []*BranchStatus{
{
Name: "feature/branch1",
Upstream: "origin/feature/branch1",
Behind: 0,
Ahead: 0,
},
},
}},
{newRepoWithCheckedOutTag, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
// TODO: is this correct? Can we show tag name instead of "detached HEAD"?
CurrentBranch: StatusDetached,
Branches: nil,
}},
}
for i, test := range tests {
repo := test.makeTestRepo(t)
err := repo.LoadStatus()
checkFatal(t, err)
if !reflect.DeepEqual(repo.Status, test.want) {
t.Errorf("Failed test case %d, got: %+v; want: %+v", i, repo.Status, test.want)
}
}
}
// TODO: test branch status when tracking a local branch
// TODO: test head pointing to a tag
// TODO: newRepoWithGlobalGitignore
// TODO: newRepoWithGlobalGitignoreSymlink

66
pkg/path/bundle.go Normal file
View File

@@ -0,0 +1,66 @@
package path
import (
"bufio"
"git-get/pkg/git"
"os"
"strings"
"github.com/pkg/errors"
)
var (
ErrInvalidNumberOfElements = errors.New("More than two space-separated 2 elements on the line")
)
// ParseBundleFile opens a given gitgetfile and parses its content into a slice of CloneOpts.
func ParseBundleFile(path string) ([]*git.CloneOpts, error) {
file, err := os.Open(path)
if err != nil {
return nil, errors.Wrapf(err, "Failed opening gitgetfile %s", path)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var opts []*git.CloneOpts
var line int
for scanner.Scan() {
line++
opt, err := parseLine(scanner.Text())
if err != nil {
return nil, errors.Wrapf(err, "Failed parsing line %d", line)
}
opts = append(opts, opt)
}
return opts, nil
}
// parseLine splits a gitgetfile line into space-separated segments.
// First part is the URL to clone. Second, optional, is the branch (or tag) to checkout after cloning
func parseLine(line string) (*git.CloneOpts, error) {
parts := strings.Split(line, " ")
if len(parts) > 2 {
return nil, ErrInvalidNumberOfElements
}
url, err := ParseURL(parts[0])
if err != nil {
return nil, err
}
branch := ""
if len(parts) == 2 {
branch = parts[1]
}
return &git.CloneOpts{
URL: url,
Branch: branch,
// When cloning a bundle we ignore errors about already cloned repos
IgnoreExisting: true,
}, nil
}

55
pkg/path/bundle_test.go Normal file
View File

@@ -0,0 +1,55 @@
package path
import (
"testing"
)
func TestParsingRefs(t *testing.T) {
var tests = []struct {
line string
wantBranch string
wantErr error
}{
{
line: "https://github.com/grdl/git-get",
wantBranch: "",
wantErr: nil,
},
{
line: "https://github.com/grdl/git-get master",
wantBranch: "master",
wantErr: nil,
},
{
line: "https://github.com/grdl/git-get refs/tags/v1.0.0",
wantBranch: "refs/tags/v1.0.0",
wantErr: nil,
},
{
line: "https://github.com/grdl/git-get master branch",
wantBranch: "",
wantErr: ErrInvalidNumberOfElements,
},
{
line: "https://github.com",
wantBranch: "",
wantErr: ErrEmptyURLPath,
},
}
for i, test := range tests {
got, err := parseLine(test.line)
if err != nil && test.wantErr == nil {
t.Fatalf("Test case %d should not return an error", i)
}
if err != nil && test.wantErr != nil {
continue
}
if got.Branch != test.wantBranch {
t.Errorf("Failed test case %d, got: %s; wantBranch: %s", i, got.Branch, test.wantBranch)
}
}
}

106
pkg/path/list.go Normal file
View File

@@ -0,0 +1,106 @@
package path
import (
"fmt"
"git-get/pkg/cfg"
"git-get/pkg/git"
"os"
"sort"
"strings"
"syscall"
"github.com/karrick/godirwalk"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
// skipNode is used as an error indicating that .git directory has been found.
// It's handled by ErrorsCallback to tell the WalkCallback to skip this dir.
var skipNode = errors.New(".git directory found, skipping this node")
var repos []string
func FindRepos() ([]string, error) {
repos = []string{}
root := viper.GetString(cfg.KeyReposRoot)
if _, err := os.Stat(root); err != nil {
return nil, fmt.Errorf("Repos root %s does not exist or can't be accessed", root)
}
walkOpts := &godirwalk.Options{
ErrorCallback: ErrorCb,
Callback: WalkCb,
// Use Unsorted to improve speed because repos will be processed by goroutines in a random order anyway.
Unsorted: true,
}
err := godirwalk.Walk(root, walkOpts)
if err != nil {
return nil, err
}
if len(repos) == 0 {
return nil, fmt.Errorf("No git repos found in repos root %s", root)
}
return repos, nil
}
func WalkCb(path string, ent *godirwalk.Dirent) error {
if ent.IsDir() && ent.Name() == ".git" {
repos = append(repos, strings.TrimSuffix(path, ".git"))
return skipNode
}
return nil
}
func ErrorCb(_ string, err error) godirwalk.ErrorAction {
// Skip .git directory and directories we don't have permissions to access
// TODO: Will syscall.EACCES work on windows?
if errors.Is(err, skipNode) || errors.Is(err, syscall.EACCES) {
return godirwalk.SkipNode
}
return godirwalk.Halt
}
func OpenAll(paths []string) ([]*git.Repo, error) {
var repos []*git.Repo
reposChan := make(chan *git.Repo)
for _, path := range paths {
go func(path string) {
repo, err := git.OpenRepo(path)
if err != nil {
// TODO handle error
fmt.Println(err)
}
err = repo.LoadStatus()
if err != nil {
// TODO handle error
fmt.Println(err)
}
// when error happened we just sent a nil
reposChan <- repo
}(path)
}
for repo := range reposChan {
repos = append(repos, repo)
// TODO: is this the right way to close the channel? What if we have non-unique paths?
if len(repos) == len(paths) {
close(reposChan)
}
}
// sort the final array to make printing easier
sort.Slice(repos, func(i, j int) bool {
return strings.Compare(repos[i].Path, repos[j].Path) < 0
})
return repos, nil
}

77
pkg/path/url.go Normal file
View File

@@ -0,0 +1,77 @@
package path
import (
"git-get/pkg/cfg"
urlpkg "net/url"
"path"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
var (
ErrEmptyURLPath = errors.New("Parsed URL path is empty")
)
// scpSyntax matches the SCP-like addresses used by the ssh protocol (eg, [user@]host.xz:path/to/repo.git/).
// See: https://golang.org/src/cmd/go/internal/get/vcs.go
var scpSyntax = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)
func ParseURL(rawURL string) (url *urlpkg.URL, err error) {
// If rawURL matches the SCP-like syntax, convert it into a standard ssh Path.
// eg, git@github.com:user/repo => ssh://git@github.com/user/repo
if m := scpSyntax.FindStringSubmatch(rawURL); m != nil {
url = &urlpkg.URL{
Scheme: "ssh",
User: urlpkg.User(m[1]),
Host: m[2],
Path: m[3],
}
} else {
url, err = urlpkg.Parse(rawURL)
if err != nil {
return nil, errors.Wrap(err, "Failed parsing URL")
}
}
if url.Host == "" && url.Path == "" {
return nil, ErrEmptyURLPath
}
if url.Scheme == "git+ssh" {
url.Scheme = "ssh"
}
// Default to "git" user when using ssh and no user is provided
if url.Scheme == "ssh" && url.User == nil {
url.User = urlpkg.User("git")
}
// Default to configured defaultHost when host is empty
if url.Host == "" {
url.Host = viper.GetString(cfg.KeyDefaultHost)
}
// Default to https when scheme is empty
if url.Scheme == "" {
url.Scheme = "https"
}
return url, nil
}
func URLToPath(url *urlpkg.URL) (repoPath string) {
// Remove port numbers from host
repoHost := strings.Split(url.Host, ":")[0]
// Remove trailing ".git" from repo name
repoPath = path.Join(repoHost, url.Path)
repoPath = strings.TrimSuffix(repoPath, ".git")
// Remove tilde (~) char from username
repoPath = strings.ReplaceAll(repoPath, "~", "")
return repoPath
}

85
pkg/path/url_test.go Normal file
View File

@@ -0,0 +1,85 @@
package path
import (
"git-get/pkg/cfg"
"testing"
)
// Following URLs are considered valid according to https://git-scm.com/docs/git-clone#_git_urls:
// ssh://[user@]host.xz[:port]/path/to/repo.git
// ssh://[user@]host.xz[:port]/~[user]/path/to/repo.git/
// [user@]host.xz:path/to/repo.git/
// [user@]host.xz:/~[user]/path/to/repo.git/
// git://host.xz[:port]/path/to/repo.git/
// git://host.xz[:port]/~[user]/path/to/repo.git/
// http[s]://host.xz[:port]/path/to/repo.git/
// ftp[s]://host.xz[:port]/path/to/repo.git/
// /path/to/repo.git/
// file:///path/to/repo.git/
func TestURLParse(t *testing.T) {
tests := []struct {
in string
want string
}{
{"ssh://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"ssh://user@github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"ssh://user@github.com:1234/grdl/git-get.git", "github.com/grdl/git-get"},
{"ssh://user@github.com/~user/grdl/git-get.git", "github.com/user/grdl/git-get"},
{"git+ssh://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"git@github.com:grdl/git-get.git", "github.com/grdl/git-get"},
{"git@github.com:/~user/grdl/git-get.git", "github.com/user/grdl/git-get"},
{"git://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"git://github.com/~user/grdl/git-get.git", "github.com/user/grdl/git-get"},
{"https://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"http://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"https://github.com/grdl/git-get", "github.com/grdl/git-get"},
{"https://github.com/git-get.git", "github.com/git-get"},
{"https://github.com/git-get", "github.com/git-get"},
{"https://github.com/grdl/sub/path/git-get.git", "github.com/grdl/sub/path/git-get"},
{"https://github.com:1234/grdl/git-get.git", "github.com/grdl/git-get"},
{"https://github.com/grdl/git-get.git/", "github.com/grdl/git-get"},
{"https://github.com/grdl/git-get/", "github.com/grdl/git-get"},
{"https://github.com/grdl/git-get/////", "github.com/grdl/git-get"},
{"https://github.com/grdl/git-get.git/////", "github.com/grdl/git-get"},
{"ftp://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"ftps://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"rsync://github.com/grdl/git-get.git", "github.com/grdl/git-get"},
{"local/grdl/git-get/", "github.com/local/grdl/git-get"},
{"file://local/grdl/git-get", "local/grdl/git-get"},
}
// We need to init config first so the default values are correctly loaded
cfg.InitConfig()
for _, test := range tests {
url, err := ParseURL(test.in)
if err != nil {
t.Errorf("Error parsing Path: %+v", err)
}
got := URLToPath(url)
if got != test.want {
t.Errorf("Wrong result of parsing Path: %s, got: %s; wantBranch: %s", test.in, got, test.want)
}
}
}
func TestInvalidURLParse(t *testing.T) {
invalidURLs := []string{
"",
//TODO: This Path is technically a correct scp-like syntax. Not sure how to handle it
"github.com:grdl/git-git.get.git",
//TODO: Is this a valid git Path?
//"git@github.com:1234:grdl/git-get.git",
}
for _, in := range invalidURLs {
got, err := ParseURL(in)
if err == nil {
t.Errorf("Wrong result of parsing invalid Path: %s, got: %s, wantBranch: error", in, got)
}
}
}

33
pkg/print/flat.go Normal file
View File

@@ -0,0 +1,33 @@
package print
import (
"fmt"
"git-get/pkg/git"
"path/filepath"
"strings"
)
type FlatPrinter struct{}
func (p *FlatPrinter) Print(root string, repos []*git.Repo) string {
val := root
for _, repo := range repos {
path := strings.TrimPrefix(repo.Path, root)
path = strings.Trim(path, string(filepath.Separator))
val += fmt.Sprintf("\n%s %s", path, printWorktreeStatus(repo))
for _, branch := range repo.Status.Branches {
// Don't print the status of the current branch. It was already printed above.
if branch.Name == repo.Status.CurrentBranch {
continue
}
indent := strings.Repeat(" ", len(path))
val += fmt.Sprintf("\n%s %s", indent, printBranchStatus(branch))
}
}
return val
}

85
pkg/print/print.go Normal file
View File

@@ -0,0 +1,85 @@
package print
import (
"fmt"
"git-get/pkg/git"
"strings"
)
type Printer interface {
Print(root string, repos []*git.Repo) string
}
const (
ColorRed = "\033[1;31m%s\033[0m"
ColorGreen = "\033[1;32m%s\033[0m"
ColorBlue = "\033[1;34m%s\033[0m"
ColorYellow = "\033[1;33m%s\033[0m"
)
func printWorktreeStatus(repo *git.Repo) string {
clean := true
var status []string
// if current branch status can't be found it's probably a detached head
// TODO: what if current HEAD points to a tag?
if current := repo.CurrentBranchStatus(); current == nil {
status = append(status, fmt.Sprintf(ColorYellow, repo.Status.CurrentBranch))
} else {
status = append(status, printBranchStatus(current))
}
// TODO: this is ugly
// unset clean flag to use it to render braces around worktree status and remove "ok" from branch status if it's there
if repo.Status.HasUncommittedChanges || repo.Status.HasUntrackedFiles {
clean = false
}
if !clean {
status[len(status)-1] = strings.TrimSuffix(status[len(status)-1], git.StatusOk)
status = append(status, "[")
}
if repo.Status.HasUntrackedFiles {
status = append(status, fmt.Sprintf(ColorRed, git.StatusUntracked))
}
if repo.Status.HasUncommittedChanges {
status = append(status, fmt.Sprintf(ColorRed, git.StatusUncommitted))
}
if !clean {
status = append(status, "]")
}
return strings.Join(status, " ")
}
func printBranchStatus(branch *git.BranchStatus) string {
// ok indicates that the branch has upstream and is not ahead or behind it
ok := true
var status []string
status = append(status, fmt.Sprintf(ColorBlue, branch.Name))
if branch.Upstream == "" {
ok = false
status = append(status, fmt.Sprintf(ColorYellow, git.StatusNoUpstream))
}
if branch.Behind != 0 {
ok = false
status = append(status, fmt.Sprintf(ColorYellow, fmt.Sprintf("%d %s", branch.Behind, git.StatusBehind)))
}
if branch.Ahead != 0 {
ok = false
status = append(status, fmt.Sprintf(ColorYellow, fmt.Sprintf("%d %s", branch.Ahead, git.StatusAhead)))
}
if ok {
status = append(status, fmt.Sprintf(ColorGreen, git.StatusOk))
}
return strings.Join(status, " ")
}

214
pkg/print/tree.go Normal file
View File

@@ -0,0 +1,214 @@
package print
import (
"git-get/pkg/git"
"path/filepath"
"strings"
"github.com/xlab/treeprint"
)
type SimpleTreePrinter struct{}
type SmartTreePrinter struct {
// length is the size (number of chars) of the currently processed line.
// It's used to correctly indent the lines with branches status.
length int
}
func (p *SmartTreePrinter) Print(root string, repos []*git.Repo) string {
tree := BuildTree(root, repos)
return p.PrintSmartTree(tree)
}
func (p *SimpleTreePrinter) Print(root string, repos []*git.Repo) string {
tree := BuildTree(root, repos)
tp := treeprint.New()
tp.SetValue(root)
p.PrintSimpleTree(tree, tp)
return tp.String()
}
// Node represents a node (ie. path fragment) in a repos tree.
type Node struct {
val string
depth int // depth is a nesting depth used when rendering a smart tree, not a depth level of a tree node.
parent *Node
children []*Node
repo *git.Repo
}
// Root creates a new root of a tree
func Root(val string) *Node {
root := &Node{
val: val,
}
return root
}
// Add adds a child node
func (n *Node) Add(val string) *Node {
if n.children == nil {
n.children = make([]*Node, 0)
}
child := &Node{
val: val,
parent: n,
}
n.children = append(n.children, child)
return child
}
// GetChild finds a node with val inside this node's children (only 1 level deep).
// Returns pointer to found child or nil if node doesn't have any children or doesn't have a child with sought value.
func (n *Node) GetChild(val string) *Node {
if n.children == nil {
return nil
}
for _, child := range n.children {
if child.val == val {
return child
}
}
return nil
}
// BuildTree builds a directory tree of paths to repositories.
// Each node represents a directory in the repo path.
// Each leaf (final node) contains a pointer to the repo.
func BuildTree(root string, repos []*git.Repo) *Node {
tree := Root(root)
for _, repo := range repos {
path := strings.TrimPrefix(repo.Path, root)
path = strings.Trim(path, string(filepath.Separator))
subs := strings.Split(path, string(filepath.Separator))
// For each path fragment, start at the root of the tree
// and check if the fragment exist among the children of the node.
// If not, add it to node's children and move to next fragment.
// If it does, just move to the next fragment.
node := tree
for i, sub := range subs {
child := node.GetChild(sub)
if child == nil {
node = node.Add(sub)
// If that's the last fragment, it's a tree leaf and needs a *Repo attached.
if i == len(subs)-1 {
node.repo = repo
}
continue
}
node = child
}
}
return tree
}
// PrintSmartTree returns a string representation of repos tree.
// It's "smart" because it automatically folds branches which only have a single child and indents branches with many children.
//
// It recursively traverses the tree and prints its nodes.
// If a node contains multiple children, they are be printed in new lines and indented.
// If a node contains only a single child, it is printed in the same line using path separator.
// For better readability the first level (repos hosts) is not indented.
//
// Example:
// Following paths:
// /repos/github.com/user/repo1
// /repos/github.com/user/repo2
// /repos/github.com/another/repo
//
// will render a tree:
// /repos/
// github.com/
// user/
// repo1
// repo2
// another/repo
//
func (p *SmartTreePrinter) PrintSmartTree(node *Node) string {
if node.children == nil {
// If node is a leaf, print repo name and its status and finish processing this node.
value := node.val
// TODO: Ugly
// If this is called from tests the repo will be nil and we should return just the name without the status.
if node.repo.Repository == nil {
return value
}
value += " " + printWorktreeStatus(node.repo)
// Print the status of each branch on a new line, indented to match the position of the current branch name.
indent := "\n" + strings.Repeat(" ", p.length+len(node.val))
for _, branch := range node.repo.Status.Branches {
// Don't print the status of the current branch. It was already printed above.
if branch.Name == node.repo.Status.CurrentBranch {
continue
}
value += indent + printBranchStatus(branch)
}
return value
}
val := node.val + string(filepath.Separator)
shift := ""
if node.parent == nil {
// If node is a root, print its children on a new line without indentation.
shift = "\n"
} else if len(node.children) == 1 {
// If node has only a single child, print it on the same line as its parent.
// Setting node's depth to the same as parent's ensures that its children will be indented only once even if
// node's path has multiple levels above.
node.depth = node.parent.depth
p.length += len(val)
} else {
// If node has multiple children, print each of them on a new line
// and indent them once relative to the parent
node.depth = node.parent.depth + 1
shift = "\n" + strings.Repeat(" ", node.depth)
p.length = 0
}
for _, child := range node.children {
p.length += len(shift)
val += shift + p.PrintSmartTree(child)
p.length = 0
}
return val
}
func (p *SimpleTreePrinter) PrintSimpleTree(node *Node, tp treeprint.Tree) {
if node.children == nil {
tp.SetValue(node.val + " " + printWorktreeStatus(node.repo))
for _, branch := range node.repo.Status.Branches {
// Don't print the status of the current branch. It was already printed above.
if branch.Name == node.repo.Status.CurrentBranch {
continue
}
tp.AddNode(printBranchStatus(branch))
}
}
for _, child := range node.children {
branch := tp.AddBranch(child.val)
p.PrintSimpleTree(child, branch)
}
}

108
pkg/print/tree_test.go Normal file
View File

@@ -0,0 +1,108 @@
package print
import (
"fmt"
"git-get/pkg/git"
"strings"
"testing"
)
func TestTree(t *testing.T) {
var tests = []struct {
paths []string
want string
}{
{
[]string{
"root/github.com/grdl/repo1",
}, `
root/
github.com/grdl/repo1
`,
},
{
[]string{
"root/github.com/grdl/repo1",
"root/github.com/grdl/repo2",
}, `
root/
github.com/grdl/
repo1
repo2
`,
},
{
[]string{
"root/gitlab.com/grdl/repo1",
"root/github.com/grdl/repo1",
}, `
root/
gitlab.com/grdl/repo1
github.com/grdl/repo1
`,
},
{
[]string{
"root/gitlab.com/grdl/repo1",
"root/gitlab.com/grdl/repo2",
"root/gitlab.com/other/repo1",
"root/github.com/grdl/repo1",
"root/github.com/grdl/nested/repo2",
}, `
root/
gitlab.com/
grdl/
repo1
repo2
other/repo1
github.com/grdl/
repo1
nested/repo2
`,
},
{
[]string{
"root/gitlab.com/grdl/nested/repo1",
"root/gitlab.com/grdl/nested/repo2",
"root/gitlab.com/other/repo1",
}, `
root/
gitlab.com/
grdl/nested/
repo1
repo2
other/repo1
`,
},
{
[]string{
"root/gitlab.com/grdl/double/nested/repo1",
"root/gitlab.com/grdl/nested/repo2",
"root/gitlab.com/other/repo1",
}, `
root/
gitlab.com/
grdl/
double/nested/repo1
nested/repo2
other/repo1
`,
},
}
for i, test := range tests {
var repos []*git.Repo
for _, path := range test.paths {
repos = append(repos, git.NewRepo(nil, path)) //&Repo{path: path})
}
printer := SmartTreePrinter{}
// Leading and trailing newlines are added to test cases for readability. We also need to add them to the rendering result.
got := fmt.Sprintf("\n%s\n", printer.Print("root", repos))
// Rendered tree uses spaces for indentation but the test cases use tabs.
if got != strings.ReplaceAll(test.want, "\t", " ") {
t.Errorf("Failed test case %d, got: %+v; want: %+v", i, got, test.want)
}
}
}