github.com/nfisher/gitit@v0.0.7-0.20240131193748-bc8dd26542cc/assert/git.go (about)

     1  package assert
     2  
     3  import (
     4  	"github.com/go-git/go-git/v5"
     5  	"github.com/go-git/go-git/v5/config"
     6  	"github.com/go-git/go-git/v5/storage/memory"
     7  	"github.com/google/go-cmp/cmp"
     8  	"github.com/google/go-cmp/cmp/cmpopts"
     9  	"sort"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  type gitremote struct {
    15  	t *testing.T
    16  	s string
    17  }
    18  
    19  func Remote(t *testing.T, s string) *gitremote {
    20  	return &gitremote{t, s}
    21  }
    22  
    23  func (rem *gitremote) IncludesBranches(branches ...string) {
    24  	rem.t.Helper()
    25  	remoteBranches := rem.remoteBranches()
    26  
    27  	sort.Strings(remoteBranches)
    28  	remoteList := strings.Join(remoteBranches, "\n")
    29  
    30  	sort.Strings(branches)
    31  	branchList := strings.Join(branches, "\n")
    32  
    33  	if !strings.Contains(remoteList, branchList) {
    34  		diff := cmp.Diff(branchList, remoteList, cmpopts.AcyclicTransformer("multiline", func(s string) []string {
    35  			return strings.Split(s, "\n")
    36  		}))
    37  		rem.t.Errorf("remote-ls (-want +got):%s\n", diff)
    38  	}
    39  }
    40  
    41  func (rem *gitremote) ExcludesBranches(branches ...string) {
    42  	rem.t.Helper()
    43  	remoteList := rem.remoteBranches()
    44  
    45  	var m = map[string]bool{}
    46  	for _, r := range remoteList {
    47  		m[r] = true
    48  	}
    49  
    50  	for _, b := range branches {
    51  		if m[b] {
    52  			rem.t.Errorf("remote-ls should not contain: %v\n", b)
    53  		}
    54  	}
    55  }
    56  
    57  func (rem *gitremote) remoteBranches() []string {
    58  	remote := git.NewRemote(memory.NewStorage(), &config.RemoteConfig{
    59  		Name: "origin",
    60  		URLs: []string{rem.s},
    61  	})
    62  
    63  	refs, err := remote.List(&git.ListOptions{})
    64  	if err != nil {
    65  		rem.t.Fatalf("call=List err=`%v`\n", err)
    66  	}
    67  	var prefix = "refs/heads/"
    68  	var a []string
    69  	for _, r := range refs {
    70  		s := r.Name().String()
    71  		if strings.HasPrefix(s, prefix) {
    72  			a = append(a, s[len(prefix):])
    73  		}
    74  	}
    75  
    76  	return a
    77  }
    78  
    79  type gitrepo struct {
    80  	t *testing.T
    81  	g *git.Repository
    82  }
    83  
    84  func Repo(t *testing.T, g *git.Repository) *gitrepo {
    85  	return &gitrepo{t, g}
    86  }
    87  
    88  func (gr *gitrepo) Branch(b string) {
    89  	gr.t.Helper()
    90  	head, err := gr.g.Head()
    91  	if err != nil {
    92  		gr.t.Fatalf("call=Head err=`%v`\n", err)
    93  	}
    94  
    95  	a := strings.Replace(head.Name().String(), "refs/heads/", "", 1)
    96  	if a != b {
    97  		gr.t.Fatalf("want %v, got %v\n", b, a)
    98  	}
    99  }