-
Notifications
You must be signed in to change notification settings - Fork 6
/
git.go
102 lines (83 loc) · 2.2 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
// Copyright 2017 Mathew Robinson <chasinglogic@gmail.com>. All rights reserved.
// Use of this source code is governed by the GPLv3 license that can be found in
// the LICENSE file.
package git
import (
"fmt"
"os"
"os/exec"
)
func getUserMsg() string {
return os.Getenv("DFM_GIT_COMMIT_MSG")
}
// Sync will add and commit all files in the repo then push.
func Sync(workingDir string) error {
dirty, err := isDirty(workingDir)
if err != nil {
return err
}
if dirty {
err := RunGitCMD(workingDir, "add", "--all")
if err != nil {
return err
}
msg := "Files managed by DFM! https://github.com/chasinglogic/dfm"
if userMsg := os.Getenv("DFM_GIT_COMMIT_MSG"); userMsg != "" {
msg = userMsg
}
if userMsg := getUserMsg(); userMsg != "" {
msg = userMsg
}
err = RunGitCMD(workingDir, "commit", "-m", msg)
if err != nil {
return err
}
}
err = Pull(workingDir)
if err != nil {
return err
}
if dirty {
return RunGitCMD(workingDir, "push", "origin", "master")
}
return nil
}
// Pull runs git pull --rebase origin master in the given workingDir
func Pull(workingDir string) error {
err := RunGitCMD(workingDir, "pull", "--rebase", "origin", "master")
if err != nil {
return err
}
return nil
}
// Init will run git init in the directory
func Init(workingDir string) error {
return RunGitCMD(workingDir, "init")
}
func isDirty(workingDir string) (bool, error) {
command := exec.Command("git", "status", "--porcelain")
command.Dir = workingDir
out, err := command.Output()
if err != nil {
fmt.Println("ERROR Running Git Command: git status --porcelain", string(out))
}
return string(out) != "", err
}
// Branch will return the git branch of the repo at dir
func Branch(dir string) (string, error) {
command := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
command.Dir = dir
out, err := command.Output()
return string(out), err
}
// RunGitCMD runs git with the given args in workingDir
func RunGitCMD(workingDir string, args ...string) error {
command := exec.Command("git", args...)
command.Dir = workingDir
out, err := command.CombinedOutput()
fmt.Println(string(out))
if err != nil {
fmt.Println("ERROR Running Git Command:", "git", args)
}
return err
}