aboutsummaryrefslogtreecommitdiff
path: root/guix/scripts/lint.scm
blob: 9b991786c3403730591acd3aef1bc59b5e384df4 (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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Cyril Roelandt <tipecaml@gmail.com>
;;; Copyright © 2014, 2015 Eric Bavier <bavier@member.fsf.org>
;;; Copyright © 2013, 2014, 2015, 2016 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2015, 2016 Mathieu Lirzin <mthl@gnu.org>
;;; Copyright © 2016 Danny Milosavljevic <dannym+a@scratchpost.org>
;;; Copyright © 2016 Hartmut Goebel <h.goebel@crazy-compilers.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix 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.
;;;
;;; GNU Guix 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 GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix scripts lint)
  #:use-module ((guix store) #:hide (close-connection))
  #:use-module (guix base32)
  #:use-module (guix download)
  #:use-module (guix ftp-client)
  #:use-module (guix http-client)
  #:use-module (guix packages)
  #:use-module (guix licenses)
  #:use-module (guix records)
  #:use-module (guix ui)
  #:use-module (guix utils)
  #:use-module (guix combinators)
  #:use-module (guix scripts)
  #:use-module (guix gnu-maintenance)
  #:use-module (guix monads)
  #:use-module (guix cve)
  #:use-module (gnu packages)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 format)
  #:use-module (web uri)
  #:use-module ((guix build download)
                #:select (maybe-expand-mirrors
                          open-connection-for-uri
                          close-connection))
  #:use-module (web request)
  #:use-module (web response)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-6)                      ;Unicode string ports
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-37)
  #:use-module (ice-9 rdelim)
  #:export (guix-lint
            check-description-style
            check-inputs-should-be-native
            check-inputs-should-not-be-an-input-at-all
            check-patch-file-names
            check-synopsis-style
            check-derivation
            check-home-page
            check-source
            check-source-file-name
            check-mirror-url
            check-license
            check-vulnerabilities
            check-formatting
            run-checkers

            %checkers
            lint-checker
            lint-checker?
            lint-checker-name
            lint-checker-description
            lint-checker-check))


