forked from TheThingsNetwork/lorawan-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
238 lines (212 loc) · 5.44 KB
/
git.go
File metadata and controls
238 lines (212 loc) · 5.44 KB
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
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ttnmage
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/TheThingsIndustries/magepkg/git"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"golang.org/x/xerrors"
)
// Git namespace.
type Git mg.Namespace
func (Git) installHook(name string) (err error) {
if mg.Verbose() {
fmt.Printf("Installing %s hook\n", name)
}
f, err := os.OpenFile(filepath.Join(".git", "hooks", name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return err
}
defer func() {
if closeErr := f.Close(); err == nil && closeErr != nil {
err = closeErr
}
}()
if _, err = fmt.Fprintf(f, "ARGS=\"$@\" make git.%s\n", name); err != nil {
return err
}
return nil
}
var gitHooks = []string{"pre-commit", "commit-msg", "pre-push"}
// InstallHooks installs git hooks that help developers follow our best practices.
func (g Git) InstallHooks() error {
for _, hook := range gitHooks {
if err := g.installHook(hook); err != nil {
return err
}
}
return nil
}
func init() {
initDeps = append(initDeps, Git.InstallHooks)
}
// UninstallHooks uninstalls git hooks.
func (g Git) UninstallHooks() error {
for _, hook := range gitHooks {
if mg.Verbose() {
fmt.Printf("Uninstalling %s hook\n", hook)
}
if err := os.Remove(filepath.Join(".git", "hooks", hook)); err != nil && !os.IsNotExist(err) {
return err
}
}
return nil
}
func (Git) selectStaged() error {
staged, err := git.StagedFiles()
if err != nil {
return err
}
selectedFiles, selectedDirs = make(map[string]bool), make(map[string]bool)
for _, file := range staged {
selectedFiles[file] = true
selectedDirs[filepath.Dir(file)] = true
}
return nil
}
var preCommitChecks []interface{}
func (g Git) preCommit() error {
if mg.Verbose() {
fmt.Println("Running pre-commit hook")
}
mg.Deps(g.selectStaged)
mg.Deps(preCommitChecks...)
return nil
}
var gitCommitPrefixes = []string{
"all",
"api",
"as",
"ci",
"cli",
"console",
"dev",
"doc",
"dtc",
"gcs",
"gs",
"is",
"js",
"ns",
"oauth",
"pba",
"qrg",
"util",
}
func (Git) commitMsg(messageFile string) error {
if mg.Verbose() {
fmt.Println("Running commit-msg hook")
}
if messageFile == "" {
messageFile = ".git/COMMIT_EDITMSG"
}
f, err := os.Open(messageFile)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
s.Scan()
commitMsg := s.Text()
if commitMsg == "" {
return xerrors.New("commit message must not be empty")
}
if strings.HasPrefix(commitMsg, "fixup! ") || strings.HasPrefix(commitMsg, "Merge ") {
return nil
}
// Check length:
switch {
case len(commitMsg) > 72:
return xerrors.New("commit message must be shorter than 72 characters")
case len(commitMsg) > 50:
// TODO: Warn.
}
// Check topics: Message structure:
split := strings.SplitN(commitMsg, ": ", 2)
if len(split) != 2 {
return fmt.Errorf("commit message must contain topics from %s",
strings.Join(gitCommitPrefixes, ","))
}
// Check topics:
topics := strings.Split(split[0], ",")
var unknownTopics []string
nextTopic:
for _, topic := range topics {
for _, allowed := range gitCommitPrefixes {
if strings.TrimSpace(topic) == allowed {
continue nextTopic
}
}
unknownTopics = append(unknownTopics, topic)
}
if len(unknownTopics) > 0 {
return fmt.Errorf("commit messages must only topics from %s (and not %s)",
strings.Join(gitCommitPrefixes, ","),
strings.Join(unknownTopics, ","))
}
words := strings.Fields(split[1])
// Casing:
if words[0][0] < 'A' || words[0][0] > 'Z' {
return fmt.Errorf("commit messages must start with a capital letter (and %s doesn't)", words[0])
}
// Punctuation:
if strings.HasSuffix(commitMsg, ".") {
return fmt.Errorf("commit messages must not end with punctuation")
}
// Imperative
if strings.HasSuffix(words[0], "ed") || strings.HasSuffix(words[0], "ing") {
// TODO: Warn that Commit messages should use imperative mood
}
return nil
}
// RunHook runs the Git hook for $HOOK, arguments are taken from $ARGS.
func (g Git) RunHook() error {
hook, args := os.Getenv("HOOK"), strings.Fields(os.Getenv("ARGS"))
switch hook {
case "pre-commit":
return g.preCommit()
case "commit-msg":
var messageFile string
if len(args) > 0 {
messageFile = args[0]
}
return g.commitMsg(messageFile)
case "pre-push":
if mg.Verbose() {
fmt.Println("Running pre-push hook with", args)
}
return nil
default:
return fmt.Errorf("Unknown hook %s", hook)
}
}
// Diff returns error if `git diff` is not empty
func (Git) Diff() error {
if mg.Verbose() {
fmt.Println("Checking git diff")
}
output, err := sh.Output("git", "diff")
if err != nil {
return err
}
if output != "" {
return fmt.Errorf("Previous operations have created changes that were not recorded in the repository. Please make those changes on your local machine before pushing them to the repository:\n%s", output)
}
return nil
}