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

Finish refactoring by replacing old pkg with new one

This commit is contained in:
Grzegorz Dlugoszewski
2020-05-28 16:34:44 +02:00
parent ca9be3d98f
commit 1bc3928cf5
14 changed files with 523 additions and 1432 deletions

View File

@@ -27,7 +27,7 @@ func Run(cmd *cobra.Command, args []string) error {
return err return err
} }
_, err = pkg.CloneRepo(url, ReposRoot) _, err = pkg.CloneRepo(url, ReposRoot, false)
return err return err
} }

View File

@@ -1,230 +0,0 @@
package new
import (
"io/ioutil"
pkgurl "net/url"
"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"
)
type TestRepo struct {
Repo *git.Repository
Path string
URL *pkgurl.URL
t *testing.T
}
func NewRepoEmpty(t *testing.T) *TestRepo {
dir := NewTempDir(t)
repo, err := git.PlainInit(dir, false)
checkFatal(t, err)
url, err := ParseURL("file://" + dir)
checkFatal(t, err)
return &TestRepo{
Repo: repo,
Path: dir,
URL: url,
t: t,
}
}
func NewRepoWithUntracked(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
return tr
}
func NewRepoWithStaged(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
return tr
}
func NewRepoWithCommit(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
tr.NewCommit("Initial commit")
return tr
}
func NewRepoWithModified(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
tr.NewCommit("Initial commit")
tr.WriteFile("README", "I'm modified")
return tr
}
func NewRepoWithIgnored(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile(".gitignore", "ignoreme")
tr.AddFile(".gitignore")
tr.NewCommit("Initial commit")
tr.WriteFile("ignoreme", "I'm being ignored")
return tr
}
func NewRepoWithLocalBranch(t *testing.T) *TestRepo {
tr := NewRepoWithCommit(t)
tr.NewBranch("local")
return tr
}
func NewRepoWithClonedBranch(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.NewBranch("local")
return tr
}
func NewRepoWithBranchAhead(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.WriteFile("new", "I'm a new file")
tr.AddFile("new")
tr.NewCommit("New commit")
return tr
}
func NewRepoWithBranchBehind(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
origin.WriteFile("origin.new", "I'm a new file on origin")
origin.AddFile("origin.new")
origin.NewCommit("New origin commit")
tr.Fetch()
return tr
}
func NewRepoWithBranchAheadAndBehind(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.WriteFile("local.new", "I'm a new file on local")
tr.AddFile("local.new")
tr.NewCommit("New local commit")
origin.WriteFile("origin.new", "I'm a new file on origin")
origin.AddFile("origin.new")
origin.NewCommit("New origin commit")
tr.Fetch()
return tr
}
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 *TestRepo) WriteFile(name string, content string) {
wt, err := r.Repo.Worktree()
checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
file, err := wt.Filesystem.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
checkFatal(r.t, errors.Wrap(err, "Failed opening a file"))
_, err = file.Write([]byte(content))
checkFatal(r.t, errors.Wrap(err, "Failed writing a file"))
}
func (r *TestRepo) AddFile(name string) {
wt, err := r.Repo.Worktree()
checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
_, err = wt.Add(name)
checkFatal(r.t, errors.Wrap(err, "Failed adding file to index"))
}
func (r *TestRepo) NewCommit(msg string) {
wt, err := r.Repo.Worktree()
checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
opts := &git.CommitOptions{
Author: &object.Signature{
Name: "Some Guy",
Email: "someguy@example.com",
When: time.Date(2000, 01, 01, 16, 00, 00, 0, time.UTC),
},
}
_, err = wt.Commit(msg, opts)
checkFatal(r.t, errors.Wrap(err, "Failed creating commit"))
}
func (r *TestRepo) NewBranch(name string) {
head, err := r.Repo.Head()
checkFatal(r.t, err)
ref := plumbing.NewHashReference(plumbing.NewBranchReferenceName(name), head.Hash())
err = r.Repo.Storer.SetReference(ref)
checkFatal(r.t, err)
}
func (r *TestRepo) Clone() *TestRepo {
dir := NewTempDir(r.t)
repo, err := CloneRepo(r.URL, dir, true)
checkFatal(r.t, err)
url, err := ParseURL("file://" + dir)
checkFatal(r.t, err)
return &TestRepo{
Repo: repo.repo,
Path: dir,
URL: url,
t: r.t,
}
}
func (r *TestRepo) Fetch() {
repo := &Repo{
repo: r.Repo,
}
err := repo.Fetch()
checkFatal(r.t, err)
}
func checkFatal(t *testing.T, err error) {
if err != nil {
t.Fatalf("%+v", err)
}
}

View File

@@ -1,76 +0,0 @@
package new
import (
"io"
"net/url"
"os"
"github.com/pkg/errors"
"github.com/go-git/go-git/v5"
)
type Repo struct {
repo *git.Repository
Status *RepoStatus
}
func CloneRepo(url *url.URL, path string, quiet bool) (r *Repo, err error) {
var output io.Writer
if !quiet {
output = os.Stdout
}
opts := &git.CloneOptions{
URL: url.String(),
Auth: nil,
RemoteName: git.DefaultRemoteName,
ReferenceName: "",
SingleBranch: false,
NoCheckout: false,
Depth: 0,
RecurseSubmodules: git.NoRecurseSubmodules,
Progress: output,
Tags: git.AllTags,
}
repo, err := git.PlainClone(path, false, opts)
if err != nil {
return nil, errors.Wrap(err, "Failed cloning repo")
}
return newRepo(repo), nil
}
func OpenRepo(path string) (r *Repo, err error) {
repo, err := git.PlainOpen(path)
if err != nil {
return nil, errors.Wrap(err, "Failed opening repo")
}
return newRepo(repo), nil
}
func newRepo(repo *git.Repository) *Repo {
return &Repo{
repo: repo,
Status: &RepoStatus{},
}
}
// Fetch performs a git fetch on all remotes
func (r *Repo) Fetch() error {
remotes, err := r.repo.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
}

