11package main
22
33import (
4+ "encoding/json"
5+ "errors"
46 "flag"
57 "fmt"
8+ "io/ioutil"
69 "log"
10+ "net/http"
711 "os"
812 "os/exec"
913 "path/filepath"
@@ -17,14 +21,43 @@ const (
1721 rejected = 1
1822)
1923
20- var (
21- target = flag .String ("p" , "" , "(optional) path to repository" )
22- )
24+ // Repository defines the github repo where the source code is located
25+ const Repository = "ONSdigital/git-diff-check"
26+
27+ var target = flag .String ("p" , "" , "(optional) path to repository" )
28+ var showVersion bool
29+ var showHelp bool
30+
31+ func init () {
32+ flag .BoolVar (& showVersion , "version" , false , "show current version" )
33+ flag .BoolVar (& showHelp , "help" , false , "show usage" )
34+ }
35+
36+ // Version is injected at build time
37+ var Version string
2338
2439func main () {
2540
2641 flag .Parse ()
2742
43+ if showHelp {
44+ flag .PrintDefaults ()
45+ os .Exit (0 )
46+ }
47+
48+ if showVersion {
49+ if len (Version ) == 0 {
50+ fmt .Println (errors .New ("No version set in binary! You may have a broken release" ))
51+ os .Exit (1 )
52+ }
53+ fmt .Println (Version )
54+ os .Exit (0 )
55+ }
56+
57+ // Attempt to check for a new version and inform the user if this is so.
58+ // If we can't connect or get the version for some reason then this is non-fatal
59+ versionCheck ()
60+
2861 if * target == "" {
2962 * target = "."
3063 }
@@ -86,3 +119,45 @@ func main() {
86119 fmt .Println ("If you're VERY SURE these files are ok, rerun commit with --no-verify" )
87120 os .Exit (rejected )
88121}
122+
123+ // VersionResponse is the response from the github verson call
124+ type VersionResponse struct {
125+ TagName string `json:"tag_name"`
126+ }
127+
128+ func versionCheck () bool {
129+
130+ // TODO
131+ // Set default client timeouts etc
132+
133+ resp , err := http .Get ("https://api.github.com/repos/" + Repository + "/releases/latest" )
134+ if err != nil {
135+ fmt .Println (errors .New ("Failed to check for new versions" + err .Error ()))
136+ return false
137+ }
138+
139+ body , err := ioutil .ReadAll (resp .Body )
140+ if err != nil {
141+ fmt .Println (errors .New ("Failed to read response from version check" + err .Error ()))
142+ return false
143+ }
144+
145+ var v VersionResponse
146+ err = json .Unmarshal (body , & v )
147+ if err != nil {
148+ fmt .Println (errors .New ("Failed to read response from version check" + err .Error ()))
149+ return false
150+ }
151+
152+ if len (v .TagName ) == 0 {
153+ fmt .Println (errors .New ("Failed to parse version from github response" ))
154+ return false
155+ }
156+
157+ if v .TagName != Version {
158+ fmt .Printf ("\n ** Precommit: New version %s available (installed %s) **\n \n " , v .TagName , Version )
159+ return true
160+ }
161+
162+ return false
163+ }
0 commit comments