-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
commands.go
568 lines (457 loc) · 12.3 KB
/
commands.go
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package git
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
"github.com/thomiceli/opengist/internal/config"
)
var (
ReposDirectory = "repos"
)
const truncateLimit = 2 << 18
type RevisionNotFoundError struct{}
func (m *RevisionNotFoundError) Error() string {
return "revision not found"
}
func RepositoryPath(user string, gist string) string {
return filepath.Join(config.GetHomeDir(), ReposDirectory, strings.ToLower(user), gist)
}
func RepositoryUrl(ctx echo.Context, user string, gist string) string {
httpProtocol := "http"
if ctx.Request().TLS != nil || ctx.Request().Header.Get("X-Forwarded-Proto") == "https" {
httpProtocol = "https"
}
var baseHttpUrl string
// if a custom external url is set, use it
if config.C.ExternalUrl != "" {
baseHttpUrl = config.C.ExternalUrl
} else {
baseHttpUrl = httpProtocol + ":https://" + ctx.Request().Host
}
return fmt.Sprintf("%s/%s/%s", baseHttpUrl, user, gist)
}
func TmpRepositoryPath(gistId string) string {
dirname := TmpRepositoriesPath()
return filepath.Join(dirname, gistId)
}
func TmpRepositoriesPath() string {
return filepath.Join(config.GetHomeDir(), "tmp", "repos")
}
func InitRepository(user string, gist string) error {
repositoryPath := RepositoryPath(user, gist)
var args []string
args = append(args, "init")
if config.C.GitDefaultBranch != "" {
args = append(args, "--initial-branch", config.C.GitDefaultBranch)
}
args = append(args, "--bare", repositoryPath)
cmd := exec.Command("git", args...)
if err := cmd.Run(); err != nil {
return err
}
return CreateDotGitFiles(user, gist)
}
func CountCommits(user string, gist string) (string, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command(
"git",
"rev-list",
"--all",
"--count",
)
cmd.Dir = repositoryPath
stdout, err := cmd.Output()
return strings.TrimSuffix(string(stdout), "\n"), err
}
func GetFilesOfRepository(user string, gist string, revision string) ([]string, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command(
"git",
"ls-tree",
"--name-only",
"--",
revision,
)
cmd.Dir = repositoryPath
stdout, err := cmd.Output()
if err != nil {
return nil, err
}
slice := strings.Split(string(stdout), "\n")
return slice[:len(slice)-1], nil
}
type catFileBatch struct {
Name, Hash, Content string
Size uint64
Truncated bool
}
func CatFileBatch(user string, gist string, revision string, truncate bool) ([]*catFileBatch, error) {
repositoryPath := RepositoryPath(user, gist)
lsTreeCmd := exec.Command("git", "ls-tree", "-l", revision)
lsTreeCmd.Dir = repositoryPath
lsTreeOutput, err := lsTreeCmd.Output()
if err != nil {
return nil, err
}
fileMap := make([]*catFileBatch, 0)
lines := strings.Split(string(lsTreeOutput), "\n")
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) < 4 {
continue // Skip lines that don't have enough fields
}
hash := fields[2]
size, err := strconv.ParseUint(fields[3], 10, 64)
if err != nil {
continue // Skip lines with invalid size field
}
name := strings.Join(fields[4:], " ") // File name may contain spaces
fileMap = append(fileMap, &catFileBatch{
Hash: hash,
Size: size,
Name: name,
})
}
catFileCmd := exec.Command("git", "cat-file", "--batch")
catFileCmd.Dir = repositoryPath
stdin, err := catFileCmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := catFileCmd.StdoutPipe()
if err != nil {
return nil, err
}
if err = catFileCmd.Start(); err != nil {
return nil, err
}
reader := bufio.NewReader(stdout)
for _, file := range fileMap {
_, err = stdin.Write([]byte(file.Hash + "\n"))
if err != nil {
return nil, err
}
header, err := reader.ReadString('\n')
if err != nil {
return nil, err
}
parts := strings.Fields(header)
if len(parts) > 3 {
continue // Not a valid header, skip this entry
}
size, err := strconv.ParseUint(parts[2], 10, 64)
if err != nil {
return nil, err
}
sizeToRead := size
if truncate && sizeToRead > truncateLimit {
sizeToRead = truncateLimit
}
// Read exactly size bytes from header, or the max allowed if truncated
content := make([]byte, sizeToRead)
if _, err = io.ReadFull(reader, content); err != nil {
return nil, err
}
file.Content = string(content)
if truncate && size > truncateLimit {
// skip other bytes if truncated
if _, err = reader.Discard(int(size - truncateLimit)); err != nil {
return nil, err
}
file.Truncated = true
}
// Read the blank line following the content
if _, err := reader.ReadByte(); err != nil {
return nil, err
}
}
if err = stdin.Close(); err != nil {
return nil, err
}
if err = catFileCmd.Wait(); err != nil {
return nil, err
}
return fileMap, nil
}
func GetFileContent(user string, gist string, revision string, filename string, truncate bool) (string, bool, error) {
repositoryPath := RepositoryPath(user, gist)
var maxBytes int64 = -1
if truncate {
maxBytes = truncateLimit
}
// Set up a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
cmd := exec.CommandContext(
ctx,
"git",
"--no-pager",
"show",
revision+":"+filename,
)
cmd.Dir = repositoryPath
output, err := cmd.Output()
if err != nil {
return "", false, err
}
content, truncated, err := truncateCommandOutput(bytes.NewReader(output), maxBytes)
if err != nil {
return "", false, err
}
return content, truncated, nil
}
func GetFileSize(user string, gist string, revision string, filename string) (uint64, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command(
"git",
"cat-file",
"-s",
revision+":"+filename,
)
cmd.Dir = repositoryPath
stdout, err := cmd.Output()
if err != nil {
return 0, err
}
return strconv.ParseUint(strings.TrimSuffix(string(stdout), "\n"), 10, 64)
}
func GetLog(user string, gist string, skip int) ([]*Commit, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command(
"git",
"--no-pager",
"log",
"-n",
"11",
"--no-color",
"-p",
"--skip",
strconv.Itoa(skip),
"--format=format:c %H%na %aN%nm %ae%nt %at",
"--shortstat",
"HEAD",
)
cmd.Dir = repositoryPath
stdout, _ := cmd.StdoutPipe()
err := cmd.Start()
if err != nil {
return nil, err
}
defer func(cmd *exec.Cmd) {
waitErr := cmd.Wait()
if waitErr != nil {
err = waitErr
}
}(cmd)
return parseLog(stdout, truncateLimit), err
}
func CloneTmp(user string, gist string, gistTmpId string, email string, remove bool) error {
repositoryPath := RepositoryPath(user, gist)
tmpPath := TmpRepositoriesPath()
tmpRepositoryPath := path.Join(tmpPath, gistTmpId)
err := os.RemoveAll(tmpRepositoryPath)
if err != nil {
return err
}
cmd := exec.Command("git", "clone", repositoryPath, gistTmpId)
cmd.Dir = tmpPath
if err = cmd.Run(); err != nil {
return err
}
// remove every file (keep the .git directory)
// useful when user wants to edit multiple files from an existing gist
if remove {
if err = removeFilesExceptGit(tmpRepositoryPath); err != nil {
return err
}
}
cmd = exec.Command("git", "config", "--local", "user.name", user)
cmd.Dir = tmpRepositoryPath
if err = cmd.Run(); err != nil {
return err
}
cmd = exec.Command("git", "config", "--local", "user.email", email)
cmd.Dir = tmpRepositoryPath
return cmd.Run()
}
func ForkClone(userSrc string, gistSrc string, userDst string, gistDst string) error {
repositoryPathSrc := RepositoryPath(userSrc, gistSrc)
repositoryPathDst := RepositoryPath(userDst, gistDst)
cmd := exec.Command("git", "clone", "--bare", repositoryPathSrc, repositoryPathDst)
if err := cmd.Run(); err != nil {
return err
}
return CreateDotGitFiles(userDst, gistDst)
}
func SetFileContent(gistTmpId string, filename string, content string) error {
repositoryPath := TmpRepositoryPath(gistTmpId)
return os.WriteFile(filepath.Join(repositoryPath, filename), []byte(content), 0644)
}
func AddAll(gistTmpId string) error {
tmpPath := TmpRepositoryPath(gistTmpId)
// in case of a change where only a file name has its case changed
cmd := exec.Command("git", "rm", "-r", "--cached", "--ignore-unmatch", ".")
cmd.Dir = tmpPath
err := cmd.Run()
if err != nil {
return err
}
cmd = exec.Command("git", "add", "-A")
cmd.Dir = tmpPath
return cmd.Run()
}
func CommitRepository(gistTmpId string, authorName string, authorEmail string) error {
cmd := exec.Command("git",
"commit",
"--allow-empty",
"-m",
"Opengist commit",
"--author",
fmt.Sprintf("%s <%s>", authorName, authorEmail),
)
tmpPath := TmpRepositoryPath(gistTmpId)
cmd.Dir = tmpPath
return cmd.Run()
}
func Push(gistTmpId string) error {
tmpRepositoryPath := TmpRepositoryPath(gistTmpId)
cmd := exec.Command(
"git",
"push",
)
cmd.Dir = tmpRepositoryPath
err := cmd.Run()
if err != nil {
return err
}
return os.RemoveAll(tmpRepositoryPath)
}
func DeleteRepository(user string, gist string) error {
return os.RemoveAll(RepositoryPath(user, gist))
}
func UpdateServerInfo(user string, gist string) error {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command("git", "update-server-info")
cmd.Dir = repositoryPath
return cmd.Run()
}
func RPC(user string, gist string, service string) ([]byte, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command("git", service, "--stateless-rpc", "--advertise-refs", ".")
cmd.Dir = repositoryPath
stdout, err := cmd.Output()
return stdout, err
}
func GcRepos() error {
subdirs, err := os.ReadDir(filepath.Join(config.GetHomeDir(), ReposDirectory))
if err != nil {
return err
}
for _, subdir := range subdirs {
if !subdir.IsDir() {
continue
}
subRoot := filepath.Join(config.GetHomeDir(), ReposDirectory, subdir.Name())
gitRepos, err := os.ReadDir(subRoot)
if err != nil {
log.Warn().Err(err).Msg("Cannot read directory")
continue
}
for _, repo := range gitRepos {
if !repo.IsDir() {
continue
}
repoPath := filepath.Join(subRoot, repo.Name())
log.Info().Msg("Running git gc for repository " + repoPath)
cmd := exec.Command("git", "gc")
cmd.Dir = repoPath
err = cmd.Run()
if err != nil {
log.Warn().Err(err).Msg("Cannot run git gc for repository " + repoPath)
continue
}
}
}
return err
}
func HasNoCommits(user string, gist string) (bool, error) {
repositoryPath := RepositoryPath(user, gist)
cmd := exec.Command("git", "rev-parse", "--all")
cmd.Dir = repositoryPath
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return false, err
}
if out.String() == "" {
return true, nil // No commits exist
}
return false, nil // Commits exist
}
func GetGitVersion() (string, error) {
cmd := exec.Command("git", "--version")
stdout, err := cmd.Output()
if err != nil {
return "", err
}
versionFields := strings.Fields(string(stdout))
if len(versionFields) < 3 {
return string(stdout), nil
}
return versionFields[2], nil
}
func CreateDotGitFiles(user string, gist string) error {
repositoryPath := RepositoryPath(user, gist)
f1, err := os.OpenFile(filepath.Join(repositoryPath, "git-daemon-export-ok"), os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer f1.Close()
if os.Getenv("OPENGIST_SKIP_GIT_HOOKS") != "1" {
for _, hook := range []string{"pre-receive", "post-receive"} {
if err = createDotGitHookFile(repositoryPath, hook, fmt.Sprintf(hookTemplate, hook)); err != nil {
return err
}
}
}
return nil
}
func createDotGitHookFile(repositoryPath string, hook string, content string) error {
preReceiveDst, err := os.OpenFile(filepath.Join(repositoryPath, "hooks", hook), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0744)
if err != nil {
return err
}
if _, err = preReceiveDst.WriteString(content); err != nil {
return err
}
defer preReceiveDst.Close()
return nil
}
func removeFilesExceptGit(dir string) error {
return filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() && filepath.Base(path) == ".git" {
return filepath.SkipDir
}
if !d.IsDir() {
return os.Remove(path)
}
return nil
})
}
const hookTemplate = `#!/bin/sh
"$OG_OPENGIST_HOME_INTERNAL/symlinks/opengist" --config=$OG_OPENGIST_HOME_INTERNAL/symlinks/config.yml hook %s
`