all repos

mugit @ cc59ce4becd876f686c626f299c8969541c1d90f

🐮 git server that your cow will love

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

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