02e755470dc5a96f76db66e01f52034136b00a08
[scratchy.git] / examples / browse-git.scm
1 ;; Script to browse locally-hosted URLs
2
3 (lambda (type-str repo branch path)
4   (import (chicken string)
5           (chicken process)
6           (chicken io)
7           (chicken pathname)
8           srfi-13)
9
10   (define git-base-url "git://MY.GIT.SERVER/")
11   (define git-base-dir "/PATH/TO/REPOS/")
12
13   (define (git . args)
14     (with-current-working-directory
15      (list git-base-dir repo)
16      (lambda ()
17        (let-values (((in-port out-port id) (process "git" args)))
18          (let ((result (read-lines in-port)))
19            (close-input-port in-port)
20            (close-output-port out-port)
21            result)))))
22
23   (define (serve-tree)
24     (let ((entries (git "ls-tree" branch path))
25           (references (git "show-ref" "--heads")))
26       (append
27        (list
28         (conc "Git repository " repo)
29         ""
30         (conc "(Clone from " git-base-url repo ".)")
31         ""
32         "-----= Branches =-----")
33        (map (lambda (ref)
34               (let ((refname (caddr (string-split ref "/"))))
35                 (list
36                  1
37                  (conc (if (equal? branch refname) "*" "")
38                        refname)
39                  (conc "browse-git.scm|tree|" repo "|" refname "|" path))))
40             references)
41        (list ""
42              (conc "-----= Files [" path "] =-----"))
43        (map (lambda (entry)
44               (let* ((l (string-split entry "\t"))
45                      (type (string->symbol (cadr (string-split (car l) " "))))
46                      (file-path (cadr l))
47                      (file (conc (pathname-file file-path)
48                                  (if (pathname-extension file-path)
49                                      (conc "." (pathname-extension file-path))
50                                      ""))))
51                 (list (if (eq? type 'tree) 1 0)
52                       file
53                       (conc "browse-git.scm|" type "|" repo "|" branch "|"
54                             file-path
55                             (if (eq? type 'tree) "/" "")))))
56             entries))))
57
58   (define (serve-blob)
59     (for-each
60      (lambda (line)
61        (print line "\r"))
62      (git "cat-file" "blob" (conc branch "|" path)))
63     (print ".\r"))
64
65   (let ((type (string->symbol type-str)))
66     (case type
67       ((tree) (serve-tree))
68       ((blob) (serve-blob))
69       (else
70        (error "Unsupported git object.")))))
71