View File

@@ -1,215 +0,0 @@
package new
import (
"sort"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/pkg/errors"
)
type RepoStatus struct {
HasUntrackedFiles bool
HasUncommittedChanges bool
Branches []*BranchStatus
}
type BranchStatus struct {
Name string
Upstream string
NeedsPull bool
NeedsPush bool
}
func (r *Repo) LoadStatus() error {
wt, err := r.repo.Worktree()
if err != nil {
return errors.Wrap(err, "Failed getting worktree")
}
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)
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 (r *Repo) loadBranchesStatus() error {
iter, err := r.repo.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. It's useful to have them sorted for printing and testing.
sort.Slice(r.Status.Branches, func(i, j int) bool {
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
}
needsPull, needsPush, err := r.needsPullOrPush(branch, upstream)
if err != nil {
return nil, err
}
bs.Upstream = upstream
bs.NeedsPush = needsPush
bs.NeedsPull = needsPull
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 upstreamn 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.repo.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) needsPullOrPush(localBranch string, upstreamBranch string) (needsPull bool, needsPush bool, err error) {
localHash, err := r.repo.ResolveRevision(plumbing.Revision(localBranch))
if err != nil {
return false, false, errors.Wrapf(err, "Failed resolving revision %s", localBranch)
}
upstreamHash, err := r.repo.ResolveRevision(plumbing.Revision(upstreamBranch))
if err != nil {
return false, false, errors.Wrapf(err, "Failed resolving revision %s", upstreamBranch)
}
localCommit, err := r.repo.CommitObject(*localHash)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding a commit for hash %s", localHash.String())
}
upstreamCommit, err := r.repo.CommitObject(*upstreamHash)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding a commit for hash %s", upstreamHash.String())
}
// If local branch hash is the same as upstream, it means there is no difference between local and upstream
if *localHash == *upstreamHash {
return false, false, nil
}
commons, err := localCommit.MergeBase(upstreamCommit)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding common ancestors for branches %s & %s", localBranch, upstreamBranch)
}
if len(commons) == 0 {
// TODO: No common ancestors. This should be an error
return false, false, nil
}
if len(commons) > 1 {
// TODO: multiple best ancestors. How to handle this?
return false, false, nil
}
mergeBase := commons[0]
// If merge base is the same as upstream branch, local branch is ahead and push is needed
// If merge base is the same as local branch, local branch is behind and pull is needed
// If merge base is something else, branches have diverged and merge is needed (both pull and push)
// ref: https://stackoverflow.com/a/17723781/1085632
if mergeBase.Hash == *upstreamHash {
return false, true, nil
}
if mergeBase.Hash == *localHash {
return true, false, nil
}
return true, true, nil
}

View File

@@ -1,149 +0,0 @@
package new
import (
"reflect"
"testing"
)
func TestStatus(t *testing.T) {
var tests = []struct {
makeTestRepo func(*testing.T) *TestRepo
want *RepoStatus
}{
{NewRepoEmpty, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: nil,
}},
{NewRepoWithUntracked, &RepoStatus{
HasUntrackedFiles: true,
HasUncommittedChanges: false,
Branches: nil,
}},
{NewRepoWithStaged, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
Branches: nil,
}},
{NewRepoWithCommit, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithModified, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithIgnored, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithLocalBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "local",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
}, {
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithClonedBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "local",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
}, {
Name: "master",
Upstream: "origin/master",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithBranchAhead, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: false,
NeedsPush: true,
},
},
}},
{NewRepoWithBranchBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: true,
NeedsPush: false,
},
},
}},
{NewRepoWithBranchAheadAndBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: true,
NeedsPush: true,
},
},
}},
}
for _, test := range tests {
tr := test.makeTestRepo(t)
repo, err := OpenRepo(tr.Path)
checkFatal(t, err)
err = repo.LoadStatus()
checkFatal(t, err)
if !reflect.DeepEqual(repo.Status, test.want) {
t.Errorf("Wrong repo status, got: %+v; want: %+v", repo.Status, test.want)
}
}
}

View File

@@ -1,68 +0,0 @@
package new
import (
urlpkg "net/url"
"path"
"regexp"
"strings"
"github.com/pkg/errors"
)
// 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 Path")
}
}
if url.Host == "" && url.Path == "" {
return nil, errors.New("Parsed Path is empty")
}
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 https
if url.Scheme == "" {
url.Scheme = "https"
}
// TODO: Default to github host
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
}

View File

@@ -1,81 +0,0 @@
package new
import (
"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/", "local/grdl/git-get"},
{"file://local/grdl/git-get", "local/grdl/git-get"},
}
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; want: %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, want: error", in, got)
}
}
}

View File

