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

Add cobra commands and update project folder structure

This commit is contained in:
Grzegorz Dlugoszewski
2020-05-20 11:37:16 +02:00
parent 4b8b1d52f0
commit ac765c9c06
12 changed files with 196 additions and 30 deletions

91
pkg/branch.go Normal file
View File

@@ -0,0 +1,91 @@
package pkg
import (
git "github.com/libgit2/git2go/v30"
"github.com/pkg/errors"
)
type BranchStatus struct {
Name string
IsRemote bool
HasUpstream bool
NeedsPull bool
NeedsPush bool
Ahead int
Behind int
}
func Branches(repo *git.Repository) (map[string]BranchStatus, error) {
iter, err := repo.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
})
if err != nil {
return nil, errors.Wrap(err, "Failed iterating over branches")
}
statuses := make(map[string]BranchStatus)
for _, branch := range branches {
status, err := NewBranchStatus(repo, branch)
if err != nil {
// TODO: Handle error. We should tell user that we couldn't read status of that branch but probably shouldn't exit
continue
}
statuses[status.Name] = status
}
return statuses, nil
}
func NewBranchStatus(repo *git.Repository, branch *git.Branch) (BranchStatus, error) {
var status BranchStatus
name, err := branch.Name()
if err != nil {
return status, errors.Wrap(err, "Failed getting branch name")
}
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 err != nil && !git.IsErrorCode(err, git.ErrNotFound) {
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.
if upstream == nil {
return status, nil
}
status.HasUpstream = true
ahead, behind, err := repo.AheadBehind(branch.Target(), upstream.Target())
if err != nil {
return status, errors.Wrap(err, "Failed getting ahead/behind information")
}
status.Ahead = ahead
status.Behind = behind
if ahead > 0 {
status.NeedsPush = true
}
if behind > 0 {
status.NeedsPull = true
}
return status, nil
}

93
pkg/branch_test.go Normal file
View File

@@ -0,0 +1,93 @@
package pkg
import (
"reflect"
"testing"
)
func TestNewLocalBranch(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 := NewBranchStatus(repo, 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 TestClonedBranches(t *testing.T) {
origin := newTestRepo(t)
createFile(t, origin, "file")
stageFile(t, origin, "file")
createCommit(t, origin, "Initial commit")
createBranch(t, origin, "branch")
repo, err := CloneRepo(origin.Path(), newTempDir(t))
checkFatal(t, err)
createBranch(t, repo, "local")
checkoutBranch(t, repo, "branch")
createFile(t, repo, "anotherFile")
stageFile(t, repo, "anotherFile")
createCommit(t, repo, "Second commit")
branches, err := Branches(repo)
checkFatal(t, err)
var tests = []struct {
got BranchStatus
want BranchStatus
}{
{branches["master"], BranchStatus{
Name: "master",
IsRemote: false,
HasUpstream: true,
}},
{branches["origin/master"], BranchStatus{
Name: "origin/master",
IsRemote: true,
HasUpstream: false,
}},
{branches["branch"], BranchStatus{
Name: "branch",
IsRemote: false,
HasUpstream: true,
Ahead: 1,
NeedsPush: true,
}},
{branches["origin/branch"], BranchStatus{
Name: "origin/branch",
IsRemote: true,
HasUpstream: false,
}},
{branches["local"], BranchStatus{
Name: "local",
IsRemote: false,
HasUpstream: false,
}},
}
for _, test := range tests {
if !reflect.DeepEqual(test.got, test.want) {
t.Errorf("Wrong branch status, got %+v; want %+v", test.got, test.want)
}
}
}

140
pkg/helpers_test.go Normal file
View File

@@ -0,0 +1,140 @@
package pkg
import (
"io/ioutil"
"os"
"path"
"testing"
"time"
"github.com/pkg/errors"
git "github.com/libgit2/git2go/v30"
)
func checkFatal(t *testing.T, err error) {
if err != nil {
t.Fatalf("%+v", err)
}
}
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 newTestRepo(t *testing.T) *git.Repository {
dir := newTempDir(t)
repo, err := git.InitRepository(dir, false)
checkFatal(t, errors.Wrap(err, "Failed initializing a temp repo"))
return repo
}
func createFile(t *testing.T, repo *git.Repository, name string) {
err := ioutil.WriteFile(path.Join(repo.Workdir(), name), []byte("I'm a file"), 0644)
checkFatal(t, errors.Wrap(err, "Failed writing a file"))
}
func stageFile(t *testing.T, repo *git.Repository, name string) {
index, err := repo.Index()
checkFatal(t, errors.Wrap(err, "Failed getting repo index"))
err = index.AddByPath(name)
checkFatal(t, errors.Wrap(err, "Failed adding file to index"))
err = index.Write()
checkFatal(t, errors.Wrap(err, "Failed writing index"))
}
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()
checkFatal(t, errors.Wrap(err, "Failed checking if repo is empty"))
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 {
head, err := repo.Head()
checkFatal(t, errors.Wrap(err, "Failed getting repo head"))
commit, err := repo.LookupCommit(head.Target())
checkFatal(t, errors.Wrap(err, "Failed getting commit id from head"))
branch, err := repo.CreateBranch(name, commit, false)
checkFatal(t, errors.Wrap(err, "Failed creating branch"))
return branch
}
func checkoutBranch(t *testing.T, repo *git.Repository, name string) {
branch, err := repo.LookupBranch(name, git.BranchAll)
// If branch can't be found, let's check if it's a remote branch
if branch == nil {
branch, err = repo.LookupBranch("origin/"+name, git.BranchAll)
}
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"))
}

41
pkg/repo.go Normal file
View File

@@ -0,0 +1,41 @@
package pkg
import (
"github.com/pkg/errors"
git "github.com/libgit2/git2go/v30"
)
func CloneRepo(url string, path string) (*git.Repository, error) {
options := &git.CloneOptions{
CheckoutOpts: nil,
FetchOptions: nil,
Bare: false,
CheckoutBranch: "",
RemoteCreateCallback: nil,
}
repo, err := git.Clone(url, path, options)
return repo, errors.Wrap(err, "Failed cloning repo")
}
func Fetch(repo *git.Repository) error {
remotes, err := repo.Remotes.List()
if err != nil {
return errors.Wrap(err, "Failed listing remotes")
}
for _, r := range remotes {
remote, err := repo.Remotes.Lookup(r)
if err != nil {
return errors.Wrap(err, "Failed looking up remote")
}
err = remote.Fetch(nil, nil, "")
if err != nil {
return errors.Wrap(err, "Failed fetching remote")
}
}
return nil
}

42
pkg/repo_test.go Normal file
View File

@@ -0,0 +1,42 @@
package pkg
import "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
repo, err := CloneRepo(origin.Path(), newTempDir(t))
checkFatal(t, err)
// Check cloned status. It should not be behind origin
status, err := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
if status.BranchStatuses["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 = Fetch(repo)
status, err = NewRepoStatus(repo.Workdir())
checkFatal(t, err)
// Cloned master should now be 1 commit behind origin
if status.BranchStatuses["master"].Behind != 1 {
t.Errorf("Master should be 1 commit behind")
}
if status.BranchStatuses["master"].Ahead != 0 {
t.Errorf("Master should not be ahead")
}
}

72
pkg/status.go Normal file
View File

@@ -0,0 +1,72 @@
package pkg
import (
git "github.com/libgit2/git2go/v30"
"github.com/pkg/errors"
)
type RepoStatus struct {
HasUntrackedFiles bool
HasUncommittedChanges bool
BranchStatuses map[string]BranchStatus
}
func NewRepoStatus(path string) (RepoStatus, error) {
var status RepoStatus
repo, err := git.OpenRepository(path)
if err != nil {
return status, errors.Wrap(err, "Failed opening repository")
}
entries, err := statusEntries(repo)
if err != nil {
return status, errors.Wrap(err, "Failed getting repository status")
}
for _, entry := range entries {
switch entry.Status {
case git.StatusWtNew:
status.HasUntrackedFiles = true
case git.StatusIndexNew:
status.HasUncommittedChanges = true
}
}
branchStatuses, err := Branches(repo)
if err != nil {
return status, errors.Wrap(err, "Failed getting branches statuses")
}
status.BranchStatuses = branchStatuses
return status, nil
}
func statusEntries(repo *git.Repository) ([]git.StatusEntry, error) {
opts := &git.StatusOptions{
Show: git.StatusShowIndexAndWorkdir,
Flags: git.StatusOptIncludeUntracked,
}
status, err := repo.StatusList(opts)
if err != nil {
return nil, errors.Wrap(err, "Failed getting repository status")
}
entryCount, err := status.EntryCount()
if err != nil {
return nil, errors.Wrap(err, "Failed getting repository status count")
}
var entries []git.StatusEntry
for i := 0; i < entryCount; i++ {
entry, err := status.ByIndex(i)
if err != nil {
return nil, errors.Wrap(err, "Failed getting repository status entry")
}
entries = append(entries, entry)
}
return entries, nil
}

177
pkg/status_test.go Normal file
View File

@@ -0,0 +1,177 @@
package pkg
import (
"reflect"
"testing"
git "github.com/libgit2/git2go/v30"
)
func TestStatusWithEmptyRepo(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 := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
BranchStatuses: status.BranchStatuses,
}
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 := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: true,
HasUncommittedChanges: false,
BranchStatuses: status.BranchStatuses,
}
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 := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: true,
BranchStatuses: status.BranchStatuses,
}
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 := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
BranchStatuses: status.BranchStatuses,
}
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 := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
BranchStatuses: status.BranchStatuses,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}
func TestStatusCloned(t *testing.T) {
origin := newTestRepo(t)
dir := newTempDir(t)
repo, err := CloneRepo(origin.Path(), dir)
checkFatal(t, err)
status, err := NewRepoStatus(repo.Workdir())
checkFatal(t, err)
want := RepoStatus{
HasUntrackedFiles: false,
HasUncommittedChanges: false,
BranchStatuses: status.BranchStatuses,
}
if !reflect.DeepEqual(status, want) {
t.Errorf("Wrong repo status, got %+v; want %+v", status, want)
}
}