;;;
;;; Helpers
;;;
(define* (emit-warning package message #:optional field)
  ;; Emit a warning about PACKAGE, printing the location of FIELD if it is
  ;; given, the location of PACKAGE otherwise, the full name of PACKAGE and the
  ;; provided MESSAGE.
  (let ((loc (or (package-field-location package field)
                 (package-location package))))
    (format (guix-warning-port) "~a: ~a: ~a~%"
            (location->string loc)
            (package-full-name package)
            message)))

(define (call-with-accumulated-warnings thunk)
  "Call THUNK, accumulating any warnings in the current state, using the state
monad."
  (let ((port (open-output-string)))
    (mlet %state-monad ((state      (current-state))
                        (result ->  (parameterize ((guix-warning-port port))
                                      (thunk)))
                        (warning -> (get-output-string port)))
      (mbegin %state-monad
        (munless (string=? "" warning)
          (set-current-state (cons warning state)))
        (return result)))))

(define-syntax-rule (with-accumulated-warnings exp ...)
  "Evaluate EXP and accumulate warnings in the state monad."
  (call-with-accumulated-warnings
   (lambda ()
     exp ...)))


;;;
;;; Checkers
;;;
(define-record-type* <lint-checker>
  lint-checker make-lint-checker
  lint-checker?
  ;; TODO: add a 'certainty' field that shows how confident we are in the
  ;; checker. Then allow users to only run checkers that have a certain
  ;; 'certainty' level.
  (name        lint-checker-name)
  (description lint-checker-description)
  (check       lint-checker-check))

(define (list-checkers-and-exit)
  ;; Print information about all available checkers and exit.
  (format #t (_ "Available checkers:~%"))
  (for-each (lambda (checker)
              (format #t "- ~a: ~a~%"
                      (lint-checker-name checker)
                      (_ (lint-checker-description checker))))
            %checkers)
  (exit 0))

(define (properly-starts-sentence? s)
  (string-match "^[(\"'`[:upper:][:digit:]]" s))

(define (starts-with-abbreviation? s)
  "Return #t if S starts with what looks like an abbreviation or acronym."
  (string-match "^[A-Z][A-Z0-9]+\\>" s))

(define %quoted-identifier-rx
  ;; A quoted identifier, like 'this'.
  (make-regexp "['`][[:graph:]]+'"))

(define (check-description-style package)
  ;; Emit a warning if stylistic issues are found in the description of PACKAGE.
  (define (check-not-empty description)
    (when (string-null? description)
      (emit-warning package
                    (_ "description should not be empty")
                    'description)))

  (define (check-texinfo-markup description)
    "Check that DESCRIPTION can be parsed as a Texinfo fragment.  If the
markup is valid return a plain-text version of DESCRIPTION, otherwise #f."
    (catch #t
      (lambda () (texi->plain-text description))
      (lambda (keys . args)
        (emit-warning package
                      (_ "Texinfo markup in description is invalid")
                      'description)
        #f)))

  (define (check-trademarks description)
    "Check that DESCRIPTION does not contain '™' or '®' characters.  See
http://www.gnu.org/prep/standards/html_node/Trademarks.html."
    (match (string-index description (char-set #\™ #))
      ((and (? number?) index)
       (emit-warning package
                     (format #f (_ "description should not contain ~
trademark sign '~a' at ~d")
                             (string-ref description index) index)
                     'description))
      (else #t)))

  (define (check-quotes description)
    "Check whether DESCRIPTION contains single quotes and suggest @code."
    (when (regexp-exec %quoted-identifier-rx description)
      (emit-warning package

                    ;; TRANSLATORS: '@code' is Texinfo markup and must be kept
                    ;; as is.
                    (_ "use @code or similar ornament instead of quotes")
                    'description)))

  (define (check-proper-start description)
    (unless (or (properly-starts-sentence? description)
                (string-prefix-ci? (package-name package) description))
      (emit-warning package
                    (_ "description should start with an upper-case letter or digit")
                    'description)))

  (define (check-end-of-sentence-space description)
    "Check that an end-of-sentence period is followed by two spaces."
    (let ((infractions
           (reverse (fold-matches
                     "\\. [A-Z]" description '()
                     (lambda (m r)
                       ;; Filter out matches of common abbreviations.
                       (if (find (lambda (s)
                                   (string-suffix-ci? s (match:prefix m)))
                                 '("i.e" "e.g" "a.k.a" "resp"))
                           r (cons (match:start m) r)))))))
      (unless (null? infractions)
        (emit-warning package
                      (format #f (_ "sentences in description should be followed ~
by two spaces; possible infraction~p at ~{~a~^, ~}")
                              (length infractions)
                              infractions)
                      'description))))

  (let ((description (package-description package)))
    (if (string? description)
        (begin
          (check-not-empty description)
          (check-quotes description)
          (check-trademarks description)
          ;; Use raw description for this because Texinfo rendering
          ;; automatically fixes end of sentence space.
          (check-end-of-sentence-space description)
          (and=> (check-texinfo-markup description)
                 check-proper-start))
        (emit-warning package
                      (format #f (_ "invalid description: ~s") description)
                      'description))))

(define (warn-if-package-has-input linted inputs-to-check input-names message)
  ;; Emit a warning MESSAGE if some of the inputs named in INPUT-NAMES are
  ;; contained in INPUTS-TO-CHECK, which are assumed to be inputs of package
  ;; LINTED.
  (match inputs-to-check
    (((labels packages . outputs) ...)
     (for-each (lambda (package output)
                 (when (package? package)
                   (let ((input (string-append
                                 (package-name package)
                                 (if (> (length output) 0)
                                     (string-append ":" (car output))
                                     ""))))
                     (when (member input input-names)
                       (emit-warning linted
                                     (format #f (_ message) input)
                                     'inputs-to-check)))))
               packages outputs))))

(define (check-inputs-should-be-native package)
  ;; Emit a warning if some inputs of PACKAGE are likely to belong to its
  ;; native inputs.
  (let ((message "'~a' should probably be a native input")
        (inputs (package-inputs package))
        (input-names
          '("pkg-config"
            "extra-cmake-modules"
            "glib:bin"
            "intltool"
            "itstool"
            "qttools"
            "python-coverage" "python2-coverage"
            "python-cython" "python2-cython"
            "python-docutils" "python2-docutils"
            "python-mock" "python2-mock"
            "python-nose" "python2-nose"
            "python-pbr" "python2-pbr"
            "python-pytest" "python2-pytest"
            "python-pytest-cov" "python2-pytest-cov"
            "python-setuptools-scm" "python2-setuptools-scm"
            "python-sphinx" "python2-sphinx")))
    (warn-if-package-has-input package inputs input-names message)))

(define (check-inputs-should-not-be-an-input-at-all package)
  ;; Emit a warning if some inputs of PACKAGE are likely to should not be
  ;; an input at all.
  (let ((message "'~a' should probably not be an input at all")
        (inputs (package-inputs package))
        (input-names
          '("python-setuptools"
            "python2-setuptools"
            "python-pip"
            "python2-pip")))
    (warn-if-package-has-input package (package-inputs package)
                               input-names message)
    (warn-if-package-has-input package (package-native-inputs package)
                               input-names message)
    (warn-if-package-has-input package (package-propagated-inputs package)
                               input-names message)))

(define (package-name-regexp package)
  "Return a regexp that matches PACKAGE's name as a word at the beginning of a
line."
  (make-regexp (string-append "^" (regexp-quote (package-name package))
                              "\\>")
               regexp/icase))

(define (check-synopsis-style package)
  ;; Emit a warning if stylistic issues are found in the synopsis of PACKAGE.
  (define (check-not-empty synopsis)
    (when (string-null? synopsis)
      (emit-warning package
                    (_ "synopsis should not be empty")
                    'synopsis)))

  (define (check-final-period synopsis)
    ;; Synopsis should not end with a period, except for some special cases.
    (when (and (string-suffix? "." synopsis)
               (not (string-suffix? "etc." synopsis)))
      (emit-warning package
                    (_ "no period allowed at the end of the synopsis")
                    'synopsis)))

  (define check-start-article
    ;; Skip this check for GNU packages, as suggested by Karl Berry's reply to
    ;; <http://lists.gnu.org/archive/html/bug-womb/2014-11/msg00000.html>.
    (if (false-if-exception (gnu-package? package))
        (const #t)
        (lambda (synopsis)
          (when (or (string-prefix-ci? "A " synopsis)
                    (string-prefix-ci? "An " synopsis))
            (emit-warning package
                          (_ "no article allowed at the beginning of \
the synopsis")
                          'synopsis)))))

  (define (check-synopsis-length synopsis)
    (when (>= (string-length synopsis) 80)
      (emit-warning package
                    (_ "synopsis should be less than 80 characters long")
                    'synopsis)))

  (define (check-proper-start synopsis)
    (unless (properly-starts-sentence? synopsis)
      (emit-warning package
                    (_ "synopsis should start with an upper-case letter or digit")
                    'synopsis)))

  (define (check-start-with-package-name synopsis)
    (when (and (regexp-exec (package-name-regexp package) synopsis)
               (not (starts-with-abbreviation? synopsis)))
      (emit-warning package
                    (_ "synopsis should not start with the package name")
                    'synopsis)))

  (define checks
    (list check-not-empty check-proper-start check-final-period
          check-start-article check-start-with-package-name
          check-synopsis-length))

  (match (package-synopsis package)
    ((? string? synopsis)
     (for-each (lambda (proc)
                 (proc synopsis))
               checks))
    (invalid
     (emit-warning package (format #f (_ "invalid synopsis: ~s") invalid)
                   'synopsis))))

(define* (probe-uri uri #:key timeout)
  "Probe URI, a URI object, and return two values: a symbol denoting the
probing status, such as 'http-response' when we managed to get an HTTP
response from URI, and additional details, such as the actual HTTP response.

TIMEOUT is the maximum number of seconds (possibly an inexact number) to wait
for connections to complete; when TIMEOUT is #f, wait as long as needed."
  (define headers
    '((User-Agent . "GNU Guile")
      (Accept . "*/*")))

  (let loop ((uri     uri)
             (visited '()))
    (match (uri-scheme uri)
      ((or 'http 'https)
       (catch #t
         (lambda ()
           (let ((port    (open-connection-for-uri uri #:timeout timeout))
                 (request (build-request uri #:headers headers)))
             (define response
               (dynamic-wind
                 (const #f)
                 (lambda ()
                   (write-request request port)
                   (force-output port)
                   (read-response port))
                 (lambda ()
                   (close-connection port))))

             (case (response-code response)
               ((301 302 307)
                (let ((location (response-location response)))
                  (if (or (not location) (member location visited))
                      (values 'http-response response)
                      (loop location (cons location visited))))) ;follow the redirect
               (else
                (values 'http-response response)))))
         (lambda (key . args)
           (case key
             ((bad-header bad-header-component)
              ;; This can happen if the server returns an invalid HTTP header,
              ;; as is the case with the 'Date' header at sqlite.org.
              (values 'invalid-http-response #f))
             ((getaddrinfo-error system-error
               gnutls-error tls-certificate-error)
              (values key args))
             (else
              (apply throw key args))))))
      ('ftp
       (catch #t
         (lambda ()
           (let ((conn (ftp-open (uri-host uri) #:timeout timeout)))
             (define response
               (dynamic-wind
                 (const #f)
                 (lambda ()
                   (ftp-chdir conn (dirname (uri-path uri)))
                   (ftp-size conn (basename (uri-path uri))))
                 (lambda ()
                   (ftp-close conn))))
             (values 'ftp-response '(ok))))
         (lambda (key . args)
           (case key
             ((ftp-error)
              (values 'ftp-response `(error ,@args)))
             ((getaddrinfo-error system-error gnutls-error)
              (values key args))
             (else
              (apply throw key args))))))
      (_
       (values 'unknown-protocol #f)))))

(define (tls-certificate-error-string args)
  "Return a string explaining the 'tls-certificate-error' arguments ARGS."
  (call-with-output-string
    (lambda (port)
      (print-exception port #f
                       'tls-certificate-error args))))

(define (validate-uri uri package field)
  "Return #t if the given URI can be reached, otherwise return #f and emit a
warning for PACKAGE mentionning the FIELD."
  (let-values (((status argument)
                (probe-uri uri #:timeout 3)))     ;wait at most 3 seconds
    (case status
      ((http-response)
       (if (= 200 (response-code argument))
           (match (response-content-length argument)
             ((? number? length)
              ;; As of July 2016, SourceForge returns 200 (instead of 404)
              ;; with a small HTML page upon failure.  Attempt to detect such
              ;; malicious behavior.
              (or (> length 1000)
                  (begin
                    (emit-warning package
                                  (format #f
                                          (_ "URI ~a returned \
suspiciously small file (~a bytes)")
                                          (uri->string uri)
                                          length))
                    #f)))
             (_ #t))
           (begin
             (emit-warning package
                           (format #f
                                   (_ "URI ~a not reachable: ~a (~s)")
                                   (uri->string uri)
                                   (response-code argument)
                                   (response-reason-phrase argument))
                           field)
             #f)))
      ((ftp-response)
       (match argument
         (('ok) #t)
         (('error port command code message)
          (emit-warning package
                        (format #f
                                (_ "URI ~a not reachable: ~a (~s)")
                                (uri->string uri)
                                code (string-trim-both message)))
          #f)))
      ((getaddrinfo-error)
       (emit-warning package
                     (format #f
                             (_ "URI ~a domain not found: ~a")
                             (uri->string uri)
                             (gai-strerror (car argument)))
                     field)
       #f)
      ((system-error)
       (emit-warning package
                     (format #f
                             (_ "URI ~a unreachable: ~a")
                             (uri->string uri)
                             (strerror
                              (system-error-errno
                               (cons status argument))))
                     field)
       #f)
      ((tls-certificate-error)
       (emit-warning package
                     (format #f (_ "TLS certificate error: ~a")
                             (tls-certificate-error-string argument))))
      ((invalid-http-response gnutls-error)
       ;; Probably a misbehaving server; ignore.
       #f)
      ((unknown-protocol)                             ;nothing we can do
       #f)
      (else
       (error "internal linter error" status)))))

(define (check-home-page package)
  "Emit a warning if PACKAGE has an invalid 'home-page' field, or if that
'home-page' is not reachable."
  (let ((uri (and=> (package-home-page package) string->uri)))
    (cond
     ((uri? uri)
      (validate-uri uri package 'home-page))
     ((not (package-home-page package))
      (unless (or (string-contains (package-name package) "bootstrap")
                  (string=? (package-name package) "ld-wrapper"))
        (emit-warning package
                      (_ "invalid value for home page")
                      'home-page)))
     (else
      (emit-warning package (format #f (_ "invalid home page URL: ~s")
                                    (package-home-page package))
                    'home-page)))))

(define (check-patch-file-names package)
  "Emit a warning if the patches requires by PACKAGE are badly named or if the
patch could not be found."
  (guard (c ((message-condition? c)     ;raised by 'search-patch'
             (emit-warning package (condition-message c)
                           'patch-file-names)))
    (unless (every (match-lambda        ;patch starts with package name?
                     ((? string? patch)
                      (and=> (string-contains (basename patch)
                                              (package-name package))
                             zero?))
                     (_  #f))     ;must be an <origin> or something like that.
                   (or (and=> (package-source package) origin-patches)
                       '()))
      (emit-warning
       package
       (_ "file names of patches should start with the package name")
       'patch-file-names))))

(define (escape-quotes str)
  "Replace any quote character in STR by an escaped quote character."
  (list->string
   (string-fold-right (lambda (chr result)
                        (match chr
                          (#\" (cons* #\\ #\"result))
                          (_   (cons chr result))))
                      '()
                      str)))

(define official-gnu-packages*
  (memoize
   (lambda ()
     "A memoizing version of 'official-gnu-packages' that returns the empty
list when something goes wrong, such as a networking issue."
     (let ((gnus (false-if-exception (official-gnu-packages))))
       (or gnus '())))))

(define (check-gnu-synopsis+description package)
  "Make sure that, if PACKAGE is a GNU package, it uses the synopsis and
descriptions maintained upstream."
  (match (find (lambda (descriptor)
                 (string=? (gnu-package-name descriptor)
                           (package-name package)))
               (official-gnu-packages*))
    (#f                                   ;not a GNU package, so nothing to do
     #t)
    (descriptor                                   ;a genuine GNU package
     (let ((upstream   (gnu-package-doc-summary descriptor))
           (downstream (package-synopsis package))
           (loc        (or (package-field-location package 'synopsis)
                           (package-location package))))
       (when (and upstream
                  (or (not (string? downstream))
                      (not (string=? upstream downstream))))
         (format (guix-warning-port)
                 (_ "~a: ~a: proposed synopsis: ~s~%")
                 (location->string loc) (package-full-name package)
                 upstream)))

     (let ((upstream   (gnu-package-doc-description descriptor))
           (downstream (package-description package))
           (loc        (or (package-field-location package 'description)
                           (package-location package))))
       (when (and upstream
                  (or (not (string? downstream))
                      (not (string=? (fill-paragraph upstream 100)
                                     (fill-paragraph downstream 100)))))
         (format (guix-warning-port)
                 (_ "~a: ~a: proposed description:~%     \"~a\"~%")
                 (location->string loc) (package-full-name package)
                 (fill-paragraph (escape-quotes upstream) 77 7)))))))

(define (origin-uris origin)
  "Return the list of URIs (strings) for ORIGIN."
  (match (origin-uri origin)
    ((? string? uri)
     (list uri))
    ((uris ...)
     uris)))

(define (check-source package)
  "Emit a warning if PACKAGE has an invalid 'source' field, or if that
'source' is not reachable."
  (define (try-uris uris)
    (run-with-state
        (anym %state-monad
              (lambda (uri)
                (with-accumulated-warnings
                 (validate-uri uri package 'source)))
              (append-map (cut maybe-expand-mirrors <> %mirrors)
                          uris))
      '()))

  (let ((origin (package-source package)))
    (when (and origin
               (eqv? (origin-method origin) url-fetch))
      (let ((uris (map string->uri (origin-uris origin))))

        ;; Just make sure that at least one of the URIs is valid.
        (call-with-values
            (lambda () (try-uris uris))
          (lambda (success? warnings)
            ;; When everything fails, report all of WARNINGS, otherwise don't
            ;; report anything.
            ;;
            ;; XXX: Ideally we'd still allow warnings to be raised if *some*
            ;; URIs are unreachable, but distinguish that from the error case
            ;; where *all* the URIs are unreachable.
            (unless success?
              (emit-warning package
                            (_ "all the source URIs are unreachable:")
                            'source)
              (for-each (lambda (warning)
                          (display warning (guix-warning-port)))
                        (reverse warnings)))))))))

(define (check-source-file-name package)
  "Emit a warning if PACKAGE's origin has no meaningful file name."
  (define (origin-file-name-valid? origin)
    ;; Return #t if the source file name contains only a version or is #f;
    ;; indicates that the origin needs a 'file-name' field.
    (let ((file-name (origin-actual-file-name origin))
          (version (package-version package)))
      (and file-name
           (not (or (string-prefix? version file-name)
                    ;; Common in many projects is for the filename to start
                    ;; with a "v" followed by the version,
                    ;; e.g. "v3.2.0.tar.gz".
                    (string-prefix? (string-append "v" version) file-name))))))

  (let ((origin (package-source package)))
    (unless (or (not origin) (origin-file-name-valid? origin))
      (emit-warning package
                    (_ "the source file name should contain the package name")
                    'source))))

(define (check-mirror-url package)
  "Check whether PACKAGE uses source URLs that should be 'mirror://'."
  (define (check-mirror-uri uri)                  ;XXX: could be optimized
    (let loop ((mirrors %mirrors))
      (match mirrors
        (()
         #t)
        (((mirror-id mirror-urls ...) rest ...)
         (match (find (cut string-prefix? <> uri) mirror-urls)
           (#f
            (loop rest))
           (prefix
            (emit-warning package
                          (format #f (_ "URL should be \
'mirror://~a/~a'")
                                  mirror-id
                                  (string-drop uri (string-length prefix)))
                          'source)))))))

  (let ((origin (package-source package)))
    (when (and (origin? origin)
               (eqv? (origin-method origin) url-fetch))
      (let ((uris (origin-uris origin)))
        (for-each check-mirror-uri uris)))))

(define (check-derivation package)
  "Emit a warning if we fail to compile PACKAGE to a derivation."
  (catch #t
    (lambda ()
      (guard (c ((nix-protocol-error? c)
                 (emit-warning package
                               (format #f (_ "failed to create derivation: ~a")
                                       (nix-protocol-error-message c))))
                ((message-condition? c)
                 (emit-warning package
                               (format #f (_ "failed to create derivation: ~a")
                                       (condition-message c)))))
        (with-store store
          ;; Disable grafts since it can entail rebuilds.
          (package-derivation store package #:graft? #f)

          ;; If there's a replacement, make sure we can compute its
          ;; derivation.
          (match (package-replacement package)
            (#f #t)
            (replacement
             (package-derivation store replacement #:graft? #f))))))
    (lambda args
      (emit-warning package
                    (format #f (_ "failed to create derivation: ~s~%")
                            args)))))

(define (check-license package)
  "Warn about type errors of the 'license' field of PACKAGE."
  (match (package-license package)
    ((or (? license?)
         ((? license?) ...))
     #t)
    (x
     (emit-warning package (_ "invalid license field")
                   'license))))

(define (patch-file-name patch)
  "Return the basename of PATCH's file name, or #f if the file name could not
be determined."
  (match patch
    ((? string?)
     (basename patch))
    ((? origin?)
     (and=> (origin-actual-file-name patch) basename))))

(define (current-vulnerabilities*)
  "Like 'current-vulnerabilities', but return the empty list upon networking
or HTTP errors.  This allows network-less operation and makes problems with
the NIST server non-fatal.."
  (guard (c ((http-get-error? c)
             (warning (_ "failed to retrieve CVE vulnerabilities \
from ~s: ~a (~s)~%")
                      (uri->string (http-get-error-uri c))
                      (http-get-error-code c)
                      (http-get-error-reason c))
             (warning (_ "assuming no CVE vulnerabilities~%"))
             '()))
    (catch #t
      (lambda ()
        (current-vulnerabilities))
      (match-lambda*
        (('getaddrinfo-error errcode)
         (warning (_ "failed to lookup NIST host: ~a~%")
                  (gai-strerror errcode))
         (warning (_ "assuming no CVE vulnerabilities~%"))
         '())
        (('tls-certificate-error args ...)
         (warning (_ "TLS certificate error: ~a")
                  (tls-certificate-error-string args))
         (warning (_ "assuming no CVE vulnerabilities~%"))
         '())
        (args
         (apply throw args))))))

(define package-vulnerabilities
  (let ((lookup (delay (vulnerabilities->lookup-proc
                        (current-vulnerabilities*)))))
    (lambda (package)
      "Return a list of vulnerabilities affecting PACKAGE."
      ;; First we retrieve the Common Platform Enumeration (CPE) name and
      ;; version for PACKAGE, then we can pass them to LOOKUP.
      (let ((name    (or (assoc-ref (package-properties package)
                                    'cpe-name)
                         (package-name package)))
            (version (or (assoc-ref (package-properties package)
                                    'cpe-version)
                         (package-version package))))
        ((force lookup) name version)))))

(define (check-vulnerabilities package)
  "Check for known vulnerabilities for PACKAGE."
  (let ((package (or (package-replacement package) package)))
    (match (package-vulnerabilities package)
      (()
       #t)
      ((vulnerabilities ...)
       (let* ((patches   (filter-map patch-file-name
                                     (or (and=> (package-source package)
                                                origin-patches)
                                         '())))
              (unpatched (remove (lambda (vuln)
                                   (find (cute string-contains
                                           <> (vulnerability-id vuln))
                                         patches))
                                 vulnerabilities)))
         (unless (null? unpatched)
           (emit-warning package
                         (format #f (_ "probably vulnerable to ~a")
                                 (string-join (map vulnerability-id unpatched)
                                              ", ")))))))))


;;;
;;; Source code formatting.
;;;

(define (report-tabulations package line line-number)
  "Warn about tabulations found in LINE."
  (match (string-index line #\tab)
    (#f #t)
    (index
     (emit-warning package
                   (format #f (_ "tabulation on line ~a, column ~a")
                           line-number index)))))

(define (report-trailing-white-space package line line-number)
  "Warn about trailing white space in LINE."
  (unless (or (string=? line (string-trim-right line))
              (string=? line (string #\page)))
    (emit-warning package
                  (format #f
                          (_ "trailing white space on line ~a")
                          line-number))))

(define (report-long-line package line line-number)
  "Emit a warning if LINE is too long."
  ;; Note: We don't warn at 80 characters because sometimes hashes and URLs
  ;; make it hard to fit within that limit and we want to avoid making too
  ;; much noise.
  (when (> (string-length line) 90)
    (emit-warning package
                  (format #f (_ "line ~a is way too long (~a characters)")
                          line-number (string-length line)))))

(define %hanging-paren-rx
  (make-regexp "^[[:blank:]]*[()]+[[:blank:]]*$"))

(define (report-lone-parentheses package line line-number)
  "Emit a warning if LINE contains hanging parentheses."
  (when (regexp-exec %hanging-paren-rx line)
    (emit-warning package
                  (format #f
                          (_ "line ~a: parentheses feel lonely, \
move to the previous or next line")
                          line-number))))

(define %formatting-reporters
  ;; List of procedures that report formatting issues.  These are not separate
  ;; checkers because they would need to re-read the file.
  (list report-tabulations
        report-trailing-white-space
        report-long-line
        report-lone-parentheses))

(define* (report-formatting-issues package file starting-line
                                   #:key (reporters %formatting-reporters))
  "Report white-space issues in FILE starting from STARTING-LINE, and report
them for PACKAGE."
  (define last-line
    ;; Number of the presumed last line.
    ;; XXX: Ideally we'd stop at the boundaries of the surrounding sexp, but
    ;; for now just use this simple heuristic.
    (+ starting-line 60))

  (call-with-input-file file
    (lambda (port)
      (let loop ((line-number 1))
        (let ((line (read-line port)))
          (or (eof-object? line)
              (> line-number last-line)
              (begin
                (unless (< line-number starting-line)
                  (for-each (lambda (report)
                              (report package line line-number))
                            reporters))
                (loop (+ 1 line-number)))))))))

(define (check-formatting package)
  "Check the formatting of the source code of PACKAGE."
  (let ((location (package-location package)))
    (when location
      (and=> (search-path %load-path (location-file location))
             (lambda (file)
               ;; Report issues starting from the line before the 'package'
               ;; form, which usually contains the 'define' form.
               (report-formatting-issues package file
                                         (- (location-line location) 1)))))))


;;;
;;; List of checkers.
;;;

(define %checkers
  (list
   (lint-checker
     (name        'description)
     (description "Validate package descriptions")
     (check       check-description-style))
   (lint-checker
     (name        'gnu-description)
     (description "Validate synopsis & description of GNU packages")
     (check       check-gnu-synopsis+description))
   (lint-checker
     (name        'inputs-should-be-native)
     (description "Identify inputs that should be native inputs")
     (check       check-inputs-should-be-native))
   (lint-checker
     (name        'inputs-should-not-be-input)
     (description "Identify inputs that should be inputs at all")
     (check       check-inputs-should-not-be-an-input-at-all))
   (lint-checker
     (name        'patch-file-names)
     (description "Validate file names and availability of patches")
     (check       check-patch-file-names))
   (lint-checker
     (name        'home-page)
     (description "Validate home-page URLs")
     (check       check-home-page))
   (lint-checker
     (name        'license)
     ;; TRANSLATORS: <license> is the name of a data type and must not be
     ;; translated.
     (description "Make sure the 'license' field is a <license> \
or a list thereof")
     (check       check-license))
   (lint-checker
     (name        'source)
     (description "Validate source URLs")
     (check       check-source))
   (lint-checker
     (name        'mirror-url)
     (description "Suggest 'mirror://' URLs")
     (check       check-mirror-url))
   (lint-checker
     (name        'source-file-name)
     (description "Validate file names of sources")
     (check       check-source-file-name))
   (lint-checker
     (name        'derivation)
     (description "Report failure to compile a package to a derivation")
     (check       check-derivation))
   (lint-checker
     (name        'synopsis)
     (description "Validate package synopses")
     (check       check-synopsis-style))
   (lint-checker
     (name        'cve)
     (description "Check the Common Vulnerabilities and Exposures\
 (CVE) database")
     (check       check-vulnerabilities))
   (lint-checker
     (name        'formatting)
     (description "Look for formatting issues in the source")
     (check       check-formatting))))

(define* (run-checkers package #:optional (checkers %checkers))
  "Run the given CHECKERS on PACKAGE."
  (let ((tty? (isatty? (current-error-port)))
        (name (package-full-name package)))
    (for-each (lambda (checker)
                (when tty?
                  (format (current-error-port) "checking ~a [~a]...\x1b[K\r"
                          name (lint-checker-name checker))
                  (force-output (current-error-port)))
                ((lint-checker-check checker) package))
              checkers)
    (when tty?
      (format (current-error-port) "\x1b[K")
      (force-output (current-error-port)))))


;;;
;;; Command-line options.
;;;

(define %default-options
  ;; Alist of default option values.
  '())

(define (show-help)
  (display (_ "Usage: guix lint [OPTION]... [PACKAGE]...
Run a set of checkers on the specified package; if none is specified,
run the checkers on all packages.\n"))
  (display (_ "
  -c, --checkers=CHECKER1,CHECKER2...
                         only run the specified checkers"))
  (display (_ "
  -h, --help             display this help and exit"))
  (display (_ "
  -l, --list-checkers    display the list of available lint checkers"))
  (display (_ "
  -V, --version          display version information and exit"))
  (newline)
  (show-bug-report-information))


(define %options
  ;; Specification of the command-line options.
  ;; TODO: add some options:
  ;; * --certainty=[low,medium,high]: only run checkers that have at least this
  ;;                                  'certainty'.
  (list (option '(#\c "checkers") #t #f
                (lambda (opt name arg result)
                  (let ((names (map string->symbol (string-split arg #\,))))
                    (for-each (lambda (c)
                                (unless (memq c
                                              (map lint-checker-name
                                                   %checkers))
                                  (leave (_ "~a: invalid checker~%") c)))
                              names)
                    (alist-cons 'checkers
                                (filter (lambda (checker)
                                          (member (lint-checker-name checker)
                                                  names))
                                        %checkers)
                                result))))
        (option '(#\h "help") #f #f
                (lambda args
                  (show-help)
                  (exit 0)))
        (option '(#\l "list-checkers") #f #f
                (lambda args
                   (list-checkers-and-exit)))
        (option '(#\V "version") #f #f
                (lambda args
                  (show-version-and-exit "guix lint")))))


;;;
;;; Entry Point
;;;

(define (guix-lint . args)
  (define (parse-options)
    ;; Return the alist of option values.
    (args-fold* args %options
                (lambda (opt name arg result)
                  (leave (_ "~A: unrecognized option~%") name))
                (lambda (arg result)
                  (alist-cons 'argument arg result))
                %default-options))

  (let* ((opts (parse-options))
         (args (filter-map (match-lambda
                            (('argument . value)
                             value)
                            (_ #f))
                           (reverse opts)))
         (checkers (or (assoc-ref opts 'checkers) %checkers)))
     (if (null? args)
          (fold-packages (lambda (p r) (run-checkers p checkers)) '())
          (for-each (lambda (spec)
                      (run-checkers (specification->package spec) checkers))
                    args))))