@@ -2,23 +2,142 @@ package pkg
import ( import (
"io/ioutil" "io/ioutil"
pkgurl "net/url"
"os" "os"
"path"
"testing" "testing"
"time" "time"
"github.com/pkg/errors" "github.com/go-git/go-git/v5/plumbing"
git "github.com/libgit2/git2go/v30" "github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5"
"github.com/pkg/errors"
) )
func checkFatal(t *testing.T, err error) { type TestRepo struct {
if err != nil { Repo *git.Repository
t.Fatalf("%+v", err) Path string
URL *pkgurl.URL
t *testing.T
}
func NewRepoEmpty(t *testing.T) *TestRepo {
dir := NewTempDir(t)
repo, err := git.PlainInit(dir, false)
checkFatal(t, err)
url, err := ParseURL("file://" + dir)
checkFatal(t, err)
return &TestRepo{
Repo: repo,
Path: dir,
URL: url,
t: t,
} }
} }
func newTempDir(t *testing.T) string { func NewRepoWithUntracked(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
return tr
}
func NewRepoWithStaged(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
return tr
}
func NewRepoWithCommit(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
tr.NewCommit("Initial commit")
return tr
}
func NewRepoWithModified(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile("README", "I'm a README file")
tr.AddFile("README")
tr.NewCommit("Initial commit")
tr.WriteFile("README", "I'm modified")
return tr
}
func NewRepoWithIgnored(t *testing.T) *TestRepo {
tr := NewRepoEmpty(t)
tr.WriteFile(".gitignore", "ignoreme")
tr.AddFile(".gitignore")
tr.NewCommit("Initial commit")
tr.WriteFile("ignoreme", "I'm being ignored")
return tr
}
func NewRepoWithLocalBranch(t *testing.T) *TestRepo {
tr := NewRepoWithCommit(t)
tr.NewBranch("local")
return tr
}
func NewRepoWithClonedBranch(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.NewBranch("local")
return tr
}
func NewRepoWithBranchAhead(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.WriteFile("new", "I'm a new file")
tr.AddFile("new")
tr.NewCommit("New commit")
return tr
}
func NewRepoWithBranchBehind(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
origin.WriteFile("origin.new", "I'm a new file on origin")
origin.AddFile("origin.new")
origin.NewCommit("New origin commit")
tr.Fetch()
return tr
}
func NewRepoWithBranchAheadAndBehind(t *testing.T) *TestRepo {
origin := NewRepoWithCommit(t)
tr := origin.Clone()
tr.WriteFile("local.new", "I'm a new file on local")
tr.AddFile("local.new")
tr.NewCommit("New local commit")
origin.WriteFile("origin.new", "I'm a new file on origin")
origin.AddFile("origin.new")
origin.NewCommit("New origin commit")
tr.Fetch()
return tr
}
func NewTempDir(t *testing.T) string {
dir, err := ioutil.TempDir("", "git-get-repo-") dir, err := ioutil.TempDir("", "git-get-repo-")
checkFatal(t, errors.Wrap(err, "Failed creating test repo directory")) checkFatal(t, errors.Wrap(err, "Failed creating test repo directory"))
@@ -33,108 +152,79 @@ func newTempDir(t *testing.T) string {
return dir return dir
} }
func newTestRepo(t *testing.T) *git.Repository { func (r *TestRepo) WriteFile(name string, content string) {
dir := newTempDir(t) wt, err := r.Repo.Worktree()
repo, err := git.InitRepository(dir, false) checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
checkFatal(t, errors.Wrap(err, "Failed initializing a temp repo"))
return repo file, err := wt.Filesystem.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
checkFatal(r.t, errors.Wrap(err, "Failed opening a file"))
_, err = file.Write([]byte(content))
checkFatal(r.t, errors.Wrap(err, "Failed writing a file"))
} }
func createFile(t *testing.T, repo *git.Repository, name string) { func (r *TestRepo) AddFile(name string) {
err := ioutil.WriteFile(path.Join(repo.Workdir(), name), []byte("I'm a file"), 0644) wt, err := r.Repo.Worktree()
checkFatal(t, errors.Wrap(err, "Failed writing a file")) checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
_, err = wt.Add(name)
checkFatal(r.t, errors.Wrap(err, "Failed adding file to index"))
} }
func stageFile(t *testing.T, repo *git.Repository, name string) { func (r *TestRepo) NewCommit(msg string) {
index, err := repo.Index() wt, err := r.Repo.Worktree()
checkFatal(t, errors.Wrap(err, "Failed getting repo index")) checkFatal(r.t, errors.Wrap(err, "Failed getting worktree"))
err = index.AddByPath(name) opts := &git.CommitOptions{
checkFatal(t, errors.Wrap(err, "Failed adding file to index")) Author: &object.Signature{
Name: "Some Guy",
err = index.Write() Email: "someguy@example.com",
checkFatal(t, errors.Wrap(err, "Failed writing index")) When: time.Date(2000, 01, 01, 16, 00, 00, 0, time.UTC),
} },
func createCommit(t *testing.T, repo *git.Repository, message string) *git.Commit {
index, err := repo.Index()
checkFatal(t, errors.Wrap(err, "Failed getting repo index"))
treeId, err := index.WriteTree()
checkFatal(t, errors.Wrap(err, "Failed building tree from index"))
tree, err := repo.LookupTree(treeId)
checkFatal(t, errors.Wrap(err, "Failed looking up tree id"))
signature := &git.Signature{
Name: "Some Guy",
Email: "someguy@example.com",
When: time.Date(2000, 01, 01, 16, 00, 00, 0, time.UTC),
} }
empty, err := repo.IsEmpty() _, err = wt.Commit(msg, opts)
checkFatal(t, errors.Wrap(err, "Failed checking if repo is empty")) checkFatal(r.t, errors.Wrap(err, "Failed creating commit"))
var commitId *git.Oid
if !empty {
currentBranch, err := repo.Head()
checkFatal(t, errors.Wrap(err, "Failed getting current branch"))
currentTip, err := repo.LookupCommit(currentBranch.Target())
checkFatal(t, errors.Wrap(err, "Failed getting current tip"))
commitId, err = repo.CreateCommit("HEAD", signature, signature, message, tree, currentTip)
} else {
commitId, err = repo.CreateCommit("HEAD", signature, signature, message, tree)
}
commit, err := repo.LookupCommit(commitId)
checkFatal(t, errors.Wrap(err, "Failed looking up a commit"))
return commit
} }
func createBranch(t *testing.T, repo *git.Repository, name string) *git.Branch { func (r *TestRepo) NewBranch(name string) {
head, err := repo.Head() head, err := r.Repo.Head()
checkFatal(t, errors.Wrap(err, "Failed getting repo head")) checkFatal(r.t, err)
commit, err := repo.LookupCommit(head.Target()) ref := plumbing.NewHashReference(plumbing.NewBranchReferenceName(name), head.Hash())
checkFatal(t, errors.Wrap(err, "Failed getting commit id from head"))
branch, err := repo.CreateBranch(name, commit, false) err = r.Repo.Storer.SetReference(ref)
checkFatal(t, errors.Wrap(err, "Failed creating branch")) checkFatal(r.t, err)
return branch
} }
func checkoutBranch(t *testing.T, repo *git.Repository, name string) { func (r *TestRepo) Clone() *TestRepo {
branch, err := repo.LookupBranch(name, git.BranchAll) dir := NewTempDir(r.t)
// If branch can't be found, let's check if it's a remote branch repo, err := CloneRepo(r.URL, dir, true)
if branch == nil { checkFatal(r.t, err)
branch, err = repo.LookupBranch("origin/"+name, git.BranchAll)
url, err := ParseURL("file://" + dir)
checkFatal(r.t, err)
return &TestRepo{
Repo: repo.repo,
Path: dir,
URL: url,
t: r.t,
}
}
func (r *TestRepo) Fetch() {
repo := &Repo{
repo: r.Repo,
}
err := repo.Fetch()
checkFatal(r.t, err)
}
func checkFatal(t *testing.T, err error) {
if err != nil {
t.Fatalf("%+v", err)
} }
checkFatal(t, errors.Wrap(err, "Failed looking up branch"))
// If branch is remote, we need to create a local one first
if branch.IsRemote() {
commit, err := repo.LookupCommit(branch.Target())
checkFatal(t, errors.Wrap(err, "Failed looking up commit"))
localBranch, err := repo.CreateBranch(name, commit, false)
checkFatal(t, errors.Wrap(err, "Failed creating local branch"))
err = localBranch.SetUpstream("origin/" + name)
checkFatal(t, errors.Wrap(err, "Failed setting upstream"))
}
err = repo.SetHead("refs/heads/" + name)
checkFatal(t, errors.Wrap(err, "Failed setting head"))
options := &git.CheckoutOpts{
Strategy: git.CheckoutForce,
}
err = repo.CheckoutHead(options)
checkFatal(t, errors.Wrap(err, "Failed checking out tree"))
} }

View File

@@ -1,14 +1,13 @@
package pkg package pkg
import ( import (
urlpkg "net/url" "io"
"net/url"
"os" "os"
"path"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors" "github.com/pkg/errors"
git "github.com/libgit2/git2go/v30" "github.com/go-git/go-git/v5"
) )
type Repo struct { type Repo struct {
@@ -16,112 +15,62 @@ type Repo struct {
Status *RepoStatus Status *RepoStatus
} }
func credentialsCallback(url string, username string, allowedTypes git.CredType) (*git.Cred, error) { func CloneRepo(url *url.URL, path string, quiet bool) (r *Repo, err error) {
home, err := homedir.Dir() var output io.Writer
if err != nil { if !quiet {
return nil, errors.Wrap(err, "Failed getting user home directory") output = os.Stdout
} }
// TODO: Add option to provide custom path opts := &git.CloneOptions{
publicKey := path.Join(home, ".ssh", "id_rsa.pub") URL: url.String(),
privateKey := path.Join(home, ".ssh", "id_rsa") Auth: nil,
RemoteName: git.DefaultRemoteName,
cred, err := git.NewCredSshKey(username, publicKey, privateKey, "") ReferenceName: "",
if err != nil { SingleBranch: false,
return nil, errors.Wrap(err, "Failed getting SSH credentials") NoCheckout: false,
Depth: 0,
RecurseSubmodules: git.NoRecurseSubmodules,
Progress: output,
Tags: git.AllTags,
} }
return cred, err
repo, err := git.PlainClone(path, false, opts)
if err != nil {
return nil, errors.Wrap(err, "Failed cloning repo")
}
return newRepo(repo), nil
} }
func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode { func OpenRepo(path string) (r *Repo, err error) {
// TODO: check the certificate repo, err := git.PlainOpen(path)
return 0
}
func CloneRepo(url *urlpkg.URL, repoRoot string) (path string, err error) {
repoPath := URLToPath(url)
path, err = MakeDir(repoRoot, repoPath)
if err != nil {
return path, err
}
options := &git.CloneOptions{
Bare: false,
CheckoutBranch: "",
FetchOptions: &git.FetchOptions{
RemoteCallbacks: git.RemoteCallbacks{
CredentialsCallback: credentialsCallback,
CertificateCheckCallback: certificateCheckCallback,
},
},
}
_, err = git.Clone(url.String(), path, options)
if err != nil {
_ = os.RemoveAll(path)
return path, errors.Wrap(err, "Failed cloning repo")
}
return path, nil
}
func OpenRepo(path string) (*Repo, error) {
r, err := git.OpenRepository(path)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed opening repo") return nil, errors.Wrap(err, "Failed opening repo")
} }
repoStatus, err := loadStatus(r) return newRepo(repo), nil
if err != nil {
return nil, err
}
repo := &Repo{
repo: r,
Status: repoStatus,
}
return repo, nil
} }
func (r *Repo) Reload() error { func newRepo(repo *git.Repository) *Repo {
status, err := loadStatus(r.repo) return &Repo{
if err != nil { repo: repo,
return err Status: &RepoStatus{},
} }
r.Status = status
return nil
} }
// Fetch performs a git fetch on all remotes
func (r *Repo) Fetch() error { func (r *Repo) Fetch() error {
remoteNames, err := r.repo.Remotes.List() remotes, err := r.repo.Remotes()
if err != nil { if err != nil {
return errors.Wrap(err, "Failed listing remoteNames") return errors.Wrap(err, "Failed getting remotes")
} }
for _, name := range remoteNames { for _, remote := range remotes {
remote, err := r.repo.Remotes.Lookup(name) err = remote.Fetch(&git.FetchOptions{})
if err != nil { if err != nil {
return errors.Wrap(err, "Failed looking up remote") return errors.Wrapf(err, "Failed fetching remote %s", remote.Config().Name)
}
err = remote.Fetch(nil, nil, "")
if err != nil {
return errors.Wrap(err, "Failed fetching remote")
} }
} }
return nil return nil
} }
func MakeDir(repoRoot, repoPath string) (string, error) {
dir := path.Join(repoRoot, repoPath)
err := os.MkdirAll(dir, 0775)
if err != nil {
return "", errors.Wrap(err, "Failed creating repo directory")
}
return dir, nil
}

