summaryrefslogtreecommitdiff
path: root/repo.go
blob: 8bb4a5dcc221e08d7bc5e3625b280d66afd77b9f (plain)
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
package syw

import (
	"context"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"tildegit.org/tjp/sliderule/logging"
)

// Repository represents a git repository.
type Repository string

// Open produces a git repository from a directory path.
//
// It will also try a few variations (dirpath.git, dirpath/.git) and use the first
// path found to be a git repository.
//
// It returns nil if neither dirpath nor any of its variations are a valid git
// repository.
func Open(dirpath string) *Repository {
	check := []string{dirpath}
	if !strings.HasSuffix(dirpath, ".git") {
		check = append(check, dirpath+".git")
	}
	check = append(check, filepath.Join(dirpath, ".git"))

	for _, p := range check {
		if st, err := os.Stat(filepath.Join(p, "objects")); err != nil || !st.IsDir() {
			continue
		}
		if st, err := os.Stat(filepath.Join(p, "refs")); err != nil || !st.IsDir() {
			continue
		}

		r := Repository(p)
		return &r
	}

	return nil
}

// Name is the repository name, defined by the directory path.
func (r *Repository) Name() string {
	name := filepath.Base(string(*r))
	if name == ".git" {
		name = filepath.Base(filepath.Dir(string(*r)))
	}
	return strings.TrimSuffix(name, ".git")
}

// NameBytes returns a byte slice of the repository name.
func (r *Repository) NameBytes() []byte {
	return []byte(r.Name())
}

func (r *Repository) cmd(ctx context.Context, cmdname string, args ...string) (*cmdResult, error) {
	args = append([]string{"--git-dir=" + string(*r), cmdname}, args...)
	start := time.Now()

	result, err := runCmd(ctx, args)

	log, ok := ctx.Value("debuglog").(logging.Logger)
	if ok {
		_ = log.Log("msg", "ran git command", "args", fmt.Sprintf("%+v", args), "dur", time.Since(start))
	}

	return result, err
}

// Type returns the result of "git cat-file -t <hash>".
func (r *Repository) Type(ctx context.Context, hash string) (string, error) {
	res, err := r.cmd(ctx, "cat-file", "-t", hash)
	if err != nil {
		return "", err
	}
	if res.status != 0 {
		return "", errors.New(res.err.String())
	}

	return strings.Trim(res.out.String(), "\n"), nil
}

// Refs returns a list of branch and tag references.
func (r *Repository) Refs(ctx context.Context) ([]Ref, error) {
	res, err := r.cmd(ctx, "show-ref", "--head", "--heads", "--tags")
	if err != nil {
		return nil, err
	}

	lines := strings.Split(res.out.String(), "\n")

	branches := make([]Ref, 0, len(lines))
	for _, line := range lines {
		hash, name, found := strings.Cut(line, " ")
		if !found {
			continue
		}
		branches = append(branches, Ref{
			Repo: r,
			Name: name,
			Hash: hash,
		})
	}
	return branches, nil
}

var badRevListOutput = errors.New("unexpected 'git rev-list' output")

// Commits lists commits backwards from a given head.
func (r *Repository) Commits(ctx context.Context, head string, count int) ([]Commit, error) {
	res, err := r.cmd(ctx, "rev-list",
		"--format=%an%n%ae%n%aI%n%cn%n%ce%n%cI%n%P%n%B$$END$$",
		"-n", strconv.Itoa(count),
		head,
	)
	if err != nil {
		return nil, err
	}

	commits := make([]Commit, 0, count)
	for _, revstr := range strings.Split(res.out.String(), "\n$$END$$\n") {
		if revstr == "" {
			continue
		}
		commits = append(commits, Commit{Repo: r})
		commit := &commits[len(commits)-1]

		commitHash, rest, found := strings.Cut(revstr, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.Hash = commitHash[7:]

		commit.AuthorName, rest, found = strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.AuthorEmail, rest, found = strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}

		adate, rest, found := strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.AuthorDate, err = time.Parse(time.RFC3339, adate)
		if err != nil {
			return nil, err
		}

		commit.CommitterName, rest, found = strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.CommitterEmail, rest, found = strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}

		cdate, rest, found := strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.CommitDate, err = time.Parse(time.RFC3339, cdate)
		if err != nil {
			return nil, err
		}

		parents, rest, found := strings.Cut(rest, "\n")
		if !found {
			return nil, badRevListOutput
		}
		commit.Parents = strings.Split(parents, " ")
		if len(commit.Parents) == 1 && commit.Parents[0] == "" {
			commit.Parents = nil
		}

		commit.Message = rest
	}

	return commits, nil
}

