all repos

mugit @ ad82a5b45b1dd9fb368d3fb07ef803df002a2681

🐮 git server that your cow will love

mugit/internal/git/repo.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
git: get last commit from git cli, improves performance..., 2 months ago
1
package git
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"path/filepath"
8
	"strings"
9
	"time"
10
11
	"github.com/go-git/go-git/v5"
12
	"github.com/go-git/go-git/v5/plumbing"
13
	"github.com/go-git/go-git/v5/plumbing/object"
14
	"github.com/go-git/go-git/v5/plumbing/storer"
15
	"github.com/go-git/go-git/v5/plumbing/transport"
16
	"github.com/go-git/go-git/v5/plumbing/transport/http"
17
)
18
19
// Thanks https://git.icyphox.sh/legit/blob/master/git/git.go
20
21
var (
22
	ErrEmptyRepo    = errors.New("repository has no commits")
23
	ErrFileNotFound = errors.New("file not found")
24
	ErrPrivate      = errors.New("repository is private")
25
)
26
27
type Repo struct {
28
	path string
29
	r    *git.Repository
30
	h    plumbing.Hash
31
}
32
33
// Open opens a git repository at path. If ref is empty, HEAD is used.
34
func Open(path, ref string) (*Repo, error) {
35
	var err error
36
	g := Repo{}
37
	g.path = path
38
	g.r, err = git.PlainOpen(path)
39
	if err != nil {
40
		return nil, fmt.Errorf("opening %s: %w", path, err)
41
	}
42
43
	if ref == "" {
44
		head, err := g.r.Head()
45
		if err != nil {
46
			if errors.Is(err, plumbing.ErrReferenceNotFound) {
47
				return &g, nil
48
			}
49
			return nil, fmt.Errorf("getting head of %s: %w", path, err)
50
		}
51
		g.h = head.Hash()
52
	} else {
53
		hash, err := g.r.ResolveRevision(plumbing.Revision(ref))
54
		if err != nil {
55
			return nil, fmt.Errorf("resolving rev %s for %s: %w", ref, path, err)
56
		}
57
		g.h = *hash
58
	}
59
	return &g, nil
60
}
61
62
// OpenPublic opens a repository, returns [ErrPrivate] if it's private.
63
func OpenPublic(path, ref string) (*Repo, error) {
64
	r, err := Open(path, ref)
65
	if err != nil {
66
		return nil, err
67
	}
68
69
	isPrivate, err := r.IsPrivate()
70
	if err != nil {
71
		return nil, err
72
	}
73
74
	if isPrivate {
75
		return nil, ErrPrivate
76
	}
77
78
	return r, nil
79
}
80
81
func (g *Repo) IsEmpty() bool {
82
	return g.h == plumbing.ZeroHash
83
}
84
85
// Init initializes a bare repo in path.
86
func Init(path string) error {
87
	if _, err := git.PlainInit(path, true); err != nil {
88
		return fmt.Errorf("failed to initialize repo: %w", err)
89
	}
90
	return nil
91
}
92
93
func (g *Repo) Name() string {
94
	name := filepath.Base(g.path)
95
	return strings.TrimSuffix(name, ".git")
96
}
97
98
func (g *Repo) Checkout(ref string) error {
99
	head := plumbing.NewSymbolicReference(plumbing.HEAD,
100
		plumbing.NewBranchReferenceName(ref))
101
	return g.r.Storer.SetReference(head)
102
}
103
104
type Commit struct {
105
	Message        string
106
	AuthorEmail    string
107
	AuthorName     string
108
	CommitterName  string
109
	CommitterEmail string
110
	Committed      time.Time
111
	ChangeID       string
112
	Hash           string
113
	HashShort      string
114
}
115
116
func newShortHash(h plumbing.Hash) string { return h.String()[:7] }
117
func newCommit(c *object.Commit) *Commit {
118
	var changeID string
119
	for _, header := range c.ExtraHeaders {
120
		if header.Key == "change-id" {
121
			changeID = header.Value
122
			break
123
		}
124
	}
125
126
	return &Commit{
127
		Message:        c.Message,
128
		AuthorEmail:    c.Author.Email,
129
		AuthorName:     c.Author.Name,
130
		CommitterName:  c.Committer.Name,
131
		CommitterEmail: c.Committer.Email,
132
		Committed:      c.Committer.When,
133
		ChangeID:       changeID,
134
		Hash:           c.Hash.String(),
135
		HashShort:      newShortHash(c.Hash),
136
	}
137
}
138
139
const CommitsPage = 150
140
141
// Commits returns [CommitsPage] commits after the given commit hash cursor.
142
// If after is empty, starts from HEAD.
143
func (g *Repo) Commits(after string) ([]*Commit, error) {
144
	if g.IsEmpty() {
145
		return []*Commit{}, nil
146
	}
147
148
	from := g.h
149
	if after != "" {
150
		hash, err := g.r.ResolveRevision(plumbing.Revision(after))
151
		if err != nil {
152
			return nil, fmt.Errorf("invalid cursor: %w", err)
153
		}
154
		from = *hash
155
	}
156
157
	ci, err := g.r.Log(&git.LogOptions{
158
		From:  from,
159
		Order: git.LogOrderCommitterTime,
160
	})
161
	if err != nil {
162
		return nil, fmt.Errorf("commits from ref: %w", err)
163
	}
164
165
	// since after commit was shown on prev page, skip it
166
	if after != "" {
167
		ci.Next()
168
	}
169
170
	commits := make([]*Commit, 0, CommitsPage)
171
	ci.ForEach(func(c *object.Commit) error {
172
		if len(commits) == CommitsPage {
173
			return storer.ErrStop
174
		}
175
		commits = append(commits, newCommit(c))
176
		return nil
177
	})
178
179
	return commits, nil
180
}
181
182
func (g *Repo) LastCommit() (*Commit, error) {
183
	if g.IsEmpty() {
184
		return &Commit{}, nil
185
	}
186
187
	c, err := g.r.CommitObject(g.h)
188
	if err != nil {
189
		return nil, fmt.Errorf("last commit: %w", err)
190
	}
191
192
	return newCommit(c), nil
193
}
194
195
type Branch struct {
196
	Name       string
197
	LastUpdate time.Time
198
}
199
200
func (g *Repo) Branches() ([]*Branch, error) {
201
	bi, err := g.r.Branches()
202
	if err != nil {
203
		return nil, fmt.Errorf("branch: %w", err)
204
	}
205
206
	var branches []*Branch
207
	err = bi.ForEach(func(r *plumbing.Reference) error {
208
		cmt, cerr := g.r.CommitObject(r.Hash())
209
		if cerr != nil {
210
			return cerr
211
		}
212
213
		branches = append(branches, &Branch{
214
			Name:       r.Name().Short(),
215
			LastUpdate: cmt.Committer.When,
216
		})
217
		return nil
218
	})
219
	return branches, err
220
}
221
222
func (g *Repo) IsGoMod() bool {
223
	_, err := g.FileContent("go.mod")
224
	return err == nil
225
}
226
227
func (g *Repo) FindMasterBranch(masters []string) (string, error) {
228
	if g.IsEmpty() {
229
		return "", ErrEmptyRepo
230
	}
231
232
	for _, b := range masters {
233
		if _, err := g.r.ResolveRevision(plumbing.Revision(b)); err == nil {
234
			return b, nil
235
		}
236
	}
237
	return "", fmt.Errorf("unable to find master branch")
238
}
239
240
func (g *Repo) Fetch(ctx context.Context) error {
241
	return g.fetch(ctx, nil)
242
}
243
244
func (g *Repo) FetchFromGithubWithToken(ctx context.Context, token string) error {
245
	return g.fetch(ctx, &http.BasicAuth{
246
		Username: "x-access-token", // this can be anything but empty
247
		Password: token,
248
	})
249
}
250
251
func (g *Repo) fetch(ctx context.Context, auth transport.AuthMethod) error {
252
	rmt, err := g.r.Remote(originRemote)
253
	if err != nil {
254
		return fmt.Errorf("failed to get remote: %w", err)
255
	}
256
257
	if err = rmt.FetchContext(ctx, &git.FetchOptions{
258
		Auth:  auth,
259
		Tags:  git.AllTags,
260
		Prune: true,
261
		Force: true,
262
	}); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
263
		return fmt.Errorf("failed to fetch: %w", err)
264
	}
265
266
	// for some reason fetch doesn't change head for empty repos
267
	if !g.IsEmpty() {
268
		return nil
269
	}
270
271
	refs, err := rmt.List(&git.ListOptions{Auth: auth})
272
	if err != nil {
273
		return fmt.Errorf("failed to list references: %w", err)
274
	}
275
276
	for _, ref := range refs {
277
		if ref.Name() == plumbing.HEAD {
278
			if err := g.r.Storer.SetReference(
279
				plumbing.NewSymbolicReference(plumbing.HEAD, ref.Target()),
280
			); err != nil {
281
				return fmt.Errorf("failed to set HEAD: %w", err)
282
			}
283
			break
284
		}
285
	}
286
287
	return nil
288
}