View File

@@ -1,66 +0,0 @@
package pkg
import (
urlpkg "net/url"
"os"
"testing"
)
func TestFetch(t *testing.T) {
// Create origin repo with a single commit in master
origin := newTestRepo(t)
createFile(t, origin, "file")
stageFile(t, origin, "file")
createCommit(t, origin, "Initial commit")
// Clone the origin repo
repoRoot := newTempDir(t)
url, err := urlpkg.Parse(origin.Path())
checkFatal(t, err)
path, err := CloneRepo(url, repoRoot)
checkFatal(t, err)
// Open cloned repo and load its status
repo, err := OpenRepo(path)
checkFatal(t, err)
// Check cloned status. It should not be behind origin
if repo.Status.Branches["master"].Behind != 0 {
t.Errorf("Master should not be behind")
}
// Add another commit to origin
createFile(t, origin, "anotherFile")
stageFile(t, origin, "anotherFile")
createCommit(t, origin, "Second commit")
// Fetch cloned repo and check the status again
err = repo.Fetch()
checkFatal(t, err)
err = repo.Reload()
checkFatal(t, err)
// Cloned master should now be 1 commit behind origin
if repo.Status.Branches["master"].Behind != 1 {
t.Errorf("Master should be 1 commit behind")
}
if repo.Status.Branches["master"].Ahead != 0 {
t.Errorf("Master should not be ahead")
}
}
func TestMakeDir(t *testing.T) {
repoRoot := newTempDir(t)
repoPath := "github.com/grdl/git-get"
dir, err := MakeDir(repoRoot, repoPath)
checkFatal(t, err)
stat, err := os.Stat(dir)
checkFatal(t, err)
if !stat.IsDir() {
t.Errorf("Path is not a directory: %s", dir)
}
}

