Kiln » gitkiln Read More
Clone URL:  
Pushed to one repository · View In Graph Contained in master

we have namespaces; don't be stupidly redundant

Changeset 192fa27a9dbc

Parent b56064d5e3cc

by Profile picture of User 12Benjamin Pollack <benjamin@fogcreek.com>

Changes to 3 files · Browse files at 192fa27a9dbc Showing diff from parent b56064d5e3cc Diff from another changeset...

Change 1 of 5 Show Entire File kiln/​api.go Stacked
 
8
9
10
11
 
12
13
14
 
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
 
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
 
114
115
116
117
 
118
119
120
 
122
123
124
125
 
126
127
128
 
8
9
10
 
11
12
13
14
 
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
 
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
 
114
115
116
 
117
118
119
120
 
122
123
124
 
125
126
127
128
@@ -8,7 +8,7 @@
 )    // Represents the error JSON returned by Kiln API requests -type KilnError struct { +type ApiError struct {   // Guaranteed-unique code for Kiln errors   Code string `json:"codeError"`   // Human-readable description @@ -16,50 +16,50 @@
 }    // Represents the project JSON returned from the Kiln API -type KilnProject struct { +type Project struct {   Id int64 `json:"ixProject"`   Slug string `json:"sSlug"`   Name string `json:"sName"`   Description string `json:"sDescription"`   DefaultPermission string `json:"permissionDefault"` - RepoGroups []KilnRepoGroup + RepoGroups []RepoGroup  }   -type KilnRepoGroup struct { - Id int64 `json:"ixRepoGroup"` - ProjectId int64 `json:"ixProject"` - Slug string `json:"sSlug"` - Name string `json:"sName"` - Repos []KilnRepo `json:"repos"` +type RepoGroup struct { + Id int64 `json:"ixRepoGroup"` + ProjectId int64 `json:"ixProject"` + Slug string `json:"sSlug"` + Name string `json:"sName"` + Repos []Repo `json:"repos"`  }   -type KilnRepo struct { - Id int64 `json:"ixRepo"` - RepoGroupId int64 `json:"ixRepoGroup"` - ParentId int64 `json:"ixParent"` - IsCentral bool `json:"fCentral"` - Slug string `json:"sSlug"` - GroupSlug string `json:"sGroupSlug"` - ProjectSlug string `json:"sProjectSlug"` - GitUrl string `json:"sGitUrl"` - GitSshUrl string `json:"sGitSshUrl"` - Name string `json:"sName"` - Description string `json:"sDescription"` - Status string `json:"sStatus"` - Size int64 `json:"bytesSize"` - Vcs int `json:"vcs"` - Creator KilnPerson `json:"personCreator"` - DefaultPermission string `json:"permissionDefault"` - Branches []KilnRepo `json:"repoBranches"` +type Repo struct { + Id int64 `json:"ixRepo"` + RepoGroupId int64 `json:"ixRepoGroup"` + ParentId int64 `json:"ixParent"` + IsCentral bool `json:"fCentral"` + Slug string `json:"sSlug"` + GroupSlug string `json:"sGroupSlug"` + ProjectSlug string `json:"sProjectSlug"` + GitUrl string `json:"sGitUrl"` + GitSshUrl string `json:"sGitSshUrl"` + Name string `json:"sName"` + Description string `json:"sDescription"` + Status string `json:"sStatus"` + Size int64 `json:"bytesSize"` + Vcs int `json:"vcs"` + Creator Person `json:"personCreator"` + DefaultPermission string `json:"permissionDefault"` + Branches []Repo `json:"repoBranches"`  }   -type KilnPerson struct { +type Person struct {   Id int64 `json:"ixPerson"`   Name string `json:"sName"`   Email string `json:"sEmail"`  }   -func (k *KilnClient) CreateBranch(repoPath, branchName string) (newRepo *KilnRepo, err error) { +func (k *Client) CreateBranch(repoPath, branchName string) (newRepo *Repo, err error) {   r, err := k.RepoForPath(repoPath)   if err != nil {   return @@ -72,28 +72,28 @@
  }   var resp []byte   if resp, err = k.apiPost("Repo/Create", params); err == nil { - var errors map[string][]KilnError + var errors map[string][]ApiError   if err = json.Unmarshal(resp, &errors); err == nil {   if kilnErr, _ := errors["errors"]; len(kilnErr) > 0 {   err = fmt.Errorf("failed: %v\n", kilnErr[0].Description)   return   }   } - newRepo = new(KilnRepo) + newRepo = new(Repo)   err = json.Unmarshal(resp, newRepo)   return   }   return  }   -func (k *KilnClient) Projects() (projects []KilnProject, err error) { +func (k *Client) Projects() (projects []Project, err error) {   if resp, err := k.apiGet("Project", apiParams{}); err == nil {   err = json.Unmarshal(resp, &projects)   }   return  }   -func (k *KilnClient) RepoForPath(repoPath string) (*KilnRepo, error) { +func (k *Client) RepoForPath(repoPath string) (*Repo, error) {   parts := strings.Split(repoPath, "/")   if len(parts) != 3 {   return nil, fmt.Errorf("unknown repository target: %v", repoPath) @@ -114,7 +114,7 @@
  return nil, fmt.Errorf("repository not found")  }   -func (k *KilnClient) IdForRepo(repoPath string) (int64, error) { +func (k *Client) IdForRepo(repoPath string) (int64, error) {   repo, err := k.RepoForPath(repoPath)   if err != nil {   return -1, err @@ -122,7 +122,7 @@
  return repo.Id, nil  }   -func (k *KilnClient) RelatedRepos(repoPath string) (repos []KilnRepo, err error) { +func (k *Client) RelatedRepos(repoPath string) (repos []Repo, err error) {   repoId, err := k.IdForRepo(repoPath)   if err == nil {   resp, err := k.apiGet(fmt.Sprintf("Repo/%v/Related", repoId), apiParams{})
Change 1 of 16 Show Changes Only kiln/​kiln.go Stacked
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
239
240
 
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
 
 
293
294
295
296
297
298
299
300
301
302
303
 
304
305
306
307
308
309
310
311
312
313
314
315
316
317
 
318
319
320
321
322
323
324
325
326
327
 
328
329
330
 
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
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
239
 
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
 
 
291
292
293
294
295
296
297
298
299
300
301
302
 
303
304
305
306
307
308
309
310
311
312
313
314
315
316
 
317
318
319
320
321
322
323
324
325
326
 
327
328
329
 
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
 package kiln    import (   "bufio"   "bytes"   "encoding/json"   "fmt"   "io"   "io/ioutil"   "net/http"   "net/url"   "os"   "os/exec"   "os/user"   "path/filepath"   "runtime"   "strings"  )    // Holds the bare minimum amount of information required to talk to a Kiln instance -type KilnClient struct { - credentials *kilnCredential +type Client struct { + credentials *credential  }    // Stores kiln credentials in the Kiln configuration file -type kilnCredential struct { +type credential struct {   // Base URL of Kiln instance   KilnUrl string `json:"kilnUrl"`   // User for whom this token applies   User string `json:"user"`   // Kiln API token   Token string `json:"token"`  }    type apiParams map[string]string   -type KilnCredentials map[string]map[string]string - -func NewKilnClient(kilnUrl *url.URL) *KilnClient { +type Credentials map[string]map[string]string + +func NewClient(kilnUrl *url.URL) *Client {   user := ""   if kilnUrl.User != nil {   user = kilnUrl.User.Username()   } - return &KilnClient{&kilnCredential{KilnUrl: kilnUrl.String(), User: user}} -} - -func (k *KilnClient) LoadCredentials() bool { + return &Client{&credential{KilnUrl: kilnUrl.String(), User: user}} +} + +func (k *Client) LoadCredentials() bool {   if creds, err := loadCredentials(); err == nil {   if token, ok := creds[k.credentials.User][k.credentials.KilnUrl]; ok {   k.credentials.Token = token   return true   }   }   return false  }   -func (k *KilnClient) StoreCredentials() (err error) { +func (k *Client) StoreCredentials() (err error) {   creds, _ := loadCredentials()   if _, ok := creds[k.credentials.User]; !ok {   creds[k.credentials.User] = make(map[string]string)   }   creds[k.credentials.User][k.credentials.KilnUrl] = k.credentials.Token   err = creds.storeCredentials()   return  }   -func (k *KilnClient) DeleteCredentials() (err error) { +func (k *Client) DeleteCredentials() (err error) {   creds, err := loadCredentials()   if err != nil {   return   }   if user, ok := creds[k.credentials.User]; ok {   delete(user, k.credentials.KilnUrl)   }   err = creds.storeCredentials()   return  }    // Logs a user into Kiln, returning true and storing their token in the -// KilnClient if successful, and returning an error otherwise -func (k *KilnClient) Logon() error { +// Client if successful, and returning an error otherwise +func (k *Client) Logon() error {   login, password := requestUserCredentials()   resp, err := k.apiGet("Auth/Login", apiParams{"sUser": login, "sPassword": password})   if err != nil {   return fmt.Errorf("unable to contact Kiln: %v\n", err)   } - var errors map[string][]KilnError + var errors map[string][]ApiError   if err = json.Unmarshal(resp, &errors); err == nil {   if err, _ := errors["errors"]; len(err) > 0 {   return fmt.Errorf("failed: %v\n", err[0].Description)   }   }   if err = json.Unmarshal(resp, &k.credentials.Token); err != nil {   return fmt.Errorf("failed to parse token: %v", err)   }   return nil  }    // Makes sure the client has credentials, taking them through the logon  // sequence if not -func (k *KilnClient) EnsureCredentials() error { +func (k *Client) EnsureCredentials() error {   if k.credentials.Token == "" && !k.LoadCredentials() {   if err := k.Logon(); err != nil {   return err   }   k.StoreCredentials()   }   return nil  }    // Resolve a Git SHA -func (k *KilnClient) ResolveSHA(commit string) (string, error) { +func (k *Client) ResolveSHA(commit string) (string, error) {   if out, err := exec.Command("git", "rev-parse", commit).CombinedOutput(); err == nil {   commit := strings.TrimSpace(string(out))   if strings.HasPrefix(commit, "fatal:") {   return "", fmt.Errorf("commit couldn't be resolved (try \"git fetch\" first)")   } else {   return commit, nil   }   }   return "", fmt.Errorf("commit couldn't be resolved (try \"git fetch\" first)")  }    // Browses the history tab of the repository -func (k *KilnClient) BrowseHistory(repo string) error { +func (k *Client) BrowseHistory(repo string) error {   return browse(k.repoRoute(repo, ""))  }    // Browse the settings tab for the repository -func (k *KilnClient) BrowseSettings(repo string) error { +func (k *Client) BrowseSettings(repo string) error {   return browse(k.repoRoute(repo, "Settings"))  }    // Browse the related tab for repository -func (k *KilnClient) BrowseRelated(repo string) error { +func (k *Client) BrowseRelated(repo string) error {   return browse(k.repoRoute(repo, "Related"))  }    // Browse a commit, expanding out to the full SHA beforehand -func (k *KilnClient) BrowseCommit(repo string, commit string) (err error) { +func (k *Client) BrowseCommit(repo string, commit string) (err error) {   if commit, err = k.ResolveSHA(commit); err == nil {   err = browse(k.repoRoute(repo, "History/"+commit))   }   return  }    // Browse a file in Kiln -func (k *KilnClient) BrowseFile(repo string, file string) error { +func (k *Client) BrowseFile(repo string, file string) error {   path, err := repoRelativePath(file)   if err != nil {   return err   }   return browse(k.repoRoute(repo, fmt.Sprintf("Files%v", path)))  }    // Browse an annotated file in Kiln -func (k *KilnClient) BrowseAnnotatedFile(repo string, file string) error { +func (k *Client) BrowseAnnotatedFile(repo string, file string) error {   path, err := repoRelativePath(file)   if err != nil {   return err   }   return browse(k.repoRoute(repo, fmt.Sprintf("Files%v?view=annotate", path)))  }    // Browse a file in Kiln -func (k *KilnClient) BrowseFileHistory(repo string, file string) error { +func (k *Client) BrowseFileHistory(repo string, file string) error {   path, err := repoRelativePath(file)   if err != nil {   return err   }   return browse(k.repoRoute(repo, fmt.Sprintf("FileHistory%v", path)))  }    // Find the root of the Git repo  func GitRoot() (path string, err error) {   out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()   if err != nil {   return   }   path = strings.TrimSpace(string(out))   if strings.HasPrefix(path, "fatal:") {   err = fmt.Errorf("unable to find root: %v", path)   }   return  }    // Opens a web browser in a cross-platform way  func browse(location string) error {   switch runtime.GOOS {   case "linux":   return exec.Command("xdg-open", location).Start()   case "windows":   return exec.Command("cmd", "/c", "start", location).Start()   case "darwin":   return exec.Command("open", location).Start()   default:   return fmt.Errorf("%v is an unsupported platform", runtime.GOOS)   }  }    // Change a relative or absolute path into a path relative to the repository root  func repoRelativePath(path string) (string, error) {   root, err := GitRoot()   if err != nil {   return "", err   }   absPath, err := filepath.Abs(path)   if err != nil {   return "", err   }   absPath = filepath.ToSlash(absPath)   return strings.TrimPrefix(absPath, root), nil  }    // Returns the full URL for relative Kiln URL -func (k *KilnClient) kilnRoute(route string) string { +func (k *Client) kilnRoute(route string) string {   return strings.TrimRight(k.credentials.KilnUrl, "/") + "/" + strings.TrimLeft(route, "/")  }    // Returns the full URL for an API call in Kiln -func (k *KilnClient) apiRoute(route string) string { +func (k *Client) apiRoute(route string) string {   return k.kilnRoute("Api/1.0/" + strings.TrimLeft(route, "/"))  }    // Returns the full URL for a given API call or Kiln route -func (k *KilnClient) repoRoute(repo string, action string) string { +func (k *Client) repoRoute(repo string, action string) string {   return k.kilnRoute(fmt.Sprintf("Code/%v/%v", repo, action))  }    // Returns the body from an API call via HTTP GET -func (k *KilnClient) apiGet(route string, params apiParams) ([]byte, error) { +func (k *Client) apiGet(route string, params apiParams) ([]byte, error) {   return k.apiRequest(route, params, "GET")  }    // Returns the body from an API call via HTTP POST -func (k *KilnClient) apiPost(route string, params apiParams) ([]byte, error) { +func (k *Client) apiPost(route string, params apiParams) ([]byte, error) {   return k.apiRequest(route, params, "POST")  }   -func (k *KilnClient) apiRequest(route string, params apiParams, method string) ([]byte, error) { +func (k *Client) apiRequest(route string, params apiParams, method string) ([]byte, error) {   v := url.Values{}   for key, value := range params {   v.Set(key, value)   }   if k.credentials.Token != "" {   v.Set("token", k.credentials.Token)   }     var resp *http.Response   var err error   if method == "GET" {   resp, err = http.Get(k.apiRoute(route) + "?" + v.Encode())   } else if method == "POST" {   resp, err = http.PostForm(k.apiRoute(route), v)   }     if err != nil {   return nil, err   }   defer resp.Body.Close()   return ioutil.ReadAll(resp.Body)  }    // Encode a path by Kiln's hex encoding  func hexEncoded(path string) string {   utf8 := []byte(path)   hexBytes := make([]string, len(utf8))   for idx, b := range utf8 {   hexBytes[idx] = fmt.Sprintf("%x", b)   }   return strings.Join(hexBytes, "")  }    // Request new credentials from the user, securely  func requestUserCredentials() (login, password string) {   scanner := bufio.NewScanner(os.Stdin)   for {   fmt.Print("Login: ")   scanner.Scan()   login = scanner.Text()   if strings.Trim(login, "\t ") == "" {   fmt.Println("Please enter your Kiln name or email address")   continue   }   password, _ = getPass("Password: ")   return   }  }    // Load any existing credentials from the user's credential store -func loadCredentials() (credentials KilnCredentials, err error) { - credentials = make(KilnCredentials) +func loadCredentials() (credentials Credentials, err error) { + credentials = make(Credentials)   path := filepath.Join(configDirectory(), "kiln_client.json")   fd, err := os.Open(path)   if err != nil {   return   }   defer fd.Close()   data, err := ioutil.ReadAll(fd)   if err != nil {   return   } - var creds []kilnCredential + var creds []credential   if err = json.Unmarshal(data, &creds); err != nil {   return   }   for _, cred := range creds {   if _, ok := credentials[cred.User]; !ok {   credentials[cred.User] = make(map[string]string)   }   credentials[cred.User][cred.KilnUrl] = cred.Token   }   return  }    // Store all credentials in the credential store, overwriting any already present -func (credentials KilnCredentials) storeCredentials() (err error) { +func (credentials Credentials) storeCredentials() (err error) {   if err = os.MkdirAll(configDirectory(), 0700); err != nil {   return   }   path := filepath.Join(configDirectory(), "kiln_client.json")   fd, err := os.Create(path)   if err != nil {   return   }   defer fd.Close() - creds := make([]*kilnCredential, 0, 10) + creds := make([]*credential, 0, 10)   for user, urls := range credentials {   for url, token := range urls { - creds = append(creds, &kilnCredential{KilnUrl: url, User: user, Token: token}) + creds = append(creds, &credential{KilnUrl: url, User: user, Token: token})   }   }   data, _ := json.Marshal(creds)   _, err = io.Copy(fd, bytes.NewReader(data))   return  }    // Finds the directory in which to store Kiln files. Platform-dependent.  func configDirectory() string {   switch runtime.GOOS {   case "windows":   return filepath.Join(os.Getenv("APPDATA"), "Kiln")   default:   usr, err := user.Current()   if err != nil {   panic("unable to determine current user")   }   return filepath.Join(usr.HomeDir, ".config", "kiln")   }  }
Change 1 of 4 Show Entire File main.go Stacked
 
112
113
114
115
 
116
117
118
 
131
132
133
134
135
 
 
136
137
138
 
143
144
145
146
 
147
148
149
 
286
287
288
289
 
290
291
 
112
113
114
 
115
116
117
118
 
131
132
133
 
 
134
135
136
137
138
 
143
144
145
 
146
147
148
149
 
286
287
288
 
289
290
291
@@ -112,7 +112,7 @@
  }  }   -func requireAuth(k *kiln.KilnClient) { +func requireAuth(k *kiln.Client) {   if err := k.EnsureCredentials(); err != nil {   fmt.Fprintf(os.Stderr, "unable to logon: %v\n", err)   os.Exit(1) @@ -131,8 +131,8 @@
  return  }   -func findTargets(related []kiln.KilnRepo, project, group, repo string) []kiln.KilnRepo { - targets := make([]kiln.KilnRepo, 0) +func findTargets(related []kiln.Repo, project, group, repo string) []kiln.Repo { + targets := make([]kiln.Repo, 0)   for _, r := range related {   if r.Slug == repo &&   (len(group) == 0 || r.GroupSlug == group) && @@ -143,7 +143,7 @@
  return targets  }   -func dispatch(k *kiln.KilnClient, repoPath string) { +func dispatch(k *kiln.Client, repoPath string) {   var command string   if len(os.Args) == 1 {   command = "history" @@ -286,6 +286,6 @@
  fmt.Fprintf(os.Stderr, "%v\n", err)   os.Exit(1)   } - k := kiln.NewKilnClient(kilnUrl) + k := kiln.NewClient(kilnUrl)   dispatch(k, repoPath)  }