Home

ugit @22cdff623a8ec2342b9f90cc60f4d66f0e7ec712 - refs - log -
-
https://git.jolheiser.com/ugit.git
The code powering this h*ckin' site
ugit / internal / git / repo.go
- raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package git

import (
	"bytes"
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/object"
)

// Repo is a git repository
type Repo struct {
	path string
	Meta RepoMeta
}

// Name returns the human-friendly name, the dir name without the .git suffix
func (r Repo) Name() string {
	return strings.TrimSuffix(filepath.Base(r.path), ".git")
}

// NewRepo constructs a Repo given a dir and name
func NewRepo(dir, name string) (*Repo, error) {
	if !strings.HasSuffix(name, ".git") {
		name += ".git"
	}
	r := &Repo{
		path: filepath.Join(dir, name),
	}

	_, err := os.Stat(r.path)
	if err != nil {
		return nil, err
	}

	if err := ensureJSONFile(r.metaPath()); err != nil {
		return nil, err
	}
	fi, err := os.Open(r.metaPath())
	if err != nil {
		return nil, err
	}
	defer fi.Close()

	if err := json.NewDecoder(fi).Decode(&r.Meta); err != nil {
		return nil, err
	}

	return r, nil
}

// DefaultBranch returns the branch referenced by HEAD, setting it if needed
func (r Repo) DefaultBranch() (string, error) {
	repo, err := r.Git()
	if err != nil {
		return "", err
	}

	ref, err := repo.Head()
	if err != nil {
		if !errors.Is(err, plumbing.ErrReferenceNotFound) {
			return "", err
		}
		brs, err := repo.Branches()
		if err != nil {
			return "", err
		}
		defer brs.Close()
		fb, err := brs.Next()
		if err != nil {
			return "", err
		}
		// Rename the default branch to the first branch available
		ref = fb
		sym := plumbing.NewSymbolicReference(plumbing.HEAD, fb.Name())
		if err := repo.Storer.SetReference(sym); err != nil {
			return "", err
		}
	}

	return strings.TrimPrefix(ref.Name().String(), "refs/heads/"), nil
}

// Git allows access to the git repository
func (r Repo) Git() (*git.Repository, error) {
	return git.PlainOpen(r.path)
}

// Commit is a git commit
type Commit struct {
	SHA       string
	Message   string
	Signature string
	Author    string
	Email     string
	When      time.Time

	// Extra
	Stats CommitStats
	Patch string
	Files []CommitFile
}

// CommitStats is the stats of a commit
type CommitStats struct {
	Changed   int
	Additions int
	Deletions int
}

// CommitFile is a file contained in a commit
type CommitFile struct {
	From   CommitFileEntry
	To     CommitFileEntry
	Action string
	Patch  string
}

// CommitFileEntry is a from/to in a file commit
type CommitFileEntry struct {
	Path   string
	Commit string
}

// Short returns the first eight characters of the SHA
func (c Commit) Short() string {
	return c.SHA[:8]
}

// Summary returns the first line of the commit, suitable for a <summary>
func (c Commit) Summary() string {
	return strings.Split(c.Message, "\n")[0]
}

// Details returns all lines *after* the first, suitable for <details>
func (c Commit) Details() string {
	return strings.Join(strings.Split(c.Message, "\n")[1:], "\n")
}

// Commit gets a specific commit by SHA, including all commit information
func (r Repo) Commit(sha string) (Commit, error) {
	repo, err := r.Git()
	if err != nil {
		return Commit{}, err
	}

	return commit(repo, sha, true)
}

// LastCommit returns the last commit of the repo without any extra information
func (r Repo) LastCommit() (Commit, error) {
	repo, err := r.Git()
	if err != nil {
		return Commit{}, err
	}

	head, err := repo.Head()
	if err != nil {
		return Commit{}, err
	}

	return commit(repo, head.Hash().String(), false)
}

