Fix bug in browse-git example.
[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/GIT/REPOS/")
12
13
14   (define (git . args)
15     (let ((repo-pathname (make-pathname git-base-dir repo)))
16       (if (not (string-prefix? git-base-dir (normalize-pathname repo-pathname)))
17           (error "Invalid git repository."))
18       (with-current-working-directory
19        repo-pathname
20        (lambda ()
21          (let-values (((in-port out-port id) (process "git" args)))
22            (let ((result (read-lines in-port)))
23              (close-input-port in-port)
24              (close-output-port out-port)
25              result))))))
26
27   (define (serve-tree)
28     (let ((entries (git "ls-tree" branch path))
29           (references (git "show-ref" "--heads")))
30       (append
31        (list
32         (conc "Git repository " repo)
33         ""
34         (conc "(Clone from " git-base-url repo ".)")
35         ""
36         "-----= Branches =-----")
37        (map (lambda (ref)
38               (let ((refname (caddr (string-split ref "/"))))
39                 (list
40                  1
41                  (conc (if (equal? branch refname) "*" "")
42                        refname)
43                  (conc "browse-git.scm|tree|" repo "|" refname "|" path))))
44             references)
45        (list ""
46              (conc "-----= Files [" path "] =-----"))
47        (map (lambda (entry)
48               (let* ((l (string-split entry "\t"))
49                      (type (string->symbol (cadr (string-split (car l) " "))))
50                      (file-path (cadr l))
51                      (file (conc (pathname-file file-path)
52                                  (if (pathname-extension file-path)
53                                      (conc "." (pathname-extension file-path))
54                                      ""))))
55                 (list (if (eq? type 'tree) 1 0)
56                       file
57                       (conc "browse-git.scm|" type "|" repo "|" branch "|"
58                             file-path
59                             (if (eq? type 'tree) "/" "")))))
60             entries))))
61
62   (define (serve-blob)
63     (for-each
64      (lambda (line)
65        (print line "\r"))
66      (git "cat-file" "blob" (conc branch ":" path)))
67     (print ".\r"))
68
69   (let ((type (string->symbol type-str)))
70     (case type
71       ((tree) (serve-tree))
72       ((blob) (serve-blob))
73       (else
74        (error "Unsupported git object.")))))
75