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
|
package main
import (
"archive/tar"
"bytes"
"database/sql"
"errors"
"flag"
"fmt"
"io"
"mime"
"net/http"
"os"
"os/exec"
"path"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
)
// ingestOptions carries the parameters of a single ingest, shared by the
// `ingest` subcommand and the post-receive hook.
type ingestOptions struct {
dbPath string // SQLite database path (required)
project string // project name the tree is stored under (required)
branch string // branch being ingested; recorded on the project row
gitDir string // source repo; if set, a clonable bundle + mtimes are built
}
// runIngest reads a `git archive` tar stream from stdin and stores the tree as
// a new generation of the given project, then makes it the live tree.
func runIngest(args []string) error {
fs := flag.NewFlagSet("ingest", flag.ContinueOnError)
dbPath := fs.String("db", "", "path to the SQLite database (required)")
project := fs.String("project", "", "project name (required)")
branch := fs.String("branch", "", "branch that was archived (recorded on the project)")
gitDir := fs.String("git-dir", "", "path to the source git repo; if set, a clonable git bundle of --branch is built and stored")
if err := fs.Parse(args); err != nil {
return err
}
if *dbPath == "" || *project == "" {
return errors.New("--db and --project are required")
}
if *gitDir != "" && *branch == "" {
return errors.New("--branch is required when --git-dir is given (it selects what to bundle)")
}
return ingestTar(os.Stdin, ingestOptions{
dbPath: *dbPath,
project: *project,
branch: *branch,
gitDir: *gitDir,
})
}
// ingestTar reads a `git archive` tar stream from r and stores the tree as a
// new generation of opts.project, then atomically makes it the live tree. It is
// the reusable core behind both the `ingest` subcommand (r = stdin) and the
// post-receive hook (r = the stdout of a `git archive` it spawns).
func ingestTar(r io.Reader, opts ingestOptions) error {
db, err := openDB(opts.dbPath)
if err != nil {
return err
}
defer db.Close()
// Everything that shells out to git happens BEFORE the write transaction is
// opened, because SQLite allows only one writer at a time: any lock we hold
// here blocks the serving process (a separate process, so busy_timeout is
// the only thing making it wait) for as long as we hold it. Packing the
// full history into a bundle and gzipping the whole tree take seconds —
// long enough to exhaust any sane timeout and make the server's
// render-cache writes fail. Doing them up front keeps the lock window down
// to the row inserts themselves.
//
// The bytes are necessarily buffered in memory rather than streamed into
// the row: SQLite's incremental blob API can only overwrite a blob of a
// size fixed at insert time (zeroblob(N)), which we cannot know without
// producing the whole artifact first, and it requires a separate connection
// — so the write would fall outside this transaction and break the
// atomic-generation guarantee below.
//
// While we do this we are not yet draining r; when the caller is the
// post-receive hook, r is a pipe from a concurrent `git archive`, which
// simply blocks on a full pipe buffer until we start reading. That
// serializes the work but cannot deadlock.
var mtimes map[string]int64 // per-file last-change times from git history
var bundleData, tarData []byte
var tarModified int64
if opts.gitDir != "" {
mtimes, err = gitFileMtimes(opts.gitDir, opts.branch)
if err != nil {
return err
}
bundleData, err = gitBundle(opts.gitDir, opts.branch)
if err != nil {
return err
}
tarData, tarModified, err = gitArchiveTarball(opts.gitDir, opts.project, opts.branch)
if err != nil {
return err
}
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback()
// Pick the next generation for this project (max existing + 1), so the
// live tree is never disturbed until we flip head_generation at the end.
gen, err := nextGeneration(tx, opts.project)
if err != nil {
return err
}
dirs := map[string]bool{} // directory paths we've already inserted
// Recursive per-directory aggregates, keyed by directory path. Every file
// and subdirectory bumps the counters of all of its ancestor directories;
// these are flushed to the file rows after the tar loop.
st := &subtreeStats{
files: map[string]int64{},
dirs: map[string]int64{},
size: map[string]int64{},
codeSize: map[string]int64{},
mtime: map[string]int64{},
}
// Children of every directory, used after the tar loop to resolve which
// directories collapse into their single child (see resolveCollapse) and
// to build the stored listings.
tree := newTreeIndex()
// Per-directory ".source-forge" directives, keyed by directory path (see
// meta.go). Collected during the tar loop — the file's bytes pass through
// here anyway — and applied to the listings once the whole tree is known.
metas := map[string]*dirMeta{}
tr := tar.NewReader(r)
var fileCount int
for {
hdr, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("read tar: %w", err)
}
// git archive prefixes entries with the tree-ish by default only when
// --prefix is given; normalize either way by trimming a leading "./".
name := strings.TrimPrefix(hdr.Name, "./")
name = strings.TrimRight(name, "/")
if name == "" {
continue
}
switch hdr.Typeflag {
case tar.TypeDir:
if err := insertDir(tx, opts.project, gen, name, dirs); err != nil {
return err
}
st.addDir(name)
tree.add(name, true)
case tar.TypeReg, tar.TypeRegA:
// Ensure every ancestor directory row exists, even if the tar
// stream omitted explicit dir entries.
if err := ensureAncestors(tx, opts.project, gen, name, dirs); err != nil {
return err
}
content, err := io.ReadAll(tr)
if err != nil {
return fmt.Errorf("read %q: %w", name, err)
}
// Last-change time: the git-history walk when available, else the
// archived commit's time that git stamps on every tar entry.
mtime := mtimes[name]
if mtime == 0 {
mtime = hdr.ModTime.Unix()
}
// Classify once here and thread the result through, so both the
// row insert and the subtree aggregates share a single scan.
binary := isBinary(content)
if err := insertFile(tx, opts.project, gen, name, content, binary, mtime); err != nil {
return err
}
st.addFile(name, int64(len(content)), mtime, binary)
tree.add(name, false)
fileCount++
// A directory's own metadata file. It is stored as an ordinary
// file row above (it stays browseable like anything else); this
// only additionally parses it for the listing/description below.
if path.Base(name) == metaFileName {
dir := path.Dir(name)
if dir == "." {
dir = ""
}
metas[dir] = parseDirMeta(dir, content)
}
default:
// Skip symlinks, hardlinks, devices, etc. — not meaningful here.
}
}
// Flush the recursive directory aggregates onto the directory rows.
root, err := st.flush(tx, opts.project, gen)
if err != nil {
return err
}
// Compute and store the directory listings: collapse chains, plus any
// `shortcut` entries the directories declared.
if err := buildListing(tx, opts.project, gen, tree, metas); err != nil {
return err
}
// Store the clonable git bundle and the Nix-flake tarball built above. Both
// come from the same repo read as the tree, and are written under the same
// generation, so they always match the tree that goes live.
var bundleSize, tarballSize int
if opts.gitDir != "" {
if err := insertBundle(tx, opts.project, gen, bundleData); err != nil {
return err
}
bundleSize = len(bundleData)
if err := insertTarball(tx, opts.project, gen, tarData, tarModified); err != nil {
return err
}
tarballSize = len(tarData)
}
// Store the descriptions declared by .source-forge files: one per
// directory, plus the root's, which describes the project as a whole.
if err := storeDescriptions(tx, opts.project, gen, metas); err != nil {
return err
}
if err := commitGeneration(tx, opts.project, opts.branch, gen, root); err != nil {
return err
}
if err := gcOldGenerations(tx, opts.project, gen); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit: %w", err)
}
if bundleSize > 0 {
fmt.Fprintf(os.Stderr, "source-forge: ingested %d files into %q generation %d (bundle %d bytes, tarball %d bytes)\n",
fileCount, opts.project, gen, bundleSize, tarballSize)
} else {
fmt.Fprintf(os.Stderr, "source-forge: ingested %d files into %q generation %d\n",
fileCount, opts.project, gen)
}
return nil
}
// gitArchiveTarball produces a gzipped tarball of <branch> suitable for use as
// a Nix flake, and the branch-tip commit time.
//
// It runs `git archive --format=tar.gz --prefix=<project>/ <branch>`, which
// already emits exactly what Nix's tarball input scheme needs: a single
// top-level "<project>/" directory wrapping the whole tree (Nix rejects
// archives that do not have exactly one top-level entry) with every entry —
// including that wrapper directory — stamped with the commit time (Nix reads
// the wrapper's mtime as the flake's `lastModified`, since tarball flakes have
// no rev). Letting git build and compress it avoids re-taring the tree in Go.
//
// The returned modified time (committer time of the branch tip) is stored
// alongside the blob so the HTTP handler can send a matching Last-Modified.
func gitArchiveTarball(gitDir, project, branch string) (data []byte, modified int64, err error) {
cmd := exec.Command("git", "--git-dir="+gitDir, "archive",
"--format=tar.gz", "--prefix="+project+"/", branch)
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
return nil, 0, fmt.Errorf("git archive (%s %s): %w: %s", gitDir, branch, err, errBuf.String())
}
modified, err = gitCommitTime(gitDir, branch)
if err != nil {
return nil, 0, err
}
return out.Bytes(), modified, nil
}
// gitCommitTime returns the committer time (Unix seconds) of the tip of branch.
func gitCommitTime(gitDir, branch string) (int64, error) {
cmd := exec.Command("git", "--git-dir="+gitDir, "log", "-1", "--format=format:%ct", branch)
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
return 0, fmt.Errorf("git log -1 (%s %s): %w: %s", gitDir, branch, err, errBuf.String())
}
ts, err := strconv.ParseInt(strings.TrimSpace(out.String()), 10, 64)
if err != nil {
return 0, fmt.Errorf("parse commit time %q: %w", out.String(), err)
}
return ts, nil
}
// insertTarball stores a gzipped flake tarball for a project generation.
func insertTarball(tx *sql.Tx, project string, gen int64, data []byte, modified int64) error {
_, err := tx.Exec(
`INSERT OR REPLACE INTO tarball (project, generation, created, size, modified, data)
VALUES (?, ?, ?, ?, ?, ?)`,
project, gen, time.Now().Unix(), len(data), modified, data,
)
if err != nil {
return fmt.Errorf("insert tarball: %w", err)
}
return nil
}
// gitFileMtimes walks the history of <branch> and returns, per tree path, the
// commit time (Unix seconds) of the most recent commit that touched it. It runs
// a single `git log --name-only` over the branch: output is newest-first, so
// the first time a path is seen is its last-change time.
//
// A NUL sentinel prefixes each commit's timestamp line (paths can never contain
// NUL), which unambiguously separates the timestamp lines from the file-name
// lines regardless of odd characters in paths. Renames are not followed
// (--no-renames): we only care about the path as it exists in the live tree.
func gitFileMtimes(gitDir, branch string) (map[string]int64, error) {
cmd := exec.Command("git", "--git-dir="+gitDir, "log",
"--format=format:%x00%ct", "--name-only", "--no-renames", branch)
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("git log (%s %s): %w: %s", gitDir, branch, err, errBuf.String())
}
mtimes := map[string]int64{}
var cur int64
for _, line := range strings.Split(out.String(), "\n") {
if line == "" {
continue
}
if line[0] == 0 {
// Commit boundary: the rest of the line is the committer Unix time.
ts, err := strconv.ParseInt(line[1:], 10, 64)
if err != nil {
return nil, fmt.Errorf("parse commit time %q: %w", line[1:], err)
}
cur = ts
continue
}
// A file path touched by the current (or a newer, already-recorded)
// commit. First occurrence wins because the log is newest-first.
if _, seen := mtimes[line]; !seen {
mtimes[line] = cur
}
}
return mtimes, nil
}
// gitBundle runs `git bundle create - <branch> HEAD` against the given repo and
// returns the bundle bytes. HEAD is included so a fresh `git clone` of the
// bundle checks out the branch instead of warning about a missing HEAD ref.
func gitBundle(gitDir, branch string) ([]byte, error) {
cmd := exec.Command("git", "--git-dir="+gitDir, "bundle", "create", "-", branch, "HEAD")
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("git bundle create (%s %s): %w: %s", gitDir, branch, err, errBuf.String())
}
return out.Bytes(), nil
}
// insertBundle stores a git bundle for a project generation.
func insertBundle(tx *sql.Tx, project string, gen int64, data []byte) error {
_, err := tx.Exec(
`INSERT OR REPLACE INTO bundle (project, generation, created, size, data)
VALUES (?, ?, ?, ?, ?)`,
project, gen, time.Now().Unix(), len(data), data,
)
if err != nil {
return fmt.Errorf("insert bundle: %w", err)
}
return nil
}
// subtreeStats accumulates recursive per-directory aggregates during ingest.
type subtreeStats struct {
files map[string]int64 // recursive file count per directory
dirs map[string]int64 // recursive subdirectory count per directory
size map[string]int64 // recursive total file size per directory
codeSize map[string]int64 // recursive non-binary (code) file size per directory
mtime map[string]int64 // newest descendant mtime per directory
}
// treeIndex records the shape of the ingested tree — which entries live in
// which directory — so the collapse chains can be resolved in memory once the
// whole tree is known, rather than by walking the database a level at a time
// per listing entry at request time.
type treeIndex struct {
children map[string][]string // directory path -> its entries' full paths
isDir map[string]bool // entry path -> whether it is a directory
present map[string]bool // every entry path seen, file or directory
}
func newTreeIndex() *treeIndex {
return &treeIndex{
children: map[string][]string{},
isDir: map[string]bool{},
present: map[string]bool{},
}
}
// add records one entry (file or directory) under its parent directory.
func (t *treeIndex) add(p string, isDir bool) {
if t.isDir[p] {
return // already recorded (dirs can be seen more than once)
}
parent := path.Dir(p)
if parent == "." {
parent = ""
}
t.children[parent] = append(t.children[parent], p)
if isDir {
t.isDir[p] = true
}
t.present[p] = true
}
// exists reports whether a path is present in the ingested tree, used to
// validate the targets named by .source-forge shortcuts (see meta.go).
func (t *treeIndex) exists(p string) bool { return t.present[p] }
// resolveCollapse computes, for every directory, the path it collapses to:
// while a directory contains exactly one child we descend into that child,
// stopping at the first directory that holds zero or several entries, or at a
// lone file. A directory that does not collapse maps to itself.
//
// Results are memoised, so each directory is resolved once no matter how many
// chains run through it, making this linear in the size of the tree. Unlike the
// query-per-level walk this replaces, there is no depth limit: the limit there
// existed to bound the number of round trips, and a tree cannot contain cycles.
func (t *treeIndex) resolveCollapse() map[string]string {
out := make(map[string]string, len(t.children))
var resolve func(dir string) string
resolve = func(dir string) string {
if got, ok := out[dir]; ok {
return got
}
// Guard against a cycle that cannot occur in a tree but would hang if
// it did: claim the entry before recursing.
out[dir] = dir
kids := t.children[dir]
if len(kids) != 1 {
return dir // a real branch point (or an empty directory)
}
only := kids[0]
target := only
if t.isDir[only] {
target = resolve(only)
}
out[dir] = target
return target
}
for dir := range t.children {
resolve(dir)
}
return out
}
// buildListing computes and stores every directory's listing: the sequence of
// entries shown when that directory is browsed.
//
// An entry is a *target* path — the file row actually displayed — because a
// chain of single-child directories is presented as the one entry it collapses
// to (see resolveCollapse). On top of that, a directory's ".source-forge" may
// declare `shortcut` targets (see meta.go); each valid one is spliced in right
// after the entry it lives under, so a shortcut to "users/Profpatsch" appears
// directly beneath "users/" rather than at the end of the page.
//
// Shortcuts only ever ADD entries: the base entries are always emitted, so no
// declaration can hide part of the tree. Ordering is "directories first, then
// name", matching byte-wise what the ORDER BY in the old serving query did
// (Go's string < is byte-wise, as is SQLite's default BINARY collation), so a
// tree with no .source-forge lists exactly as it did before.
func buildListing(tx *sql.Tx, project string, gen int64, tree *treeIndex, metas map[string]*dirMeta) error {
for dir, entries := range listingEntries(tree, metas) {
for seq, target := range entries {
if _, err := tx.Exec(
`INSERT INTO listing (project, generation, dir, seq, target)
VALUES (?, ?, ?, ?, ?)`,
project, gen, dir, seq, target,
); err != nil {
return fmt.Errorf("insert listing entry %q in %q: %w", target, dir, err)
}
}
}
return nil
}
// listingEntries computes every directory's entry sequence: the pure core of
// buildListing, which only writes what this decides. See buildListing for the
// rules.
func listingEntries(tree *treeIndex, metas map[string]*dirMeta) map[string][]string {
collapse := tree.resolveCollapse()
out := make(map[string][]string, len(tree.children))
for dir, kids := range tree.children {
// "Directories first, then name" over the children themselves — the
// entries are ordered by what they ARE, not by where they collapse to,
// so collapsing cannot reshuffle a listing.
sorted := append([]string(nil), kids...)
sort.Slice(sorted, func(i, j int) bool {
a, b := sorted[i], sorted[j]
if tree.isDir[a] != tree.isDir[b] {
return tree.isDir[a]
}
return path.Base(a) < path.Base(b)
})
// Shortcuts are attached to the base entry they live under, so they
// land next to it rather than at the end of the listing.
var shortcuts []string
if m := metas[dir]; m != nil {
shortcuts = m.validShortcuts(tree.exists)
}
under := map[string][]string{}
for _, target := range shortcuts {
under[firstSegment(dir, target)] = append(
under[firstSegment(dir, target)], target)
}
var entries []string
emitted := map[string]bool{}
emit := func(target string) {
if emitted[target] {
return
}
entries = append(entries, target)
emitted[target] = true
}
for _, child := range sorted {
target := collapse[child]
if target == "" {
target = child
}
emit(target)
// A shortcut naming exactly what the chain already collapsed to is
// redundant rather than wrong; emit skips such a duplicate.
for _, sc := range under[child] {
emit(sc)
}
}
out[dir] = entries
}
return out
}
// firstSegment returns the child of dir that target lies under, i.e. the base
// listing entry a shortcut attaches to.
func firstSegment(dir, target string) string {
rel := strings.TrimPrefix(target, dir+"/")
if dir == "" {
rel = target
}
if i := strings.Index(rel, "/"); i >= 0 {
rel = rel[:i]
}
return path.Join(dir, rel)
}
// ancestors returns every ancestor directory of a path, from the immediate
// parent up to and including the root directory "".
func ancestors(p string) []string {
var out []string
parent := path.Dir(p)
if parent == "." {
parent = ""
}
for {
out = append(out, parent)
if parent == "" {
break
}
next := path.Dir(parent)
if next == "." {
next = ""
}
parent = next
}
return out
}
// addFile records a file (with its size and last-change time) against all of
// its ancestor dirs. A directory's mtime is the newest mtime among everything
// beneath it. Non-binary files also bump codeSize, the "actual code" total that
// the browseable listings display (binary blobs are counted in size but not
// codeSize).
func (s *subtreeStats) addFile(p string, size, mtime int64, binary bool) {
for _, a := range ancestors(p) {
s.files[a]++
s.size[a] += size
if !binary {
s.codeSize[a] += size
}
if mtime > s.mtime[a] {
s.mtime[a] = mtime
}
}
}
// addDir records a subdirectory against all of its (strict) ancestor dirs.
func (s *subtreeStats) addDir(p string) {
for _, a := range ancestors(p) {
s.dirs[a]++
}
}
// rootStats holds the recursive totals for the whole tree (the "" directory).
type rootStats struct {
files, dirs, size, codeSize, mtime int64
}
// flush writes the accumulated aggregates onto the directory rows, and returns
// the totals for the root directory "" (which has no file row of its own; its
// totals are stored on the project row by commitGeneration instead).
func (s *subtreeStats) flush(tx *sql.Tx, project string, gen int64) (rootStats, error) {
// Collect the union of directory keys across the maps.
seen := map[string]bool{}
for d := range s.files {
seen[d] = true
}
for d := range s.dirs {
seen[d] = true
}
for d := range s.size {
seen[d] = true
}
for d := range s.codeSize {
seen[d] = true
}
for d := range s.mtime {
seen[d] = true
}
for d := range seen {
if d == "" {
continue // root: reported via return value, stored on project row
}
if _, err := tx.Exec(
`UPDATE file
SET subtree_files = ?, subtree_dirs = ?, subtree_size = ?,
subtree_code_size = ?, mtime = ?
WHERE project = ? AND path = ? AND generation = ?`,
s.files[d], s.dirs[d], s.size[d], s.codeSize[d], s.mtime[d],
project, d, gen,
); err != nil {
return rootStats{}, fmt.Errorf("update subtree stats for %q: %w", d, err)
}
}
return rootStats{
files: s.files[""], dirs: s.dirs[""], size: s.size[""],
codeSize: s.codeSize[""], mtime: s.mtime[""],
}, nil
}
// nextGeneration returns max(existing generation for project) + 1.
func nextGeneration(tx *sql.Tx, project string) (int64, error) {
var gen sql.NullInt64
err := tx.QueryRow(
`SELECT MAX(generation) FROM file WHERE project = ?`, project,
).Scan(&gen)
if err != nil {
return 0, fmt.Errorf("query max generation: %w", err)
}
if gen.Valid {
return gen.Int64 + 1, nil
}
return 1, nil
}
// insertDir inserts a directory row (idempotent within this ingest).
func insertDir(tx *sql.Tx, project string, gen int64, dir string, seen map[string]bool) error {
if seen[dir] {
return nil
}
// Make sure the parent chain exists first.
parent := path.Dir(dir)
if parent == "." {
parent = ""
}
if parent != "" && !seen[parent] {
if err := insertDir(tx, project, gen, parent, seen); err != nil {
return err
}
}
_, err := tx.Exec(
`INSERT OR REPLACE INTO file
(project, path, parent, name, generation, is_dir, is_binary, mime_type, size, content)
VALUES (?, ?, ?, ?, ?, 1, 0, 'inode/directory', 0, NULL)`,
project, dir, parent, path.Base(dir), gen,
)
if err != nil {
return fmt.Errorf("insert dir %q: %w", dir, err)
}
seen[dir] = true
return nil
}
// ensureAncestors inserts directory rows for every ancestor of file path p.
func ensureAncestors(tx *sql.Tx, project string, gen int64, p string, seen map[string]bool) error {
parent := path.Dir(p)
if parent == "." || parent == "" {
return nil
}
return insertDir(tx, project, gen, parent, seen)
}
// insertFile stores a single regular file. binary is the caller's
// classification (isBinary), reused to avoid a second content scan. mtime is
// the file's last-change time (Unix seconds) from git history, 0 if unknown.
func insertFile(tx *sql.Tx, project string, gen int64, p string, content []byte, binary bool, mtime int64) error {
parent := path.Dir(p)
if parent == "." {
parent = ""
}
mimeType := detectMIME(p, content, binary)
_, err := tx.Exec(
`INSERT OR REPLACE INTO file
(project, path, parent, name, generation, is_dir, is_binary, mime_type, size, content, mtime)
VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)`,
project, p, parent, path.Base(p), gen,
boolToInt(binary), mimeType, len(content), content, mtime,
)
if err != nil {
return fmt.Errorf("insert file %q: %w", p, err)
}
return nil
}
// storeDescriptions stores every `description` declared by a .source-forge
// where the serving side reads it: on the directory's own file row, except for
// the root's, which goes on the project row.
//
// The split mirrors what the two describe. A directory's blurb is shown on its
// entry in every listing it appears in, and above its own listing; the root has
// no parent listing to appear in, so its blurb describes the project instead —
// on the project page and the site index.
//
// The tree is authoritative: the project's description is written on every
// ingest, and *cleared* when the root declares none, so deleting the line and
// pushing removes it. This is the only way to set it — the `set-description`
// subcommand that once did so by hand is gone (see runProject) — which is
// what lets the write be unconditional. Directory descriptions need no such
// care: their rows are written fresh for each generation, so one that is no
// longer declared simply never gets set.
//
// The declared value is inline HTML (see meta.go), which is what a listing
// entry needs, so nothing is rendered here; only the project's is wrapped into
// a block, since it is shown in block positions.
//
// Both columns are emitted UNESCAPED (see their comments in schema.go): the
// trust boundary is that whoever can push to the published branch already
// controls every byte the site serves.
func storeDescriptions(tx *sql.Tx, project string, gen int64, metas map[string]*dirMeta) error {
// The project's blurb, from the root file. Written unconditionally — the
// empty string when undeclared — so the tree stays authoritative.
//
// The project row may not exist yet when a tree is ingested by hand with
// the `ingest` subcommand (commitGeneration creates it just after), so a
// no-op UPDATE is not an error here; the push path always has a row, since
// the hook refuses to ingest into an undeclared project.
projectDesc := ""
if m := metas[""]; m != nil && m.description != "" {
projectDesc = "<p>" + m.description + "</p>"
}
if _, err := tx.Exec(
`UPDATE project SET description = ? WHERE name = ?`, projectDesc, project,
); err != nil {
return fmt.Errorf("update project description: %w", err)
}
for dir, m := range metas {
if dir == "" || m.description == "" {
continue // the root's is handled above
}
file := path.Join(dir, metaFileName)
// Stored verbatim: it is emitted on the entry's own line, inside the
// listing's <span>, where only phrasing content is valid — see the
// `description` key's comment in meta.go.
res, err := tx.Exec(
`UPDATE file SET description = ?
WHERE project = ? AND path = ? AND generation = ?`,
m.description, project, dir, gen,
)
if err != nil {
return fmt.Errorf("update description of %q: %w", dir, err)
}
// Every directory holding a file has a row by now (ensureAncestors
// creates the whole chain), so this cannot normally miss — but a
// silent no-op would be a confusing way to find out otherwise.
if n, err := res.RowsAffected(); err == nil && n == 0 {
fmt.Fprintf(stderr,
"source-forge: %s: ignoring 'description': no directory row for %q\n",
file, dir)
}
}
return nil
}
// commitGeneration upserts the project row (including the whole-tree root
// stats) and flips head_generation, making the freshly-written tree live.
func commitGeneration(tx *sql.Tx, project, branch string, gen int64, root rootStats) error {
_, err := tx.Exec(
`INSERT INTO project (name, branch, head_generation, root_files, root_dirs, root_size, root_code_size, root_mtime)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
branch = excluded.branch,
head_generation = excluded.head_generation,
root_files = excluded.root_files,
root_dirs = excluded.root_dirs,
root_size = excluded.root_size,
root_code_size = excluded.root_code_size,
root_mtime = excluded.root_mtime`,
project, branch, gen, root.files, root.dirs, root.size, root.codeSize, root.mtime,
)
if err != nil {
return fmt.Errorf("flip head_generation: %w", err)
}
return nil
}
// gcOldGenerations removes file and render_cache rows from superseded
// generations, keeping only the now-live one.
func gcOldGenerations(tx *sql.Tx, project string, keep int64) error {
if _, err := tx.Exec(
`DELETE FROM file WHERE project = ? AND generation <> ?`, project, keep,
); err != nil {
return fmt.Errorf("gc old files: %w", err)
}
if _, err := tx.Exec(
`DELETE FROM render_cache WHERE project = ? AND generation <> ?`, project, keep,
); err != nil {
return fmt.Errorf("gc old cache: %w", err)
}
if _, err := tx.Exec(
`DELETE FROM listing WHERE project = ? AND generation <> ?`, project, keep,
); err != nil {
return fmt.Errorf("gc old listings: %w", err)
}
if _, err := tx.Exec(
`DELETE FROM bundle WHERE project = ? AND generation <> ?`, project, keep,
); err != nil {
return fmt.Errorf("gc old bundles: %w", err)
}
if _, err := tx.Exec(
`DELETE FROM tarball WHERE project = ? AND generation <> ?`, project, keep,
); err != nil {
return fmt.Errorf("gc old tarballs: %w", err)
}
return nil
}
// isBinary reports whether content looks like binary (non-text) data. We treat
// anything containing a NUL byte, or that is not valid UTF-8 in its leading
// sample, as binary.
func isBinary(content []byte) bool {
if len(content) == 0 {
return false
}
sample := content
if len(sample) > 8000 {
sample = sample[:8000]
}
if bytes.IndexByte(sample, 0) >= 0 {
return true
}
if !utf8.Valid(sample) {
return true
}
return false
}
// detectMIME determines a MIME type once, at ingest time. It prefers the file
// extension (which distinguishes e.g. text/css from text/plain), falling back
// to content sniffing for extensionless or unknown files.
func detectMIME(p string, content []byte, binary bool) string {
if ext := strings.ToLower(path.Ext(p)); ext != "" {
if m := mime.TypeByExtension(ext); m != "" {
return m
}
}
if !binary {
return "text/plain; charset=utf-8"
}
sample := content
if len(sample) > 512 {
sample = sample[:512]
}
return http.DetectContentType(sample)
}
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
|