View File

@@ -1,153 +1,215 @@
package pkg package pkg
import ( import (
git "github.com/libgit2/git2go/v30" "sort"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
type RepoStatus struct { type RepoStatus struct {
HasUntrackedFiles bool HasUntrackedFiles bool
HasUncommittedChanges bool HasUncommittedChanges bool
Branches map[string]BranchStatus Branches []*BranchStatus
} }
type BranchStatus struct { type BranchStatus struct {
Name string Name string
IsRemote bool Upstream string
HasUpstream bool NeedsPull bool
NeedsPull bool NeedsPush bool
NeedsPush bool
Ahead int
Behind int
} }
func loadStatus(r *git.Repository) (*RepoStatus, error) { func (r *Repo) LoadStatus() error {
entries, err := statusEntries(r) wt, err := r.repo.Worktree()
if err != nil { if err != nil {
return nil, err return errors.Wrap(err, "Failed getting worktree")
} }
branches, err := branches(r) status, err := wt.Status()
if err != nil { if err != nil {
return nil, err return errors.Wrap(err, "Failed getting worktree status")
} }
status := &RepoStatus{ r.Status.HasUncommittedChanges = hasUncommitted(status)
Branches: branches, r.Status.HasUntrackedFiles = hasUntracked(status)
err = r.loadBranchesStatus()
if err != nil {
return err
} }
for _, entry := range entries { return nil
switch entry.Status { }
case git.StatusWtNew:
status.HasUntrackedFiles = true // hasUntracked returns true if there are any untracked files in the worktree
case git.StatusIndexNew: func hasUntracked(status git.Status) bool {
status.HasUncommittedChanges = true for _, fs := range status {
if fs.Worktree == git.Untracked || fs.Staging == git.Untracked {
return true
} }
} }
return status, nil return false
} }
func statusEntries(r *git.Repository) ([]git.StatusEntry, error) { // hasUncommitted returns true if there are any uncommitted (but tracked) files in the worktree
opts := &git.StatusOptions{ func hasUncommitted(status git.Status) bool {
Show: git.StatusShowIndexAndWorkdir, // If repo is clean it means every file in worktree and staging has 'Unmodified' state
Flags: git.StatusOptIncludeUntracked, if status.IsClean() {
return false
} }
status, err := r.StatusList(opts) // 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 (r *Repo) loadBranchesStatus() error {
iter, err := r.repo.Branches()
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed getting repository status list") return errors.Wrap(err, "Failed getting branches iterator")
} }
entryCount, err := status.EntryCount() err = iter.ForEach(func(reference *plumbing.Reference) error {
if err != nil { bs, err := r.newBranchStatus(reference.Name().Short())
return nil, errors.Wrap(err, "Failed getting repository status list count")
}
var entries []git.StatusEntry
for i := 0; i < entryCount; i++ {
entry, err := status.ByIndex(i)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed getting repository status entry") return err
} }
entries = append(entries, entry) r.Status.Branches = append(r.Status.Branches, bs)
}
return entries, nil
}
func branches(r *git.Repository) (map[string]BranchStatus, error) {
iter, err := r.NewBranchIterator(git.BranchAll)
if err != nil {
return nil, errors.Wrap(err, "Failed creating branch iterator")
}
var branches []*git.Branch
err = iter.ForEach(func(branch *git.Branch, branchType git.BranchType) error {
branches = append(branches, branch)
return nil return nil
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed iterating over branches") return errors.Wrap(err, "Failed iterating over branches")
} }
statuses := make(map[string]BranchStatus) // Sort branches by name. It's useful to have them sorted for printing and testing.
for _, branch := range branches { sort.Slice(r.Status.Branches, func(i, j int) bool {
status, err := branchStatus(branch) return strings.Compare(r.Status.Branches[i].Name, r.Status.Branches[j].Name) < 0
if err != nil { })
// TODO: Handle error. We should tell user that we couldn't read status of that branch but probably shouldn't exit return nil
continue
}
statuses[status.Name] = status
}
return statuses, nil
} }
func branchStatus(branch *git.Branch) (BranchStatus, error) { func (r *Repo) newBranchStatus(branch string) (*BranchStatus, error) {
var status BranchStatus bs := &BranchStatus{
Name: branch,
}
name, err := branch.Name() upstream, err := r.upstream(branch)
if err != nil { if err != nil {
return status, errors.Wrap(err, "Failed getting branch name") return nil, err
}
status.Name = name
// If branch is a remote one, return immediately. Upstream can only be found for local branches.
if branch.IsRemote() {
status.IsRemote = true
return status, nil
} }
upstream, err := branch.Upstream() if upstream == "" {
if err != nil && !git.IsErrorCode(err, git.ErrNotFound) { return bs, nil
return status, errors.Wrap(err, "Failed getting branch upstream")
} }
// If there's no upstream, return immediately. Ahead/Behind can only be found when upstream exists. needsPull, needsPush, err := r.needsPullOrPush(branch, upstream)
if upstream == nil {
return status, nil
}
status.HasUpstream = true
ahead, behind, err := branch.Owner().AheadBehind(branch.Target(), upstream.Target())
if err != nil { if err != nil {
return status, errors.Wrap(err, "Failed getting ahead/behind information") return nil, err
} }
status.Ahead = ahead bs.Upstream = upstream
status.Behind = behind bs.NeedsPush = needsPush
bs.NeedsPull = needsPull
if ahead > 0 { return bs, nil
status.NeedsPush = true }
}
// upstream finds if a given branch tracks an upstream.
if behind > 0 { // Returns found upstream branch name (eg, origin/master) or empty string if branch doesn't track an upstream.
status.NeedsPull = true //
} // 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:
return status, nil // "remote" - name of the remote containing upstreamn 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.repo.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) needsPullOrPush(localBranch string, upstreamBranch string) (needsPull bool, needsPush bool, err error) {
localHash, err := r.repo.ResolveRevision(plumbing.Revision(localBranch))
if err != nil {
return false, false, errors.Wrapf(err, "Failed resolving revision %s", localBranch)
}
upstreamHash, err := r.repo.ResolveRevision(plumbing.Revision(upstreamBranch))
if err != nil {
return false, false, errors.Wrapf(err, "Failed resolving revision %s", upstreamBranch)
}
localCommit, err := r.repo.CommitObject(*localHash)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding a commit for hash %s", localHash.String())
}
upstreamCommit, err := r.repo.CommitObject(*upstreamHash)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding a commit for hash %s", upstreamHash.String())
}
// If local branch hash is the same as upstream, it means there is no difference between local and upstream
if *localHash == *upstreamHash {
return false, false, nil
}
commons, err := localCommit.MergeBase(upstreamCommit)
if err != nil {
return false, false, errors.Wrapf(err, "Failed finding common ancestors for branches %s & %s", localBranch, upstreamBranch)
}
if len(commons) == 0 {
// TODO: No common ancestors. This should be an error
return false, false, nil
}
if len(commons) > 1 {
// TODO: multiple best ancestors. How to handle this?
return false, false, nil
}
mergeBase := commons[0]
// If merge base is the same as upstream branch, local branch is ahead and push is needed
// If merge base is the same as local branch, local branch is behind and pull is needed
// If merge base is something else, branches have diverged and merge is needed (both pull and push)
// ref: https://stackoverflow.com/a/17723781/1085632
if mergeBase.Hash == *upstreamHash {
return false, true, nil
}
if mergeBase.Hash == *localHash {
return true, false, nil
}
return true, true, nil
} }

