summaryrefslogtreecommitdiffstatshomepage
path: root/tekuti/git.scm
blob: 355d3b109cbcb51efd1f876ce08217e8b1e9f6c1 (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
;; Tekuti
;; Copyright (C) 2008 Andy Wingo <wingo at pobox dot com>

;; 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, contact:
;;
;; Free Software Foundation           Voice:  +1-617-542-5942
;; 59 Temple Place - Suite 330        Fax:    +1-617-542-2652
;; Boston, MA  02111-1307,  USA       gnu@gnu.org

;;; Commentary:
;;
;; This is the main script that will launch tekuti.
;;
;;; Code:

(define-module (tekuti git)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 popen)
  #:use-module (tekuti util)
  #:use-module (tekuti config)
  #:use-module (scheme kwargs)
  #:use-module (match-bind)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:export (&git-condition git-condition? git-condition-argv
            git-condition-output git-condition-status false-if-git-error

            git git* ensure-git-repo git-ls-tree git-ls-subdirs
            parse-metadata parse-commit commit-utc-timestamp
            commit-parents make-tree git-rev-parse make-tree-full
            create-blob git-update-ref

            write-indices read-indices))

(define-condition-type &git-condition &condition git-condition?
  (argv git-condition-argv)
  (output git-condition-output)
  (status git-condition-status))

