-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommit.go
314 lines (283 loc) · 8.36 KB
/
commit.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/charmbracelet/log"
"github.com/clerk/clerk-sdk-go/v2"
"github.com/clerk/clerk-sdk-go/v2/user"
"github.com/go-chi/chi/v5"
"github.com/joshtenorio/glassypdm-server/internal/dal"
"github.com/joshtenorio/glassypdm-server/internal/sqlcgen"
)
/*
*
body:
- projectid, teamid
- CreateCommit msg
- files: [
{
filepath
hash
changetype
}
]
*/
func CreateCommit(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
claims, ok := clerk.SessionClaimsFromContext(r.Context())
if !ok {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"access": "unauthorized"}`))
return
}
log.Info("creating commit..")
userId := claims.Subject
var request CommitRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
WriteError(w, "bad json")
return
}
// check permission
projectPermission := GetProjectPermissionByID(userId, request.ProjectId)
if projectPermission < 2 {
WriteError(w, "no permission")
return
}
start := time.Now()
tx, err := dal.DbPool.Begin(ctx)
if err != nil {
log.Error("couldn't create transaction", "error", err)
WriteError(w, "db error")
return
}
defer tx.Rollback(ctx)
qtx := dal.Queries.WithTx(tx)
// make commit, get new commitid
cid, err := qtx.InsertCommit(ctx, sqlcgen.InsertCommitParams{
Projectid: int32(request.ProjectId),
Userid: userId,
Comment: request.Message,
Numfiles: int32(len(request.Files))})
if err != nil {
log.Error("db couldn't create commit", "db err", err)
WriteError(w, "db error")
return
}
var hashesMissing []string
//for _, file := range request.Files {
for i := 0; i < len(request.Files); i += 2 {
// FIXME these dont add numchunks
if i+1 >= len(request.Files) {
err = qtx.InsertFileRevision(ctx, sqlcgen.InsertFileRevisionParams{
Projectid: int32(request.ProjectId),
Path: request.Files[i].Path,
Commitid: cid,
Filehash: request.Files[i].Hash,
Changetype: int32(request.Files[i].ChangeType)})
} else {
err = qtx.InsertTwoFileRevisions(ctx, sqlcgen.InsertTwoFileRevisionsParams{
Projectid: int32(request.ProjectId),
Path: request.Files[i].Path,
Commitid: cid,
Filehash: request.Files[i].Hash,
Changetype: int32(request.Files[i].ChangeType),
Projectid_2: int32(request.ProjectId),
Path_2: request.Files[i+1].Path,
Commitid_2: cid,
Filehash_2: request.Files[i+1].Hash,
Changetype_2: int32(request.Files[i+1].ChangeType)})
}
if err != nil {
if strings.Contains(err.Error(), "FOREIGN KEY constraint failed") || strings.Contains(err.Error(), "foreign key mismatch") {
// TODO error handling here isnt very ergonomic i think
hashesMissing = append(hashesMissing, request.Files[i].Hash)
hashesMissing = append(hashesMissing, request.Files[i+1].Hash)
continue
} else {
log.Error("now-handled error inserting file revision", "db", err)
WriteError(w, "db error")
return
}
}
}
durationOne := time.Since(start)
log.Info("iterating took " + durationOne.String() + " over " + fmt.Sprint(len(request.Files)) + " files")
hashes_bytes, _ := json.Marshal(hashesMissing)
if len(hashesMissing) > 0 {
log.Warn("found missing hashes", "len", len(hashesMissing))
// respond with nb
PrintResponse(w, "nb", string(hashes_bytes))
return
}
// no hashes missing, so commit the transaction
// we should consider returning more info too
tx.Commit(ctx)
output := CreateCommitOutput{CommitId: int(cid)}
output_bytes, _ := json.Marshal(output)
durationTwo := time.Since(start)
log.Info("transaction took " + durationTwo.String())
WriteSuccess(w, string(output_bytes))
}
type CreateCommitOutput struct {
CommitId int `json:"commit_id"`
}
// input: query offset=<number>
// returns:
// {
// # of commits
// commit object list
// }
type CommitDescription struct {
CommitId int `json:"commit_id"`
CommitNumber int `json:"commit_number"`
NumFiles int `json:"num_files"`
Author string `json:"author"`
Comment string `json:"comment"`
Timestamp int64 `json:"timestamp"`
}
type CommitList struct {
NumCommit int `json:"num_commits"`
Commits []CommitDescription `json:"commits"`
}
func GetCommits(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
claims, ok := clerk.SessionClaimsFromContext(r.Context())
if !ok {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"access": "unauthorized"}`))
return
}
userId := claims.Subject
project := chi.URLParam(r, "project-id")
pid, err := strconv.Atoi(project)
if err != nil {
WriteError(w, "incorrect format")
return
}
if r.URL.Query().Get("offset") == "" {
WriteError(w, "incorrect format")
return
}
offset, err := strconv.Atoi(r.URL.Query().Get("offset"))
if err != nil {
WriteError(w, "incorrect format")
return
}
// check if user has read permission for project
if GetProjectPermissionByID(userId, pid) < 1 {
WriteError(w, "no permission")
return
}
// get commits
CommitDto, err := dal.Queries.ListProjectCommits(ctx, sqlcgen.ListProjectCommitsParams{Projectid: int32(pid), Offset: int32(offset), Limit: 8})
if err != nil {
log.Error("db error", "sql", err.Error())
WriteError(w, "db error")
return
}
// get total number
NumCommits, err := dal.Queries.CountProjectCommits(ctx, int32(pid))
if err != nil {
log.Error("db error", "sql", err.Error())
WriteError(w, "db error")
return
}
var CommitDescriptions []CommitDescription
for _, Commit := range CommitDto {
// get author from clerk + userid
usr, err := user.Get(ctx, Commit.Userid)
name := ""
if err != nil {
WriteError(w, "invalid user id")
return
}
name = *usr.FirstName + " " + *usr.LastName
CommitDescriptions = append(CommitDescriptions, CommitDescription{
CommitId: int(Commit.Commitid),
CommitNumber: int(Commit.Cno.Int32),
NumFiles: int(Commit.Numfiles),
Comment: Commit.Comment,
Timestamp: Commit.Timestamp.Time.UnixNano() / 1000000000,
Author: name,
})
}
output := CommitList{NumCommit: int(NumCommits), Commits: CommitDescriptions}
JSONList, err := json.Marshal(output)
if err != nil {
WriteError(w, "json error")
return
}
WriteSuccess(w, string(JSONList))
}
func GetCommitInformation(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
claims, ok := clerk.SessionClaimsFromContext(r.Context())
if !ok {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"access": "unauthorized"}`))
return
}
_ = ctx
_ = claims
// validate commit id
CommitIdStr := chi.URLParam(r, "commit-id")
CommitId, err := strconv.Atoi(CommitIdStr)
if err != nil {
fmt.Fprintf(w, `{ "response": "incorrect format" }`)
WriteError(w, "incorrect format")
return
}
// get commit information
CommitInfoDto, err := dal.Queries.GetCommitInfo(ctx, int32(CommitId))
if err != nil {
WriteError(w, "db error")
log.Warn("encountered db error when getting commit info", "db", err, "commit-id", CommitId)
return
}
// check permission - needs read permission minimum
if GetProjectPermissionByID(claims.Subject, int(CommitInfoDto.Projectid)) < 1 {
log.Warn("insufficient permission", "user", claims.Subject, "projectId", CommitInfoDto.Projectid)
WriteError(w, "insufficient permission")
return
}
// get file revisions
Files, err := dal.Queries.GetFileRevisionsByCommitId(ctx, int32(CommitId))
if err != nil {
WriteError(w, "db error")
log.Warn("encountered db error when getting file revisions for commit", "db", err, "commit-id", CommitId)
return
}
var Output CommitInformation
Output.FilesChanged = Files
usr, err := user.Get(ctx, CommitInfoDto.Userid)
name := ""
if err != nil {
WriteError(w, "invalid user id")
return
}
name = *usr.FirstName + " " + *usr.LastName
Output.Description = CommitDescription{
CommitId: CommitId,
CommitNumber: int(CommitInfoDto.Cno.Int32),
NumFiles: int(CommitInfoDto.Numfiles),
Comment: CommitInfoDto.Comment,
Timestamp: CommitInfoDto.Timestamp.Time.UnixNano() / 1000000000,
Author: name,
}
OutputJson, err := json.Marshal(Output)
if err != nil {
WriteError(w, "json error")
return
}
WriteSuccess(w, string(OutputJson))
}
type CommitInformation struct {
Description CommitDescription `json:"description"`
FilesChanged []sqlcgen.GetFileRevisionsByCommitIdRow `json:"files"`
}