summaryrefslogtreecommitdiff
path: root/mumi/bugs.scm
blob: d371dbb8a129ba5dbba956ae9c8a8e6a24c6c027 (about) (plain)
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
;;; mumi -- Mediocre, uh, mail interface
;;; Copyright © 2020 Ricardo Wurmus <rekado@elephly.net>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU Affero 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
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with this program.  If not, see
;;; <http://www.gnu.org/licenses/>.

(define-module (mumi bugs)
  #:use-module (mumi config)
  #:use-module (debbugs)
  #:use-module (sqlite3)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 format)
  #:export (db-create!
            update-bug-database!

            bugs-by-tag
            bugs-by-severity
            bugs-by-status
            bugs-by-submitter
            bugs-by-owner))


;; This procedure and the following two macros have been taken from
;; Cuirass.
(define (%sqlite-exec db sql . args)
  "Evaluate the given SQL query with the given ARGS.  Return the list of
rows."
  (define (normalize arg)
    ;; Turn ARG into a string, unless it's a primitive SQL datatype.
    (if (or (null? arg) (pair? arg) (vector? arg))
        (object->string arg)
        arg))

  (let ((stmt (sqlite-prepare db sql #:cache? #t)))
    (for-each (lambda (arg index)
                (sqlite-bind stmt index (normalize arg)))
              args (iota (length args) 1))
    (let ((result (sqlite-fold-right cons '() stmt)))
      (sqlite-finalize stmt)
      result)))

(define-syntax sqlite-exec/bind
  (lambda (s)
    ;; Expand to an '%sqlite-exec' call where the query string has
    ;; interspersed question marks and the argument list is separate.
    (define (string-literal? s)
      (string? (syntax->datum s)))

    (syntax-case s ()
      ((_ db (bindings ...) tail str arg rest ...)
       #'(sqlite-exec/bind db
                           (bindings ... (str arg))
                           tail
                           rest ...))
      ((_ db (bindings ...) tail str)
       #'(sqlite-exec/bind db (bindings ...) str))
      ((_ db ((strings args) ...) tail)
       (and (every string-literal? #'(strings ...))
            (string-literal? #'tail))
       ;; Optimized case: only string literals.
       (with-syntax ((query (string-join
                             (append (syntax->datum #'(strings ...))
                                     (list (syntax->datum #'tail)))
                             "? ")))
         #'(%sqlite-exec db query args ...)))
      ((_ db ((strings args) ...) tail)
       ;; Fallback case: some of the strings aren't literals.
       #'(%sqlite-exec db (string-join (list strings ... tail) "? ")
                       args ...)))))

(define-syntax-rule (sqlite-exec db query args ...)
  "Execute the specific QUERY with the given ARGS.  Uses of 'sqlite-exec'
typically look like this:

  (sqlite-exec db \"SELECT * FROM Foo WHERE x = \"
                  x \"AND Y=\" y \";\")

References to variables 'x' and 'y' here are replaced by question marks in the
SQL query, and then 'sqlite-bind' is used to bind them.

This ensures that (1) SQL injection is impossible, and (2) the number of
question marks matches the number of arguments to bind."
  (sqlite-exec/bind db () "" query args ...))

(define (last-insert-rowid db)
  (vector-ref (car (sqlite-exec db "SELECT last_insert_rowid();"))
              0))

(define %db-name
  (string-append (%config 'db-dir) "/bugs.db"))

(define* (with-db proc #:key write?)
  (let ((db (sqlite-open %db-name (logior (if write?
                                              SQLITE_OPEN_READWRITE
                                              SQLITE_OPEN_READONLY)
                                          SQLITE_OPEN_NOMUTEX))))
    (dynamic-wind
      (const #t)
      (lambda ()
        (proc db))
      (lambda () (sqlite-close db)))))

(define (read-sql-file file-name)
  "Return a list of string containing SQL instructions from FILE-NAME."
  (call-with-input-file file-name
    (lambda (port)
      (let loop ((insts '()))
        (let ((inst (read-delimited ";" port 'concat)))
          (if (or (eof-object? inst)
                  ;; Don't cons the spaces after the last instructions.
                  (string-every char-whitespace? inst))
              (reverse! insts)
              (loop (cons inst insts))))))))

(define (db-load db schema)
  "Evaluate the file SCHEMA, which may contain SQL queries, into DB."
  (for-each (cut sqlite-exec db <>)
            (read-sql-file schema)))

(define (db-create!)
  (unless (file-exists? %db-name)
    (let ((db (sqlite-open %db-name (logior SQLITE_OPEN_CREATE
                                            SQLITE_OPEN_READWRITE
                                            SQLITE_OPEN_NOMUTEX))))
      (db-load db (string-append (%config 'pkg-dir) "/schema.sql"))
      db)))


(define (add-bug! id submitter owner status severity tags)
  "Record a new bug with the given fields, or update an existing
record."
  (let ((tag-string
         (if tags (string-append "|"
                                 (string-join (string-split tags #\space) "|" 'suffix))
             "")))
    (with-db (lambda (db)
               (sqlite-exec db
                            "INSERT INTO bugs (id, submitter, owner, status, severity, tags) VALUES ("
                            id "," submitter "," owner "," status "," severity "," tag-string
                            ") ON CONFLICT(id) DO UPDATE SET \
status=excluded.status,\
submitter=excluded.submitter,\
owner=excluded.owner,\
severity=excluded.severity,\
tags=excluded.tags;")
               (last-insert-rowid db))
             #:write? #t)))

(define (bugs-by-status status)
  "Return all bug ids with the given STATUS."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db
                       "SELECT id FROM bugs WHERE status = " status ";")))))

(define (bugs-by-severity severity)
  "Return all bug ids with the given SEVERITY."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db
                       "SELECT id FROM bugs WHERE severity = " severity ";")))))

(define (bugs-by-submitter submitter)
  "Return all bug ids with the given SUBMITTER."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db
                       "SELECT id FROM bugs WHERE submitter LIKE "
                       (string-append "%" submitter "%") ";")))))

(define (bugs-by-owner owner)
  "Return all bug ids with the given OWNER."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db
                       "SELECT id FROM bugs WHERE owner LIKE "
                       (string-append "%" owner "%") ";")))))

(define (bugs-by-tag tag)
  "Return all bug ids that match the given TAG."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db
                       "SELECT id FROM bugs WHERE tags LIKE "
                       (string-append "%|" tag "|%") ";")))))

(define (bug-ids)
  "Return all bug ids."
  (map (cut vector-ref <> 0)
       (with-db
        (lambda (db)
          (sqlite-exec db "SELECT id FROM bugs;")))))

(define* (update-bug-database! #:optional bug-nums)
  (define chunk-size 400)
  (define (safe-split lst n)
    (catch #t
      (lambda ()
        (split-at lst n))
      (lambda _
        (values lst '()))))
  (let* ((bug-nums (or bug-nums
                       (apply lset-adjoin =
                              (append-map (lambda (package)
                                            (soap-invoke (%config 'debbugs)
                                                         get-bugs
                                                         `((package . ,package))))
                                          (%config 'packages))
                              (bug-ids))))
         (total (length bug-nums)))
    (display "updating bug database...")
    ;; Process bugs in chunks
    (let loop ((lst bug-nums))
      (let-values (((chunk tail) (safe-split lst chunk-size)))
        (let ((bugs (soap-invoke* (%config 'debbugs) get-status chunk)))
          (for-each (lambda (bug)
                      (add-bug! (bug-num bug)
                                (bug-originator bug)
                                (bug-owner bug)
                                (cond
                                 ((bug-done bug) "done")
                                 (else "open"))
                                (bug-severity bug)
                                (bug-tags bug)))
                    bugs)
          (let* ((done (- total (length tail)))
                 (ratio (/ done total)))
            (if (eq? done total)
                (display "100%!" (current-error-port))
                (format (current-error-port)
                        "~,1f%..." (exact->inexact (* 100 ratio))))))
        (if (null? tail) (newline (current-error-port)) (loop tail))))))