-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.go
99 lines (88 loc) · 1.91 KB
/
init.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
package initializer
import (
"bufio"
"fmt"
"jiko21/gomi/git"
"os"
"os/exec"
"github.com/AlecAivazis/survey/v2"
)
type Initializer struct {
branches []string
}
var POST_MERGE_SHELL = `#! /bin/bash
gomi
`
var execCommand = exec.Command
func New() (Initializer, error) {
branches, err := git.GetBranch()
if err != nil {
return Initializer{}, err
}
initializer := Initializer{branches}
return initializer, nil
}
func (i *Initializer) Exec() error {
if isGomiignoreExists() {
shouldOverwrite := false
prompt := &survey.Confirm{
Message: "`.gomiignore` file already exists. Do you overwrite it?",
}
survey.AskOne(prompt, &shouldOverwrite)
if !shouldOverwrite {
return nil
}
}
selectedBranches := []string{}
prompt := &survey.MultiSelect{
Message: "Chose branches to ignore:",
Options: i.branches,
}
survey.AskOne(prompt, &selectedBranches)
shouldAutoMerge := false
autoMergePrompt := &survey.Confirm{
Message: "Do you want to run `gomi` automatically after merging a branch?",
}
survey.AskOne(autoMergePrompt, &shouldAutoMerge)
if shouldAutoMerge {
err := writeAfterMergeHook()
if err != nil {
return err
}
}
return writeGomiignoreFile(selectedBranches)
}
func writeGomiignoreFile(branches []string) error {
f, err := os.Create(".gomiignore")
if err != nil {
return err
}
defer f.Close()
w := bufio.NewWriter(f)
headText := "# generated by `gomi init`"
fmt.Fprintln(w, headText)
for _, branch := range branches {
fmt.Fprintln(w, branch)
}
return w.Flush()
}
func writeAfterMergeHook() error {
f, err := os.Create(".git/hooks/post-merge")
if err != nil {
return err
}
defer f.Close()
_, err = f.Write([]byte(POST_MERGE_SHELL))
if err != nil {
return err
}
_, err = execCommand("chmod", "a+x", ".git/hooks/post-merge").Output()
if err != nil {
return err
}
return nil
}
func isGomiignoreExists() bool {
_, err := os.Stat(".gomiignore")
return err == nil
}