~niklaseklund/egerrit

ref: 86b1079e0089e9fc2f338589f4ec4cd712fef98d egerrit/egerrit-core.el -rw-r--r-- 13.6 KiB
86b1079eNiklas Eklund Fix broken tests 3 months ago
                                                                                
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
;;; egerrit-core.el --- Core for egerrit -*- lexical-binding: t; -*-

;; Copyright (C) 2022  Free Software Foundation, Inc.

;; This file is not part of GNU Emacs.

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; This library provides the core for `egerrit'.

;;; Code:

;;;; Requirements

(require 'egerrit-datastructures)
(require 'egerrit-request)
(require 'subr-x)

(declare-function egerrit-get-conversations "egerrit")

(defvar egerrit--mode)
(defvar egerrit-job-function)
(defvar egerrit-max-changes)
(defvar egerrit-gerrit-conversation-context)

;;;; Variables

(defcustom egerrit-project-configs nil
  "Variable to store project configs."
  :type 'list
  :group 'egerrit)

(defvar egerrit--current-git-branch nil
  "Name of the current git branch.")

;;;;; Private

(defvar egerrit--switch-branch t
  "Tell `egerrit' to enable branch switching.")

;;;; Functions

(defun egerrit-get-changes (query)
  "Return a list of `egerrit-change' objects based on QUERY."
  (thread-last query
               (seq-map (lambda (it)
                          (let ((changes (seq-map #'egerrit--create-change (apply #'egerrit--read-changes (cdr it)))))
                            (when changes
                              `(,(car it) ; Header line
                                ,@changes
                                "" ; Empty line
                                )))))
               (flatten-list)
               (seq-remove #'null)
               (butlast)))

(defun egerrit-get-detailed-change (change)
  "Return a detailed `egerrit-change' object for CHANGE."
  (let* ((changeid (url-unhex-string (egerrit-change-id change)))
         (json-entity (elt (egerrit--read-change changeid) 0)))
    (thread-last (egerrit--create-detailed-change json-entity)
                 (funcall egerrit-job-function))))

(cl-defmethod egerrit-annotator-config (_entity)
  "Return annotation configuration for ENTITY.")

(defun egerrit-select-change (changes)
  "Select a change from the list of CHANGES."
  (let* ((candidates
          (thread-last changes
                       (seq-map
                        (lambda (it)
                          (egerrit--completing-read-annotator it)))))
         (metadata `(metadata
                     (category . egerrit-change)
                     (cycle-sort-function . identity)
                     (display-sort-function . identity)))
         (collection (lambda (string predicate action)
                       (if (eq action 'metadata)
                           metadata
                         (complete-with-action action candidates string predicate))))
         (cand (completing-read "Select change: " collection nil t)))
    (cdr (assoc cand candidates))))

(defun egerrit-get-buffer (name)
  "Return an `egerrit' buffer with NAME."
  (let* ((directory default-directory)
         (host (or (file-remote-p default-directory 'host) ""))
         (buffer-name
          (if (string= host "")
              (format "*%s*" name)
            (format "*%s <%s>*" name host)))
         (buffer-candidate
          (thread-last (buffer-list)
                       (seq-map #'buffer-name)
                       (seq-find (lambda (it) (string= it buffer-name))))))
    (if buffer-candidate
        (get-buffer buffer-candidate)
      (let ((buffer (generate-new-buffer buffer-name)))
        (with-current-buffer buffer
          (setq-local default-directory directory))
        buffer))))

(defun egerrit-get-project-root (entity)
  "Return the project root for ENTITY."
  (let* ((remote (file-remote-p default-directory))
         (config (seq-find (lambda (it)
                             (string= (egerrit-project entity)
                                      (plist-get it ':name)))
                           egerrit-project-configs))
         (root (when config
                 (cond ((eq egerrit--mode 'author)
                        (plist-get config ':code-repo))
                       ((eq egerrit--mode 'reviewer)
                        (or (plist-get config ':review-repo)
                            (plist-get config ':code-repo)))
                       (t (plist-get config ':code-repo))))))
    (if root
        (if remote
            (concat remote root)
          root)
      root
      (message "No root found for project: %s" (egerrit-project entity)))))


(cl-defun egerrit-start-process (process-name
                                 command
                                 &key
                                 (success-message "Finished"))
  "Start a process named PROCESS-NAME and execute COMMAND.

Send message SUCCESS-MESSAGE upon success."
  (let* ((program shell-file-name)
         (buffer (format " *%s*" process-name))
         (args `(,process-name ,buffer ,program "-c" ,command)))
    (with-current-buffer (get-buffer-create buffer)
      (setf (buffer-string) ""))
    (set-process-sentinel
     (apply #'start-file-process args)
     (lambda (_ event)
       (cond ((string-match-p "finished" event)
              (message success-message))
             (t (pop-to-buffer buffer)))))))

;;;; Support functions

(defun egerrit--completing-read-annotator (entity)
  "Create an annotated string of ENTITY."
  (let* ((config (egerrit-annotator-config entity))
         (str (cl-loop for annotation in config
                       collect (let ((str (funcall (plist-get annotation :function) entity)))
                                 (truncate-string-to-width
                                  str
                                  (plist-get annotation :length)
                                  0 ?\s)))))
    `(,(string-join str "") . ,entity)))

(defun egerrit--create-change (change)
  "Return a `egerrit-change' created from CHANGE."
  (let-alist change
    (egerrit--change-create
     :id .id
     :changeid .change_id
     :number ._number
     :project .project
     :subject .subject
     :status .status
     :created (egerrit--compensate-time-with-timezone .created)
     :updated (egerrit--compensate-time-with-timezone .updated)
     :topic .topic
     :work-in-progress .work_in_progress
     :owner (egerrit--create-user .owner)
     :assignee (egerrit--create-user .assignee)
     :reviews (egerrit--create-reviews .labels)
     :unresolved-comments .unresolved_comment_count)))

(defun egerrit--create-detailed-change (change)
  "Return a detailed `egerrit-change' created from CHANGE."
  (let-alist change
    (let ((egerrit--current-change-number ._number)
          (egerrit--current-change-id .change_id)
          (egerrit--current-project .project))
      (egerrit--change-create
       :id .id
       :project egerrit--current-project
       :branch .branch
       :topic .topic
       :changeid egerrit--current-change-id
       :subject .subject
       :status .status
       :created (egerrit--compensate-time-with-timezone .created)
       :updated  (egerrit--compensate-time-with-timezone .updated)
       :conversations (egerrit-get-conversations egerrit--current-change-id)
       :unresolved-comments .unresolved_comment_count
       :number egerrit--current-change-number
       :owner (egerrit--create-user .owner)
       :reviewers .reviewers
       :labels .labels
       :assignee .assignee
       :messages (egerrit--create-messages .messages)
       :work-in-progress .work_in_progress
       :current-revision .current_revision
       :revisions (egerrit--create-revisions .revisions)))))

(defun egerrit--create-messages (messages)
  "Return a list `egerrit-message' objects created from MESSAGES."
  (seq-map (lambda (message)
             (let-alist message
               (egerrit--message-create
                :id .id
                :author (egerrit--create-user .author)
                :date .date
                :message .message
                :number ._revision_number)))
           messages))

(defun egerrit--create-user (user)
  "Convert USER into a `egerrit-user' object."
  (let-alist user
    (egerrit--user-create
     :name .name
     :username .username
     :email .email)))

(defun egerrit--create-revisions (revisions)
  "Return a list of `egerrit-revision' objects created from REVISIONS."
  (thread-last revisions
               (seq-map (lambda (it)
                          (cl-destructuring-bind (id . revision) it
                            (let-alist revision
                              (let ((egerrit--current-revision-id id)
                                    (egerrit--current-revision-number ._number))
                                (egerrit--revision-create
                                 :id egerrit--current-revision-id
                                 :number egerrit--current-revision-number
                                 :created (egerrit--compensate-time-with-timezone .created)
                                 :uploader (egerrit--create-user .uploader)
                                 :ref .ref
                                 :fetch (egerrit--create-fetch .fetch)
                                 :commit (egerrit--create-commit .commit)))))))
               (seq-sort-by #'egerrit--revision-number #'<)))

(defun egerrit--create-commit (commit)
  "Return an `egerrit-commit' object created from COMMIT."
  (let-alist commit
    (egerrit--commit-create
     :parents .parents
     :author (egerrit--create-user .author)
     :committer (egerrit--create-user .comitter)
     :subject .subject
     :message .message)))

(defun egerrit--create-range (range)
  "Return a `egerrit-range' object based on RANGE."
  (let-alist range
    (egerrit--range-create
     :start-line .start_line
     :start-character .start_character
     :end-line .end_line
     :end-character .end_character)))

(defun egerrit--create-reviews (reviews)
  "Return a list of `egerrit-review' objects created from REVIEWS."
  (let ((review-types '(Code-Review Secondary-Review Verified)))
    (seq-map (lambda (type)
               (let* ((review (alist-get type reviews))
                      (value (caar review))
                      (info (alist-get value review)))
                 (egerrit--review-create
                  :type type
                  :value value
                  :reviewer (egerrit--create-user info))))
             review-types)))

(defun egerrit--create-fetch (fetch)
  "Convert FETCH into a `egerrit-fetch' object."
  (let-alist fetch
    (egerrit--fetch-create
     :ssh (egerrit--create-download .ssh)
     :http (egerrit--create-download .http))))

(defun egerrit--create-download (download)
  "Convert DOWNLOAD into a `egerrit-download' object."
  (let-alist download
    (egerrit--download-create
     :url .url
     :ref .ref
     :checkout .commands.Checkout
     :cherry-pick .commands.Cherry\ Pick
     :format-patch .commands.Format\ Patch
     :cherry-pick .commands.Cherry\ Pick
     :pull .commands.Pull)))

(defun egerrit--read-change (id)
  "Query Gerrit for ID."
  (let* ((params
          `(("q" ,id)
            ("o" "DETAILED_LABELS")
            ("o" "ALL_REVISIONS")
            ("o" "ALL_COMMITS")
            ("o" "DETAILED_ACCOUNTS")
            ("o" "MESSAGES")
            ("o" "CHANGE_ACTIONS")
            ("o" "REVIEWER_UPDATES")
            ("o" "DOWNLOAD_COMMANDS"))))
    (egerrit-request-read-changes params)))

(defun egerrit--read-changes (query &optional max-changes)
  "Send QUERY to Gerrit for change(s) with MAX-CHANGES."
  (let* ((max-changes (or max-changes egerrit-max-changes))
         (params `(("q" ,query)
                   ("n" ,max-changes)
                   ("o" "LABELS")
                   ("o" "DETAILED_ACCOUNTS"))))
    (egerrit-request-read-changes params)))

(defun egerrit--read-comments (changeid)
  "Query Gerrit for comments on CHANGEID."
  (let* ((params `(("enable-context" "true")
                   ("context-padding" ,egerrit-gerrit-conversation-context))))
    (egerrit-request-read-comments
     changeid
     params)))

(defun egerrit--read-users (max-users start-offset &optional name-contain)
  "Query Gerrit for all users with MAX-USERS and START-OFFSET.

Optionally provide a NAME-CONTAIN variable to narrow the search space."
  (let* ((params `(("q" ,(if name-contain
                             (concat "is:active AND name:" name-contain)
                           "is:active"))
                   ("o" "DETAILS")
                   ("n" ,(number-to-string max-users))
                   ("start" ,(number-to-string start-offset)))))
    (egerrit-request-read-users
     params)))

(defun egerrit--post-message (message change)
  "Send MESSAGE to CHANGE."
  (egerrit-request-create-message
   (egerrit-change-id change)
   (egerrit--change-current-revision change)
   message))

(defun egerrit--post-reviewer (reviewer change)
  "Add REVIEWER to CHANGE."
  (egerrit-request-create-reviewer
   (egerrit-change-id change)
   reviewer))

(defun egerrit--post-cc (reviewer change)
  "Add REVIEWER to CHANGE."
  (egerrit-request-create-cc-reviewer
   (egerrit-change-id change)
   reviewer))

(defun egerrit--compensate-time-with-timezone (utc-time)
  "Compensate UTC-TIME to time-zone on the local-host."
  (when utc-time
    (let ((time-zone (current-time-zone)))
      (format-time-string "%Y-%m-%d %H:%M:%S %z"
                          (time-add (date-to-time utc-time)
                                    (car time-zone))))))

(provide 'egerrit-core)

;;; egerrit-core.el ends here