-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcreate.go
224 lines (195 loc) · 5.13 KB
/
create.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
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
package shortener
import (
"context"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/google/go-github/github"
"github.com/kashav/go-url-shortener/template"
)
// Creator implements Runner for the create operation.
type Creator struct {
URL string
Name string
CNAME string
Private bool
Repo string
Subdir bool
Verbose bool
}
var files = map[string]map[string]interface{}{
"index.html": {"incl": true, "tmpl": template.Index},
"CNAME": {"incl": false, "tmpl": template.CNAME},
"README.md": {"incl": true, "tmpl": template.README},
}
func (c *Creator) run(ctx context.Context, client *github.Client) error {
if c.Name == "" {
c.Name = randomString(4)
}
dir, err := ioutil.TempDir("", fmt.Sprintf("%s-", packageName))
if err != nil {
return err
}
defer os.RemoveAll(dir)
var createFunc = c.createRepo
if c.Subdir {
createFunc = c.createSubdir
}
ent, err := createFunc(ctx, client, dir)
if err != nil {
return err
}
if ent == nil {
return errors.New("failed to create entry")
}
state.Log.Entries = append(state.Log.Entries, *ent)
if err := saveLog(); err != nil {
return err
}
fmt.Printf("Created new entry: %s -> %s.\n", ent.Name, ent.RedirectURL)
return nil
}
func (c *Creator) createSubdir(ctx context.Context, client *github.Client, dir string) (*entry, error) {
if c.Repo == "" {
return nil, errors.New("expected repo with --subdir flag (use --repo)")
}
split := strings.Split(c.Repo, "/")
owner, repoName := split[0], split[1]
repo, _, err := client.Repositories.Get(ctx, owner, repoName)
if err != nil {
return nil, err
}
if repo == nil {
return nil, fmt.Errorf("repository %s doesn't exist", c.Repo)
}
if err := c.runGitCmds([]string{"clone", repo.GetCloneURL(), dir}); err != nil {
return nil, err
}
subdir := filepath.Clean(fmt.Sprintf("%s/%s", dir, c.Name))
if err := os.MkdirAll(subdir, os.ModePerm); err != nil {
return nil, err
}
if err := c.createFiles(subdir); err != nil {
return nil, err
}
cmds := [][]string{
{"-C", dir, "add", "."},
{"-C", dir, "commit", "-m", fmt.Sprintf("%s: new entry", packageName), "-m", fmt.Sprintf("%s -> %s", c.Name, c.URL)},
{"-C", dir, "push"},
}
if err := c.runGitCmds(cmds...); err != nil {
return nil, err
}
return &entry{
Name: fmt.Sprintf("%s/%s", repo.GetFullName(), c.Name),
Owner: repo.Owner.GetLogin(),
Repo: repo.GetName(),
RepoURL: repo.GetHTMLURL(),
RedirectURL: c.URL,
IsSubdir: true,
IsPrivate: c.Private,
}, nil
}
func (c *Creator) createRepo(ctx context.Context, client *github.Client, dir string) (*entry, error) {
if c.CNAME != "" {
files["CNAME"]["incl"] = true
}
repo, _, err := client.Repositories.Create(ctx, "", &github.Repository{
AutoInit: github.Bool(true),
MasterBranch: github.String("refs/heads/gh-pages"),
Name: github.String(c.Name),
Private: github.Bool(c.Private),
})
if err != nil {
return nil, err
}
if err := c.createFiles(dir); err != nil {
return nil, err
}
cmds := [][]string{
{"-C", dir, "init"},
{"-C", dir, "add", "."},
{"-C", dir, "commit", "-m", "Initial commit"},
{"-C", dir, "branch", "-m", "gh-pages"},
{"-C", dir, "remote", "add", "origin", repo.GetCloneURL()},
{"-C", dir, "push", "-u", "origin", "gh-pages"},
}
if err := c.runGitCmds(cmds...); err != nil {
return nil, err
}
// Use the API to delete the master branch, `git push origin --delete`
// doesn't work for some reason :(.
if _, err = client.Git.DeleteRef(
ctx,
repo.Owner.GetLogin(),
repo.GetName(),
"refs/heads/master",
); err != nil {
return nil, err
}
return &entry{
Name: repo.GetFullName(),
Owner: repo.Owner.GetLogin(),
Repo: repo.GetName(),
RepoURL: repo.GetHTMLURL(),
RedirectURL: c.URL,
IsSubdir: false,
IsPrivate: c.Private,
}, nil
}
// createFiles creates all necessary files. These will always include an
// index.html, and a README.md. A CNAME file is created iff the --cname flag
// is provided.
func (c *Creator) createFiles(dir string) error {
for file, opts := range files {
if !opts["incl"].(bool) {
continue
}
fi, err := os.Create(filepath.Clean(fmt.Sprintf("%s/%s", dir, file)))
if err != nil {
return err
}
tmpl := opts["tmpl"].(func(string, string, string) string)(
c.URL,
c.Name,
c.CNAME,
)
if _, err = fi.Write([]byte(tmpl)); err != nil {
return err
}
}
return nil
}
// runGitCmds executes a series of git commands on the host machine
// to add, commit, and push the associated files to the gh-pages branch.
func (c *Creator) runGitCmds(cmds ...[]string) error {
for _, cmd := range cmds {
gitCmd := exec.Command("git", cmd...)
if c.Verbose {
gitCmd.Stdout = os.Stdout
gitCmd.Stderr = os.Stderr
}
if err := gitCmd.Run(); err != nil {
return err
}
}
return nil
}
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// randomString returns a random hash of n characters.
func randomString(n int) string {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
for i := range b {
b[i] = chars[rand.Intn(len(chars))]
}
return string(b)
}