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

go fmt

Changeset 89082c218620

Parent 90d073f7b05d

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

Changes to 2 files · Browse files at 89082c218620 Showing diff from parent 90d073f7b05d Diff from another changeset...

Change 1 of 1 Show Entire File kiln/​api.go Stacked
 
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
 
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
@@ -10,41 +10,41 @@
   // Represents the project JSON returned from the Kiln API  type KilnProject struct { - Id int64 `json:"ixProject"` - Slug string `json:"sSlug"` - Name string `json:"sName"` - Description string `json:"sDescription"` + Id int64 `json:"ixProject"` + Slug string `json:"sSlug"` + Name string `json:"sName"` + Description string `json:"sDescription"`   DefaultPermission string `json:"permissionDefault"` - RepoGroups []KilnRepoGroup + RepoGroups []KilnRepoGroup  }    type KilnRepoGroup struct { - Id int64 `json:"ixRepoGroup"` - ProjectId int64 `json:"ixProject"` - Slug string `json:"sSlug"` - Name string `json:"sName"` - Repos []KilnRepo + Id int64 `json:"ixRepoGroup"` + ProjectId int64 `json:"ixProject"` + Slug string `json:"sSlug"` + Name string `json:"sName"` + Repos []KilnRepo  }    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"` - Name string `json:"sName"` - Description string `json:"sDescription"` - Status string `json:"sStatus"` - Size int64 `json:"bytesSize"` - Creator KilnPerson `json:"personCreator"` - DefaultPermission string `json:"permissionDefault"` - Branches []KilnRepo `json:"repoBranches"` + 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"` + Name string `json:"sName"` + Description string `json:"sDescription"` + Status string `json:"sStatus"` + Size int64 `json:"bytesSize"` + Creator KilnPerson `json:"personCreator"` + DefaultPermission string `json:"permissionDefault"` + Branches []KilnRepo `json:"repoBranches"`  }    type KilnPerson struct { - Id int64 `json:"ixPerson"` - Name string `json:"sName"` + Id int64 `json:"ixPerson"` + Name string `json:"sName"`   Email string `json:"sEmail"`  }
Change 1 of 1 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
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
 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  }    // Stores kiln credentials in the Kiln configuration file  type kilnCredential 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 {   user := ""   if kilnUrl.User != nil {   user = kilnUrl.User.Username()   }   return &KilnClient{&kilnCredential{KilnUrl: kilnUrl.String(), User: user}}  }    func (k *KilnClient) 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) {   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) {   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 {   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   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 {   if k.credentials.Token == "" && !k.LoadCredentials() {   if err := k.Logon(); err != nil {   return err   }   k.StoreCredentials()   }   return nil  }    // Browses the history tab of the repository  func (k *KilnClient) BrowseHistory(repo string) error {   return browse(k.repoRoute(repo, ""))  }    // Browse the settings tab for the repository  func (k *KilnClient) BrowseSettings(repo string) error {   return browse(k.repoRoute(repo, "Settings"))  }    // Browse the related tab for repository  func (k *KilnClient) 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) {   if out, err := exec.Command("git", "rev-parse", commit).Output(); err == nil {   commit = strings.TrimSpace(string(out))   if strings.HasPrefix(commit, "fatal:") {   err = fmt.Errorf("commit couldn't be resolved (try \"git fetch\")\n")   } else {   browse(k.repoRoute(repo, "History/"+commit))   }   }   return  }    // Browse a file in Kiln  func (k *KilnClient) 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 {   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 {   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 {   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 { - return k.kilnRoute("Api/1.0/"+strings.TrimLeft(route, "/")) + 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 {   return k.kilnRoute(fmt.Sprintf("Code/%v/%v", repo, action))  }    // Returns the body from a Get API call  func (k *KilnClient) apiGet(route string, params apiParams) ([]byte, error) {   v := url.Values{}   for key, value := range params {   v.Set(key, value)   }   if k.credentials.Token != "" {   v.Set("token", k.credentials.Token)   }   resp, err := http.Get(k.apiRoute(route) + "?" + v.Encode())   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)   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   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) {   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)   for user, urls := range credentials {   for url, token := range urls {   creds = append(creds, &kilnCredential{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")   }  }