manus-tracker

tracker for scientific manuscripts
git clone git://src.adamsgaard.dk/manus-tracker # fast
git clone https://src.adamsgaard.dk/manus-tracker.git # slow
Log | Files | Refs | README Back to index

commit 2e50ba11b1d52d7b6c8b600f6cc9cf50fd238b7e
parent ae3267c0acb8754ba34d332759d561f10d051132
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date:   Thu, 26 Nov 2026 06:44:07 +0300

feat(scan): detect manuscript layout and inspect git, make, figures, tex and bib

Diffstat:
Ascan/report.go | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascan/scan.go | 309+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascan/scan_test.go | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ascan/tex.go | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 679 insertions(+), 0 deletions(-)

diff --git a/scan/report.go b/scan/report.go @@ -0,0 +1,147 @@ +package scan + +import ( + "fmt" + "os" + "path/filepath" + "slices" + + "manus/bib" +) + +// SharedBib is the common bibliography in the manuscript root. +const SharedBib = "BIBnew.bib" + +// BibFiles resolves the bib files a manuscript uses. A file missing from +// src but present in root (the copied BIBnew.bib) resolves to root. +func BibFiles(root, src string, names []string) []string { + var out []string + for _, n := range names { + p := filepath.Join(src, n) + if filepath.Base(n) == SharedBib || !exists(p) { + if q := filepath.Join(root, filepath.Base(n)); exists(q) { + p = q + } + } + if !slices.Contains(out, p) { + out = append(out, p) + } + } + return out +} + +type BibReport struct { + Files []string + Errors []string + Cited int + Missing []string + Unused []string + NoDOI []string +} + +// CheckBib compares cite keys against the manuscript's bib files. Unused +// entries are reported for manuscript-local files only. +func CheckBib(root, src string, tex TeX) BibReport { + r := BibReport{Files: BibFiles(root, src, tex.Bibs), Cited: len(tex.Cites)} + all := map[string]*bib.Entry{} + local := map[string]bool{} + for _, f := range r.Files { + es, err := bib.ParseFile(f) + if err != nil { + r.Errors = append(r.Errors, fmt.Sprintf("%s: %v", filepath.Base(f), err)) + } + isShared := filepath.Dir(f) == filepath.Clean(root) + for _, e := range es { + if _, ok := all[e.Key]; !ok { + all[e.Key] = e + } + if !isShared { + local[e.Key] = true + } + } + } + cited := map[string]bool{} + for _, k := range tex.Cites { + cited[k] = true + e, ok := all[k] + switch { + case !ok: + r.Missing = append(r.Missing, k) + case e.DOI() == "" && e.Type == "article": + r.NoDOI = append(r.NoDOI, k) + } + } + for k := range local { + if !cited[k] { + r.Unused = append(r.Unused, k) + } + } + slices.Sort(r.Unused) + return r +} + +// Report gathers all previews for one manuscript. +type Report struct { + Git *Git + Targets []string + Figures []Figure + PDF *PDF + TeX TeX + Bib *BibReport + Conflicts []string +} + +// Inspect builds a report; commits limits the git log length. +func Inspect(root, dir, src, main, repo string, commits int) Report { + r := Report{ + Git: GitInfo(repo, commits), + Targets: MakeTargets(src), + Figures: Figures(src), + PDF: PDFStatus(src, main), + Conflicts: Conflicts(dir), + } + if filepath.Ext(main) == ".tex" { + r.TeX = ParseTeX(src, main) + br := CheckBib(root, src, r.TeX) + r.Bib = &br + } + return r +} + +// Flags summarises problems worth attention. +func (r Report) Flags() []string { + var f []string + if r.Git != nil && r.Git.Dirty > 0 { + f = append(f, fmt.Sprintf("dirty:%d", r.Git.Dirty)) + } + if r.Git != nil && r.Git.Ahead > 0 { + f = append(f, fmt.Sprintf("unpushed:%d", r.Git.Ahead)) + } + if r.PDF != nil && r.PDF.Missing { + f = append(f, "no-pdf") + } else if r.PDF != nil && r.PDF.Stale { + f = append(f, "stale-pdf") + } + if r.Bib != nil && len(r.Bib.Missing) > 0 { + f = append(f, fmt.Sprintf("missing-refs:%d", len(r.Bib.Missing))) + } + if len(r.TeX.Todos) > 0 { + f = append(f, fmt.Sprintf("todos:%d", len(r.TeX.Todos))) + } + if len(r.Conflicts) > 0 { + f = append(f, fmt.Sprintf("conflicts:%d", len(r.Conflicts))) + } + return f +} + +// Dirs lists non-hidden subdirectories of root. +func Dirs(root string) []string { + entries, _ := os.ReadDir(root) + var out []string + for _, e := range entries { + if e.IsDir() && e.Name()[0] != '.' { + out = append(out, e.Name()) + } + } + return out +} diff --git a/scan/scan.go b/scan/scan.go @@ -0,0 +1,309 @@ +package scan + +import ( + "bufio" + "bytes" + "context" + "io/fs" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "sort" + "strconv" + "strings" + "time" +) + +// Detected holds defaults guessed from a manuscript directory. +type Detected struct { + Kind, Src, Main, Repo string +} + +var skipDirs = map[string]bool{".git": true, "node_modules": true, "env": true, ".venv": true, "__pycache__": true, "data": true, ".artifacts": true} + +// Detect guesses kind, source dir, main file and git repo for dir. When the +// top level has no source, it looks one level down (coauthor repos, nested +// working copies). +func Detect(dir string) Detected { + d := detectIn(dir) + if d.Main == "" { + var cands []string + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if e.IsDir() && !strings.HasPrefix(e.Name(), ".") && !skipDirs[e.Name()] { + cands = append(cands, e.Name()) + } + } + sort.SliceStable(cands, func(i, j int) bool { + return isRepo(filepath.Join(dir, cands[i])) && !isRepo(filepath.Join(dir, cands[j])) + }) + for _, c := range cands { + if sub := detectIn(filepath.Join(dir, c)); sub.Main != "" { + d.Kind, d.Main, d.Src = sub.Kind, sub.Main, c + break + } + } + } + if d.Src == "" { + d.Src = "." + } + switch { + case isRepo(filepath.Join(dir, d.Src)): + d.Repo = d.Src + case isRepo(dir): + d.Repo = "." + default: + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if e.IsDir() && isRepo(filepath.Join(dir, e.Name())) { + d.Repo = e.Name() + break + } + } + } + return d +} + +func isRepo(dir string) bool { + _, err := os.Stat(filepath.Join(dir, ".git")) + return err == nil +} + +var makeName = regexp.MustCompile(`(?m)^NAME\s*=\s*(\S+)`) + +func detectIn(dir string) Detected { + if b, err := os.ReadFile(filepath.Join(dir, "Makefile")); err == nil { + if m := makeName.FindSubmatch(b); m != nil { + if f := string(m[1]) + ".tex"; exists(filepath.Join(dir, f)) { + return Detected{Kind: "latex", Main: f} + } + } + } + tex, _ := filepath.Glob(filepath.Join(dir, "*.tex")) + sort.SliceStable(tex, func(i, j int) bool { return filepath.Base(tex[i]) == "main.tex" }) + for _, p := range tex { + base := filepath.Base(p) + if strings.HasPrefix(strings.ToLower(base), "old") { + continue + } + if b, err := os.ReadFile(p); err == nil && bytes.Contains(b, []byte(`\documentclass`)) { + return Detected{Kind: "latex", Main: base} + } + } + var newest string + var newestT time.Time + for _, ext := range []string{"docx", "odt"} { + docs, _ := filepath.Glob(filepath.Join(dir, "*."+ext)) + for _, p := range docs { + if strings.HasPrefix(filepath.Base(p), "~$") { + continue + } + if fi, err := os.Stat(p); err == nil && fi.ModTime().After(newestT) { + newest, newestT = p, fi.ModTime() + } + } + } + if newest != "" { + return Detected{Kind: strings.TrimPrefix(filepath.Ext(newest), "."), Main: filepath.Base(newest)} + } + return Detected{} +} + +func exists(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +func run(dir string, name string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = dir + out, err := cmd.Output() + return string(out), err +} + +type Commit struct { + Hash, Date, Subject string +} + +type Git struct { + Branch string + Remote string + Dirty int + Ahead int + Commits []Commit +} + +// GitInfo returns nil when repo is not a git repository. It never walks up +// to a parent repository. +func GitInfo(repo string, n int) *Git { + if repo == "" || !isRepo(repo) { + return nil + } + g := &Git{} + g.Branch, _ = run(repo, "git", "rev-parse", "--abbrev-ref", "HEAD") + g.Branch = strings.TrimSpace(g.Branch) + g.Remote, _ = run(repo, "git", "remote", "get-url", "origin") + g.Remote = strings.TrimSpace(g.Remote) + if out, err := run(repo, "git", "status", "--porcelain"); err == nil { + g.Dirty = len(nonEmpty(strings.Split(out, "\n"))) + } + if out, err := run(repo, "git", "rev-list", "--count", "@{u}..HEAD"); err == nil { + g.Ahead, _ = strconv.Atoi(strings.TrimSpace(out)) + } + out, _ := run(repo, "git", "log", "-n", strconv.Itoa(n), "--date=short", "--format=%h%x09%ad%x09%s") + for _, l := range nonEmpty(strings.Split(out, "\n")) { + p := strings.SplitN(l, "\t", 3) + if len(p) == 3 { + g.Commits = append(g.Commits, Commit{p[0], p[1], p[2]}) + } + } + return g +} + +func nonEmpty(s []string) []string { + return slices.DeleteFunc(s, func(x string) bool { return strings.TrimSpace(x) == "" }) +} + +var makeTarget = regexp.MustCompile(`^([A-Za-z0-9_][A-Za-z0-9_./-]*)\s*:([^=]|$)`) + +// MakeTargets lists explicit, non-pattern targets of dir/Makefile. +func MakeTargets(dir string) []string { + f, err := os.Open(filepath.Join(dir, "Makefile")) + if err != nil { + return nil + } + defer f.Close() + var out []string + sc := bufio.NewScanner(f) + for sc.Scan() { + m := makeTarget.FindStringSubmatch(sc.Text()) + if m != nil && !slices.Contains(out, m[1]) { + out = append(out, m[1]) + } + } + return out +} + +type Figure struct { + Name string + Path string + Preview string +} + +var ( + figDirs = []string{"figures", "figs", "Figures", "fig", "figure"} + figExt = []string{".svg", ".png", ".jpg", ".jpeg", ".pdf"} +) + +// Figures lists figures in the conventional figure directory of src, +// one entry per basename, preferring a web-viewable preview file. +func Figures(src string) []Figure { + byName := map[string]*Figure{} + var names []string + for _, d := range figDirs { + entries, err := os.ReadDir(filepath.Join(src, d)) + if err != nil { + continue + } + for _, e := range entries { + ext := strings.ToLower(filepath.Ext(e.Name())) + if e.IsDir() || !slices.Contains(figExt, ext) { + continue + } + name := d + "/" + strings.TrimSuffix(e.Name(), filepath.Ext(e.Name())) + f, ok := byName[name] + if !ok { + f = &Figure{Name: name} + byName[name] = f + names = append(names, name) + } + p := d + "/" + e.Name() + if f.Preview == "" || slices.Index(figExt, ext) < slices.Index(figExt, strings.ToLower(filepath.Ext(f.Preview))) { + f.Preview = p + } + if ext == ".pdf" || f.Path == "" { + f.Path = p + } + } + break + } + sort.Strings(names) + out := make([]Figure, 0, len(names)) + for _, n := range names { + out = append(out, *byName[n]) + } + return out +} + +type PDF struct { + Path string + Missing bool + Stale bool + ModTime time.Time +} + +// PDFStatus compares the built PDF with its sources (tex, bib, figures). +func PDFStatus(src, main string) *PDF { + if filepath.Ext(main) != ".tex" { + return nil + } + p := &PDF{Path: strings.TrimSuffix(main, ".tex") + ".pdf"} + fi, err := os.Stat(filepath.Join(src, p.Path)) + if err != nil { + p.Missing = true + return p + } + p.ModTime = fi.ModTime() + var srcs []string + for _, g := range []string{"*.tex", "*.bib", "*/*.svg"} { + m, _ := filepath.Glob(filepath.Join(src, g)) + srcs = append(srcs, m...) + } + for _, s := range srcs { + if si, err := os.Stat(s); err == nil && si.ModTime().After(p.ModTime) { + p.Stale = true + break + } + } + return p +} + +var conflictRe = regexp.MustCompile(`-CM-[A-Z0-9]{6,}|\(conflicted copy|sync-conflict|\s(copy|kopi)(\s\d+)?\.[^.]+$|\s\(\d+\)\.[^.]+$`) + +// Conflicts finds sync-conflict and ad hoc copy files up to depth 2. +func Conflicts(dir string) []string { + var out []string + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + rel, _ := filepath.Rel(dir, p) + if d.IsDir() { + if p != dir && (skipDirs[d.Name()] || strings.HasPrefix(d.Name(), ".") || strings.Count(rel, string(filepath.Separator)) >= 2) { + return filepath.SkipDir + } + return nil + } + if conflictRe.MatchString(d.Name()) { + out = append(out, rel) + } + return nil + }) + return out +} + +// DocText converts a docx/odt file to plain text with pandoc. +func DocText(path string, limit int) (string, error) { + out, err := run(filepath.Dir(path), "pandoc", "-t", "plain", "--wrap=none", path) + if err != nil { + return "", err + } + if len(out) > limit { + out = out[:limit] + "\n[...]" + } + return out, nil +} diff --git a/scan/scan_test.go b/scan/scan_test.go @@ -0,0 +1,129 @@ +package scan + +import ( + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" +) + +func write(t *testing.T, p, s string) { + t.Helper() + os.MkdirAll(filepath.Dir(p), 0o755) + if err := os.WriteFile(p, []byte(s), 0o644); err != nil { + t.Fatal(err) + } +} + +func fixture(t *testing.T) string { + root := t.TempDir() + write(t, filepath.Join(root, "BIBnew.bib"), "@article{Shared2000, title={s}, doi={10.5555/s}}\n@article{NoDoi2001, title={n}}\n") + ms := filepath.Join(root, "paper") + write(t, filepath.Join(ms, "Makefile"), "NAME=paper\n\n$(NAME).pdf: $(DEPS)\n\tlatexmk\nfigures/%.pdf: figures/%.svg\n\tx\nauto: x\nCC := cc\n.PHONY: auto\n") + write(t, filepath.Join(ms, "paper.tex"), "\\documentclass{article}\n\\input{sec}\n\\cite{Shared2000,Local1}\n% \\cite{Commented}\n\\todo{fix intro}\n\\bibliography{BIBnew,methods}\n") + write(t, filepath.Join(ms, "sec.tex"), "See \\citep[p.~2]{NoDoi2001} and \\citet{Missing9}. % TODO: tighten\n") + write(t, filepath.Join(ms, "methods.bib"), "@article{Local1, doi={10.5555/l}}\n@misc{Unused1, title={u}}\n") + write(t, filepath.Join(ms, "figures", "a.svg"), "<svg/>") + write(t, filepath.Join(ms, "figures", "a.pdf"), "%PDF") + write(t, filepath.Join(ms, "figures", "b.pdf"), "%PDF") + write(t, filepath.Join(ms, "fig5-CM-LCJJPW03NP.py"), "") + write(t, filepath.Join(ms, "main copy.pdf"), "") + return root +} + +func TestDetectNested(t *testing.T) { + root := t.TempDir() + write(t, filepath.Join(root, "ms", "rev1", "response.tex"), "\\documentclass{article}") + write(t, filepath.Join(root, "ms", "repo", "paper0.tex"), "\\documentclass{article}") + os.MkdirAll(filepath.Join(root, "ms", "repo", ".git"), 0o755) + d := Detect(filepath.Join(root, "ms")) + if d != (Detected{Kind: "latex", Src: "repo", Main: "paper0.tex", Repo: "repo"}) { + t.Fatalf("detected %+v", d) + } + write(t, filepath.Join(root, "doc", "old.docx"), "") + write(t, filepath.Join(root, "doc", "new.odt"), "") + future := time.Now().Add(time.Hour) + os.Chtimes(filepath.Join(root, "doc", "new.odt"), future, future) + if d := Detect(filepath.Join(root, "doc")); d.Kind != "odt" || d.Main != "new.odt" || d.Src != "." || d.Repo != "" { + t.Fatalf("detected %+v", d) + } +} + +func TestDetectMakefileName(t *testing.T) { + root := fixture(t) + if d := Detect(filepath.Join(root, "paper")); d.Main != "paper.tex" || d.Kind != "latex" { + t.Fatalf("detected %+v", d) + } +} + +func TestMakeTargets(t *testing.T) { + got := MakeTargets(filepath.Join(fixture(t), "paper")) + if !slices.Equal(got, []string{"auto"}) { + t.Fatalf("targets = %v", got) + } +} + +func TestFigures(t *testing.T) { + got := Figures(filepath.Join(fixture(t), "paper")) + if len(got) != 2 || got[0] != (Figure{"figures/a", "figures/a.pdf", "figures/a.svg"}) || got[1].Preview != "figures/b.pdf" { + t.Fatalf("figures = %+v", got) + } +} + +func TestTeXAndBib(t *testing.T) { + root := fixture(t) + src := filepath.Join(root, "paper") + tex := ParseTeX(src, "paper.tex") + if !slices.Equal(slices.Sorted(slices.Values(tex.Cites)), []string{"Local1", "Missing9", "NoDoi2001", "Shared2000"}) { + t.Fatalf("cites = %v", tex.Cites) + } + if len(tex.Todos) != 2 || tex.Todos[0].File != "sec.tex" || tex.Todos[1].Text != "fix intro" { + t.Fatalf("todos = %+v", tex.Todos) + } + r := CheckBib(root, src, tex) + if r.Files[0] != filepath.Join(root, "BIBnew.bib") { + t.Fatalf("files = %v", r.Files) + } + if !slices.Equal(r.Missing, []string{"Missing9"}) || !slices.Equal(r.Unused, []string{"Unused1"}) || !slices.Equal(r.NoDOI, []string{"NoDoi2001"}) { + t.Fatalf("report = %+v", r) + } +} + +func TestConflictsAndPDF(t *testing.T) { + root := fixture(t) + src := filepath.Join(root, "paper") + if c := Conflicts(src); len(c) != 2 { + t.Fatalf("conflicts = %v", c) + } + if p := PDFStatus(src, "paper.tex"); !p.Missing { + t.Fatal("expected missing pdf") + } + write(t, filepath.Join(src, "paper.pdf"), "%PDF") + past := time.Now().Add(-time.Hour) + os.Chtimes(filepath.Join(src, "paper.pdf"), past, past) + if p := PDFStatus(src, "paper.tex"); p.Missing || !p.Stale { + t.Fatalf("pdf = %+v", p) + } +} + +func TestGitInfo(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not available") + } + dir := t.TempDir() + if GitInfo(dir, 5) != nil { + t.Fatal("non-repo should give nil") + } + for _, a := range [][]string{{"init", "-q"}, {"-c", "user.email=t@example.org", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "first"}} { + if out, err := exec.Command("git", append([]string{"-C", dir}, a...)...).CombinedOutput(); err != nil { + t.Fatalf("%v %s", err, out) + } + } + write(t, filepath.Join(dir, "x"), "") + g := GitInfo(dir, 5) + if g == nil || g.Dirty != 1 || len(g.Commits) != 1 || g.Commits[0].Subject != "first" { + t.Fatalf("git = %+v", g) + } +} diff --git a/scan/tex.go b/scan/tex.go @@ -0,0 +1,94 @@ +package scan + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strings" +) + +var ( + citeRe = regexp.MustCompile(`\\(?:no)?cite[a-zA-Z]*\*?(?:\[[^\]]*\]){0,2}\{([^}]*)\}`) + bibRe = regexp.MustCompile(`\\(?:bibliography|addbibresource)\{([^}]*)\}`) + inputRe = regexp.MustCompile(`\\(?:input|include|subfile)\{([^}]*)\}`) + todoRe = regexp.MustCompile(`\\todo(?:\[[^\]]*\])?\{([^}]*)\}|(?:TODO|FIXME|XXX)[:\s]+(.*)`) +) + +// TeX holds facts extracted from a LaTeX main file and its \input files. +type TeX struct { + Cites []string + Bibs []string + Todos []Todo +} + +type Todo struct { + File string + Line int + Text string +} + +// ParseTeX reads main (relative to src) and the files it inputs, one level +// of recursion per file, ignoring commented-out lines for cites and bibs. +func ParseTeX(src, main string) TeX { + var t TeX + seen := map[string]bool{} + var walk func(rel string, depth int) + walk = func(rel string, depth int) { + if seen[rel] || depth > 3 { + return + } + seen[rel] = true + b, err := os.ReadFile(filepath.Join(src, rel)) + if err != nil { + return + } + for i, line := range strings.Split(string(b), "\n") { + if m := todoRe.FindStringSubmatch(line); m != nil { + text := strings.TrimSpace(m[1] + m[2]) + if text != "" { + t.Todos = append(t.Todos, Todo{rel, i + 1, text}) + } + } + code := stripComment(line) + for _, m := range citeRe.FindAllStringSubmatch(code, -1) { + for _, k := range strings.Split(m[1], ",") { + if k = strings.TrimSpace(k); k != "" && !slices.Contains(t.Cites, k) { + t.Cites = append(t.Cites, k) + } + } + } + for _, m := range bibRe.FindAllStringSubmatch(code, -1) { + for _, k := range strings.Split(m[1], ",") { + k = strings.TrimSpace(k) + if k != "" && !strings.HasSuffix(k, ".bib") { + k += ".bib" + } + if k != "" && !slices.Contains(t.Bibs, k) { + t.Bibs = append(t.Bibs, k) + } + } + } + for _, m := range inputRe.FindAllStringSubmatch(code, -1) { + f := strings.TrimSpace(m[1]) + if filepath.Ext(f) == "" { + f += ".tex" + } + walk(f, depth+1) + } + } + } + walk(main, 0) + return t +} + +func stripComment(line string) string { + for i := 0; i < len(line); i++ { + if line[i] == '\\' { + i++ + } else if line[i] == '%' { + return line[:i] + } + } + return line +}