(define-macro (false-if-git-error . body)
  `(,guard (c ((,git-condition? c) #f))
           ,@body))

(define (shell:quote str)
  (with-output-to-string
    (lambda ()
      (display #\')
      (for-each (lambda (ch)
		  (if (eqv? ch #\')
                      (begin (display #\\) (display #\'))
                      (display ch)))
		(string->list str))
      (display #\'))))
      
(define *debug* #f)
(define (trc . args)
  (if *debug*
      (apply pk args)
      (car (last-pair args))))

(define (run-git env input-file args)
  (define (prepend-env args)
    (if (null? env)
        args
        (cons "/usr/bin/env" (append env args))))
  (define (prepend-git args)
    (cons* *git* "--bare" args))
  (define (redirect-input args)
    (if input-file
        (list "/bin/sh" "-c"
              (string-append (string-join (map shell:quote args) " ")
                             "<" input-file))
        args))
  (let* ((real-args (trc (redirect-input (prepend-env (prepend-git args)))))
         (pipe (apply open-pipe* OPEN_READ real-args))
         (output (read-delimited "" pipe))
         (ret (close-pipe pipe)))
    (case (status:exit-val ret)
      ((0) (if (eof-object? output) "" output))
      (else (trc 'git-error output ret real-args)
            (raise (condition (&git-condition
                               (argv real-args)
                               (output output)
                               (status ret))))))))

(define (call-with-temp-file contents proc)
  (let* ((template (string-copy "/tmp/tekutiXXXXXX"))
         (tmp (mkstemp! template)))
    (display contents tmp)
    (close tmp)
    (unwind-protect
     (proc template)
     (delete-file template))))

(define/kwargs (git* args (input #f) (env '()))
  ;; foolishness regarding env
  (if input
      (call-with-temp-file
       input
       (lambda (tempname)
         (trc input)
         (run-git env tempname args)))
      (run-git env #f args)))

(define (git . args)
  (git* args))

(define (is-dir? path)
  (catch 'system-error
         (lambda () (eq? (stat:type (stat path)) 'directory))
         (lambda args #f)))

(define (ensure-git-repo)
  (let ((d (expanduser *git-dir*)))
    (if (not (is-dir? d))
        (begin
          (mkdir d)
          (chdir d)
          (git "init"))
        (chdir d))))

(define (git-ls-tree treeish path)
  (or (false-if-git-error
       (match-lines (git "ls-tree" treeish (or path "."))
                    "^(.+) (.+) (.+)\t(.+)$" (_ mode type object name)
                    ;; reversed for assoc
                    (list name object type mode)))
      '()))

(define (git-ls-subdirs treeish path)
  (or (false-if-git-error
       (match-lines (git "ls-tree" treeish (or path "."))
                    "^(.+) tree (.+)\t(.+)$" (_ mode object name)
                    (cons name object)))
      '()))

(define (parse-metadata treeish specs)
  (filter
   identity
   (match-lines (git "show" treeish)
                "^([^: ]+): +(.*)$" (_ k v)
                (let* ((k (string->symbol k))
                       (parse (assq-ref specs k)))
                  (if parse
                      (catch 'parse-error
                             (lambda ()
                               (cons k (parse v)))
                             (lambda args #f))
                      (cons k v))))))

(define (parse-commit commit)
  (let ((text (git "cat-file" "commit" commit)))
    (match-bind
     "\n\n(.*)$" text (_ message)
     (acons
      'message message
      (match-lines (substring text 0 (- (string-length text) (string-length _)))
                   "^([^ ]+) (.*)$" (_ k v)
                   (cons (string->symbol k) v))))))

(define (commit-utc-timestamp commit)
  (match-bind
   "^(.*) ([0-9]+) ([+-][0-9]+)" (assq-ref (parse-commit commit) 'committer)
   (_ who ts tz)
   (let ((ts (string->number ts)) (tz (string->number tz)))
     (- ts (* (+ (* (quotient tz 100) 60) (remainder tz 100)) 60)))))

;; fixme: do to commits what i already did to posts

(define (commit-parents commit)
  (map cdr
       (filter
        (lambda (x) (eq? (car x) 'parent))
        (parse-commit commit))))

(define (make-tree alist)
  (string-trim-both
   (git* '("mktree")
         #:input (string-join
                  (map (lambda (pair)
                         (let ((name (car pair)) (sha (cdr pair)))
                           (format #f "040000 tree ~a\t~a" sha name)))
                       alist)
                  "\n" 'suffix))))

(define (git-rev-parse rev)
  (string-trim-both (git "rev-parse" rev)))

(define (create-blob contents)
  (string-trim-both
   (git* '("hash-object" "-w" "--stdin") #:input contents)))

;; order: name object type mode
(define (make-tree-full alist)
  (string-trim-both
   (git* '("mktree")
         #:input (string-join
                  (map (lambda (l)
                         (apply format #f "~a ~a ~a\t~a"
                                (reverse l)))
                       alist)
                  "\n" 'suffix))))

(define (git-update-ref refname proc count)
  (let* ((ref (git-rev-parse refname))
         (commit (proc ref)))
    (cond
     ((zero? count)
      (error "my god, we looped 5 times" commit))
     ((false-if-git-error
       (git "update-ref" refname commit ref))
      commit)
     (else
      (pk "failed to update the ref, trying again..." refname)
      (git-update-ref (git-rev-parse refname) (1- count))))))

;; fixme: map-pairs

(define (assoc-list-ref alist key n default)
  (let ((l (assoc key alist)))
    (if l (list-ref l n) default)))

(define (write-indices indices oldref specs)
  (let* ((master (assq-ref indices 'master))
         (ts (commit-utc-timestamp master))
         (env (list "GIT_COMMMITTER=tekuti"
                    (format #f "GIT_COMMITTER_DATE=~a +0100" ts)
                    (format #f "GIT_AUTHOR_DATE=~a +0100" ts)))
         (tree (make-tree-full
                (map (lambda (pair)
                       (list (symbol->string (car pair))
                             (create-blob
                              (with-output-to-string
                                (lambda ()
                                  ((assoc-list-ref specs (car pair) 2 write)
                                   (cdr pair)))))
                             "blob" "100644"))
                     indices))))
    (let ((new (string-trim-both
                (git* (cons* "commit-tree" tree
                             (if oldref (list "-p" oldref) '()))
                      #:input "reindex\n" #:env env))))
      (or (false-if-git-error
           (git "update-ref" "refs/heads/index" new (or oldref "")))
          (warn "could not update indexes ref"))
      new)))

(define (read-indices specs)
  (and=> (false-if-git-error (git-rev-parse "refs/heads/index"))
         (lambda (ref)
           (cons ref
                 (map (lambda (dent)
                        (cons (string->symbol (car dent))
                              (with-input-from-string 
                                  (git "show" (cadr dent))
                                (assoc-list-ref specs (string->symbol (car dent)) 3 read))))
                      (git-ls-tree (assq-ref (parse-commit ref) 'tree)
                                    #f))))))