View File

@@ -1,274 +1,149 @@
package pkg package pkg
import ( import (
urlpkg "net/url"
"reflect" "reflect"
"testing" "testing"
git "github.com/libgit2/git2go/v30"
) )
func TestStatusWithEmptyRepo(t *testing.T) { func TestStatus(t *testing.T) {
repo := newTestRepo(t)
entries, err := statusEntries(repo)
checkFatal(t, err)
if len(entries) != 0 {
t.Errorf("Empty repo should have no status entries")
}
status, err := loadStatus(repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusWithUntrackedFile(t *testing.T) {
repo := newTestRepo(t)
createFile(t, repo, "SomeFile")
entries, err := statusEntries(repo)
checkFatal(t, err)
if len(entries) != 1 {
t.Errorf("Repo with untracked file should have only one status entry")
}
if entries[0].Status != git.StatusWtNew {
t.Errorf("Invalid status, got %d; want %d", entries[0].Status, git.StatusWtNew)
}
status, err := loadStatus(repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: true,
HasUncommittedChanges: false,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusWithUnstagedFile(t *testing.T) {
//todo
}
func TestStatusWithUntrackedButIgnoredFile(t *testing.T) {
//todo
}
func TestStatusWithStagedFile(t *testing.T) {
repo := newTestRepo(t)
createFile(t, repo, "SomeFile")
stageFile(t, repo, "SomeFile")
entries, err := statusEntries(repo)
checkFatal(t, err)
if len(entries) != 1 {
t.Errorf("Repo with staged file should have only one status entry")
}
if entries[0].Status != git.StatusIndexNew {
t.Errorf("Invalid status, got %d; want %d", entries[0].Status, git.StatusIndexNew)
}
status, err := loadStatus(repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusWithSingleCommit(t *testing.T) {
repo := newTestRepo(t)
createFile(t, repo, "SomeFile")
stageFile(t, repo, "SomeFile")
createCommit(t, repo, "Initial commit")
entries, err := statusEntries(repo)
checkFatal(t, err)
if len(entries) != 0 {
t.Errorf("Repo with no uncommitted files should have no status entries")
}
status, err := loadStatus(repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusWithMultipleCommits(t *testing.T) {
repo := newTestRepo(t)
createFile(t, repo, "SomeFile")
stageFile(t, repo, "SomeFile")
createCommit(t, repo, "Initial commit")
createFile(t, repo, "AnotherFile")
stageFile(t, repo, "AnotherFile")
createCommit(t, repo, "Second commit")
entries, err := statusEntries(repo)
checkFatal(t, err)
if len(entries) != 0 {
t.Errorf("Repo with no uncommitted files should have no status entries")
}
status, err := loadStatus(repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusCloned(t *testing.T) {
origin := newTestRepo(t)
repoRoot := newTempDir(t)
url, err := urlpkg.Parse(origin.Path())
checkFatal(t, err)
path, err := CloneRepo(url, repoRoot)
checkFatal(t, err)
repo, err := OpenRepo(path)
checkFatal(t, err)
status, err := loadStatus(repo.repo)
checkFatal(t, err)
want := &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: status.Branches,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestBranchNewLocal(t *testing.T) {
repo := newTestRepo(t)
createFile(t, repo, "file")
stageFile(t, repo, "file")
createCommit(t, repo, "Initial commit")
branch := createBranch(t, repo, "branch")
status, err := branchStatus(branch)
checkFatal(t, err)
want := BranchStatus{
Name: "branch",
IsRemote: false,
HasUpstream: false,
NeedsPull: false,
NeedsPush: false,
Ahead: 0,
Behind: 0,
}
if status != want {
t.Errorf("Wrong branch status, got %+v; want %+v", status, want)
}
}
func TestBranchCloned(t *testing.T) {
origin := newTestRepo(t)
createFile(t, origin, "file")
stageFile(t, origin, "file")
createCommit(t, origin, "Initial commit")
createBranch(t, origin, "branch")
repoRoot := newTempDir(t)
url, err := urlpkg.Parse(origin.Path())
checkFatal(t, err)
path, err := CloneRepo(url, repoRoot)
checkFatal(t, err)
repo, err := OpenRepo(path)
checkFatal(t, err)
createBranch(t, repo.repo, "local")
checkoutBranch(t, repo.repo, "branch")
createFile(t, repo.repo, "anotherFile")
stageFile(t, repo.repo, "anotherFile")
createCommit(t, repo.repo, "Second commit")
err = repo.Reload()
checkFatal(t, err)
var tests = []struct { var tests = []struct {
got BranchStatus makeTestRepo func(*testing.T) *TestRepo
want BranchStatus want *RepoStatus
}{ }{
{repo.Status.Branches["master"], BranchStatus{ {NewRepoEmpty, &RepoStatus{
Name: "master", HasUntrackedFiles: false,
IsRemote: false, HasUncommittedChanges: false,
HasUpstream: true, Branches: nil,
}}, }},
{repo.Status.Branches["origin/master"], BranchStatus{ {NewRepoWithUntracked, &RepoStatus{
Name: "origin/master", HasUntrackedFiles: true,
IsRemote: true, HasUncommittedChanges: false,
HasUpstream: false, Branches: nil,
}}, }},
{repo.Status.Branches["branch"], BranchStatus{ {NewRepoWithStaged, &RepoStatus{
Name: "branch", HasUntrackedFiles: false,
IsRemote: false, HasUncommittedChanges: true,
HasUpstream: true, Branches: nil,
Ahead: 1,
NeedsPush: true,
}}, }},
{repo.Status.Branches["origin/branch"], BranchStatus{ {NewRepoWithCommit, &RepoStatus{
Name: "origin/branch", HasUntrackedFiles: false,
IsRemote: true, HasUncommittedChanges: false,
HasUpstream: false, Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}}, }},
{repo.Status.Branches["local"], BranchStatus{ {NewRepoWithModified, &RepoStatus{
Name: "local", HasUntrackedFiles: false,
IsRemote: false, HasUncommittedChanges: true,
HasUpstream: false, Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithIgnored, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithLocalBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "local",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
}, {
Name: "master",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithClonedBranch, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "local",
Upstream: "",
NeedsPull: false,
NeedsPush: false,
}, {
Name: "master",
Upstream: "origin/master",
NeedsPull: false,
NeedsPush: false,
},
},
}},
{NewRepoWithBranchAhead, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: false,
NeedsPush: true,
},
},
}},
{NewRepoWithBranchBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: true,
NeedsPush: false,
},
},
}},
{NewRepoWithBranchAheadAndBehind, &RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
Branches: []*BranchStatus{
{
Name: "master",
Upstream: "origin/master",
NeedsPull: true,
NeedsPush: true,
},
},
}}, }},
} }
for _, test := range tests { for _, test := range tests {
if !reflect.DeepEqual(test.got, test.want) { tr := test.makeTestRepo(t)
t.Errorf("Wrong branch status, got %+v; want %+v", test.got, test.want)
repo, err := OpenRepo(tr.Path)
checkFatal(t, err)
err = repo.LoadStatus()
checkFatal(t, err)
if !reflect.DeepEqual(repo.Status, test.want) {
t.Errorf("Wrong repo status, got: %+v; want: %+v", repo.Status, test.want)
} }
} }
} }

View File

@@ -14,7 +14,7 @@ import (
var scpSyntax = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`) var scpSyntax = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)
func ParseURL(rawURL string) (url *urlpkg.URL, err error) { func ParseURL(rawURL string) (url *urlpkg.URL, err error) {
// If rawURL matches the SCP-like syntax, convert it into a standard ssh URL. // 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 // eg, git@github.com:user/repo => ssh://git@github.com/user/repo
if m := scpSyntax.FindStringSubmatch(rawURL); m != nil { if m := scpSyntax.FindStringSubmatch(rawURL); m != nil {
url = &urlpkg.URL{ url = &urlpkg.URL{
@@ -26,12 +26,12 @@ func ParseURL(rawURL string) (url *urlpkg.URL, err error) {
} else { } else {
url, err = urlpkg.Parse(rawURL) url, err = urlpkg.Parse(rawURL)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed parsing URL") return nil, errors.Wrap(err, "Failed parsing Path")
} }
} }
if url.Host == "" && url.Path == "" { if url.Host == "" && url.Path == "" {
return nil, errors.New("Parsed URL is empty") return nil, errors.New("Parsed Path is empty")
} }
if url.Scheme == "git+ssh" { if url.Scheme == "git+ssh" {

View File

@@ -51,13 +51,13 @@ func TestURLParse(t *testing.T) {
for _, test := range tests { for _, test := range tests {
url, err := ParseURL(test.in) url, err := ParseURL(test.in)
if err != nil { if err != nil {
t.Errorf("Error parsing URL: %+v", err) t.Errorf("Error parsing Path: %+v", err)
} }
got := URLToPath(url) got := URLToPath(url)
if got != test.want { if got != test.want {
t.Errorf("Wrong result of parsing URL: %s, got: %s; want: %s", test.in, got, test.want) t.Errorf("Wrong result of parsing Path: %s, got: %s; want: %s", test.in, got, test.want)
} }
} }
} }
@@ -65,17 +65,17 @@ func TestURLParse(t *testing.T) {
func TestInvalidURLParse(t *testing.T) { func TestInvalidURLParse(t *testing.T) {
invalidURLs := []string{ invalidURLs := []string{
"", "",
//TODO: This URL is technically a correct scp-like syntax. Not sure how to handle it //TODO: This Path is technically a correct scp-like syntax. Not sure how to handle it
"github.com:grdl/git-git.get.git", "github.com:grdl/git-git.get.git",
//TODO: Is this a valid git URL? //TODO: Is this a valid git Path?
//"git@github.com:1234:grdl/git-get.git", //"git@github.com:1234:grdl/git-get.git",
} }
for _, in := range invalidURLs { for _, in := range invalidURLs {
got, err := ParseURL(in) got, err := ParseURL(in)
if err == nil { if err == nil {
t.Errorf("Wrong result of parsing invalid URL: %s, got: %s, want: error", in, got) t.Errorf("Wrong result of parsing invalid Path: %s, got: %s, want: error", in, got)
} }
} }
} }