forked from lithammer/go-wiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
133 lines (105 loc) · 2.38 KB
/
git.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
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
type Commit struct {
Author string
Date time.Time
File string
Hash string
Subject string
}
func (c Commit) Diff() ([]byte, error) {
return Diff(c.File, c.Hash)
}
func (c Commit) FileNoExt() string {
return strings.TrimSuffix(c.File, filepath.Ext(c.File))
}
func (c Commit) HumanDate() string {
return c.Date.Format("2006-01-02 15:04")
}
func Diff(file, hash string) ([]byte, error) {
var out bytes.Buffer
git := exec.Command("git", "-C", options.Dir, "show", "--oneline", "--no-color", hash, file)
// Prune diff stats from output with tail
tail := exec.Command("tail", "-n", "+8")
var err error
tail.Stdin, err = git.StdoutPipe()
if err != nil {
log.Println("ERROR", err)
}
tail.Stdout = &out
err = tail.Start()
if err != nil {
log.Println("ERROR", err)
}
err = git.Run()
if err != nil {
log.Println("ERROR", err)
}
err = tail.Wait()
if err != nil {
log.Println("ERROR", err)
}
return out.Bytes(), err
}
func Commits(filename string, n int) ([]Commit, error) {
var commits []Commit
// abbreviated commit hash|author name|author date, UNIX timestamp|subject
logFormat := "--pretty=%h|%an|%at|%s"
cmd := exec.Command("git", "-C", options.Dir, "log", "-n", strconv.Itoa(n), logFormat, filename)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println("ERROR", err)
return commits, err
}
defer stdout.Close()
err = cmd.Start()
if err != nil {
log.Println("ERROR", err)
return commits, err
}
out := bufio.NewScanner(stdout)
for out.Scan() {
fields := strings.Split(out.Text(), "|")
commit := Commit{
Author: fields[1],
File: filename,
Hash: fields[0],
Subject: fields[3],
}
unix, err := strconv.ParseInt(fields[2], 10, 64)
if err != nil {
log.Println("ERROR", err)
}
commit.Date = time.Unix(unix, 0)
commits = append(commits, commit)
}
return commits, nil
}
// Check if a path contains a Git repository
func IsGitRepository(path string) bool {
var out bytes.Buffer
cmd := exec.Command("git", "-C", options.Dir, "rev-parse", "--is-inside-work-tree")
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Println("ERROR", err)
return false
}
var val bool
_, err = fmt.Sscanf(out.String(), "%t", &val)
if err != nil {
log.Println("ERROR", err)
return false
}
return val
}