func commit(repo *git.Repository, sha string, extra bool) (Commit, error) {
	obj, err := repo.CommitObject(plumbing.NewHash(sha))
	if err != nil {
		return Commit{}, err
	}

	var c, a, d int
	var p string
	var f []CommitFile
	if extra {
		stats, err := obj.Stats()
		if err != nil {
			return Commit{}, err
		}

		c = len(stats)
		for _, stat := range stats {
			a += stat.Addition
			d += stat.Deletion
		}

		parent, err := obj.Parent(0)
		if err != nil {
			return Commit{}, err
		}

		patch, err := obj.Patch(parent)
		if err != nil {
			return Commit{}, err
		}

		var buf bytes.Buffer
		if err := patch.Encode(&buf); err != nil {
			return Commit{}, err
		}
		p = buf.String()

		objTree, err := obj.Tree()
		if err != nil {
			return Commit{}, err
		}
		parentTree, err := parent.Tree()
		if err != nil {
			return Commit{}, err
		}

		changes, err := parentTree.Diff(objTree)
		if err != nil {
			return Commit{}, err
		}

		for _, change := range changes {
			action, err := change.Action()
			if err != nil {
				return Commit{}, err
			}
			patch, err := change.Patch()
			if err != nil {
				return Commit{}, err
			}
			var buf bytes.Buffer
			if err := patch.Encode(&buf); err != nil {
				return Commit{}, err
			}
			f = append(f, CommitFile{
				From: CommitFileEntry{
					Path:   change.From.Name,
					Commit: parent.Hash.String(),
				},
				To: CommitFileEntry{
					Path:   change.To.Name,
					Commit: obj.Hash.String(),
				},
				Action: action.String(),
				Patch:  buf.String(),
			})
		}
	}

	return Commit{
		SHA:       obj.Hash.String(),
		Message:   obj.Message,
		Signature: obj.PGPSignature,
		Author:    obj.Author.Name,
		Email:     obj.Author.Email,
		When:      obj.Author.When,
		Stats: CommitStats{
			Changed:   c,
			Additions: a,
			Deletions: d,
		},
		Patch: p,
		Files: f,
	}, nil
}

// Branches is all repo branches, default first and sorted alphabetically after that
func (r Repo) Branches() ([]string, error) {
	repo, err := r.Git()
	if err != nil {
		return nil, err
	}

	def, err := r.DefaultBranch()
	if err != nil {
		return nil, err
	}

	brs, err := repo.Branches()
	if err != nil {
		return nil, err
	}

	var branches []string
	if err := brs.ForEach(func(branch *plumbing.Reference) error {
		branches = append(branches, branch.Name().Short())
		return nil
	}); err != nil {
		return nil, err
	}

	sort.Slice(branches, func(i, j int) bool {
		return branches[i] == def || branches[i] < branches[j]
	})

	return branches, nil
}

// Tag is a git tag, which may or may not have an annotation/signature
type Tag struct {
	Name       string
	Annotation string
	Signature  string
	When       time.Time
}

// Tags is all repo tags, sorted by time descending
func (r Repo) Tags() ([]Tag, error) {
	repo, err := r.Git()
	if err != nil {
		return nil, err
	}

	tgs, err := repo.Tags()
	if err != nil {
		return nil, err
	}

	var tags []Tag
	if err := tgs.ForEach(func(tag *plumbing.Reference) error {
		obj, err := repo.TagObject(tag.Hash())
		switch {
		case errors.Is(err, plumbing.ErrObjectNotFound):
			commit, err := repo.CommitObject(tag.Hash())
			if err != nil {
				return err
			}
			tags = append(tags, Tag{
				Name:       tag.Name().Short(),
				Annotation: commit.Message,
				Signature:  commit.PGPSignature,
				When:       commit.Author.When,
			})
		case err == nil:
			tags = append(tags, Tag{
				Name:       obj.Name,
				Annotation: obj.Message,
				Signature:  obj.PGPSignature,
				When:       obj.Tagger.When,
			})
		default:
			return err
		}
		return nil
	}); err != nil {
		return nil, err
	}

	sort.Slice(tags, func(i, j int) bool {
		return tags[i].When.After(tags[j].When)
	})

	return tags, nil
}

// Commits returns commits from a specific hash in descending order
func (r Repo) Commits(ref string) ([]Commit, error) {
	repo, err := r.Git()
	if err != nil {
		return nil, err
	}

	hash, err := repo.ResolveRevision(plumbing.Revision(ref))
	if err != nil {
		return nil, err
	}

	cmts, err := repo.Log(&git.LogOptions{
		From: *hash,
	})
	if err != nil {
		return nil, err
	}

	var commits []Commit
	if err := cmts.ForEach(func(commit *object.Commit) error {
		commits = append(commits, Commit{
			SHA:       commit.Hash.String(),
			Message:   commit.Message,
			Signature: commit.PGPSignature,
			Author:    commit.Author.Name,
			Email:     commit.Author.Email,
			When:      commit.Author.When,
		})
		return nil
	}); err != nil {
		return nil, err
	}

	return commits, nil
}