// Commit gathers a single commit by a reference string.
func (r *Repository) Commit(ctx context.Context, ref string) (*Commit, error) {
	commits, err := r.Commits(ctx, ref, 1)
	if err != nil {
		return nil, err
	}
	return &commits[0], nil
}

// Diffstat produces a diffstat of two trees by their references.
func (r *Repository) Diffstat(ctx context.Context, fromref, toref string) (string, error) {
	res, err := r.cmd(ctx, "diff-tree", "-r", "--stat", fromref, toref)
	if err != nil {
		return "", err
	}
	if res.status != 0 {
		return "", errors.New(res.err.String())
	}
	return res.out.String(), nil
}

// Diff produces a diff of two trees by their references.
func (r *Repository) Diff(ctx context.Context, fromref, toref string) (string, error) {
	res, err := r.cmd(ctx, "diff-tree", "-r", "-p", "-u", fromref, toref)
	if err != nil {
		return "", err
	}
	if res.status != 0 {
		return "", errors.New(res.err.String())
	}
	return res.out.String(), nil
}

// Readme represents a README file.
type Readme struct {
	Filename    string
	RawContents string
}

// GeminiEscapedContent produces the file contents with any ```-leading lines prefixed with a space.
func (r Readme) GeminiEscapedContents() string {
	body := r.RawContents
	if strings.HasPrefix(body, "```") {
		body = " " + body
	}
	return strings.ReplaceAll(body, "\n```", "\n ```")
}

// GopherEscapedContent produces the file formatted as gophermap with every line an info-message line.
func (r Readme) GopherEscapedContents(selector, host, port string) string {
	return gopherRawtext(selector, host, port, r.RawContents)
}

// Readme finds a README blob in the root path under a ref string.
func (r *Repository) Readme(ctx context.Context, ref string) (*Readme, error) {
	dir, err := r.Tree(ctx, ref, "")
	if err != nil {
		return nil, err
	}

	filename := ""
	for i := range dir {
		if dir[i].Type == "blob" && strings.HasPrefix(strings.ToLower(dir[i].Path), "readme") {
			filename = dir[i].Path
			break
		}
	}

	if filename != "" {
		body, err := r.Blob(ctx, ref, filename)
		if err != nil {
			return nil, err
		}

		return &Readme{
			Filename:    filename,
			RawContents: string(body),
		}, nil
	}

	return nil, nil
}

// Description reads the "description" file from in the git repository.
func (r *Repository) Description() string {
	f, err := os.Open(filepath.Join(string(*r), "description"))
	if err != nil {
		return ""
	}
	defer func() { _ = f.Close() }()

	b, err := io.ReadAll(f)
	if err != nil {
		return ""
	}

	return strings.TrimRight(string(b), "\n")
}

// Blob returns the contents of a blob at a given ref (commit) and path.
func (r *Repository) Blob(ctx context.Context, ref, path string) ([]byte, error) {
	res, err := r.cmd(ctx, "cat-file", "blob", ref+":"+path)
	switch {
	case res == nil:
		return nil, err
	case res.status == 0:
		return res.out.Bytes(), nil
	case res.status == 128:
		return nil, objectDoesNotExist
	default:
		return nil, errors.New(res.err.String())
	}
}

// ObjectDescription represents an object within a git tree (directory).
type ObjectDescription struct {
	Mode int
	Type string
	Hash string
	Size int
	Path string
}

// Tree lists the contents of a given directory (path) in a commit (ref).
func (r *Repository) Tree(ctx context.Context, ref, path string) ([]ObjectDescription, error) {
	pattern := ref
	if path != "" && path != "." {
		pattern += ":" + path
	}

	res, err := r.cmd(ctx, "ls-tree", "-l", pattern)
	if err != nil {
		return nil, err
	}

	out := []ObjectDescription{}
	for _, line := range strings.Split(res.out.String(), "\n") {
		if line == "" {
			continue
		}

		spl := dropEmpty(strings.Split(strings.ReplaceAll(line, "\t", " "), " "))

		mode, err := strconv.ParseInt(spl[0], 8, 64)
		if err != nil {
			return nil, err
		}

		var size int
		if spl[3] != "-" {
			size, err = strconv.Atoi(spl[3])
			if err != nil {
				return nil, err
			}
		}

		out = append(out, ObjectDescription{
			Mode: int(mode),
			Type: spl[1],
			Hash: spl[2],
			Size: size,
			Path: spl[4],
		})
	}
	return out, nil
}

func dropEmpty(sl []string) []string {
	n := 0
	for i := 0; i < len(sl); i += 1 {
		if sl[i] == "" {
			copy(sl[i:], sl[i+1:])
			i -= 1
			n += 1
		}
	}
	return sl[:len(sl)-n]
}

var objectDoesNotExist = errors.New("object does not exist")