Debian Codegraph @

cmd/haredoc/doc/util.ha

raw
1 // SPDX-License-Identifier: GPL-3.0-only
2 // (c) Hare authors <https://harelang.org>
3
4 use bufio;
5 use fmt;
6 use fs;
7 use hare::module;
8 use io;
9 use memio;
10 use os;
11 use path;
12 use sort;
13 use sort::cmp;
14 use strings;
15
16 let firstline: bool = true;
17
18 fn trim_comment(s: str) str = {
19 let trimmed = memio::dynamic();
20 let tok = strings::tokenize(s, "\n");
21 for (let line => strings::next_token(&tok)) {
22 memio::concat(&trimmed, strings::trimprefix(line, " "), "\n")!;
23 };
24 return strings::dup(memio::string(&trimmed)!)!;
25 };
26
27 export type submodule = struct {
28 name: str,
29 desc: str,
30 };
31
32 export fn submodules(path: str, show_undocumented: bool) ([]submodule | error) = {
33 let submodules: []submodule = [];
34 let it = os::iter(path)?;
35 defer fs::finish(it);
36 let pathbuf = path::init(path)!;
37 for (let d => module::next(it)?) {
38 path::set(&pathbuf, path, d.name, "README")!;
39
40 const file = match (os::open(path::string(&pathbuf))) {
41 case let f: io::file =>
42 yield f;
43 case =>
44 if (show_undocumented) {
45 append(submodules, submodule {
46 name = strings::dup(d.name)!,
47 desc = "",
48 })!;
49 };
50 continue;
51 };
52 defer io::close(file)!;
53
54 let mod = submodule {
55 name = strings::dup(d.name)!,
56 desc = "",
57 };
58
59 const scan = bufio::newscanner(file);
60 defer bufio::finish(&scan);
61
62 const prefix = fmt::asprintf("{}: ", d.name)!;
63 defer free(prefix);
64
65 match (bufio::scan_line(&scan)) {
66 case let s: const str =>
67 if (strings::hasprefix(s, prefix)) {
68 const desc = strings::sub(s, len(prefix));
69 mod.desc = strings::dup(desc)!;
70 };
71 case => void;
72 };
73
74 append(submodules, mod)!;
75 };
76 sort::sort(submodules, size(submodule), &submodule_cmp)!;
77 return submodules;
78 };
79
80 export fn submodules_finish(subs: []submodule) void = {
81 for (let sub .. subs) {
82 free(sub.name);
83 free(sub.desc);
84 };
85 free(subs);
86 };
87
88 fn submodule_cmp(a: *const opaque, b: *const opaque) int = {
89 const a = a: *const submodule;
90 const b = b: *const submodule;
91 return cmp::strs(&a.name, &b.name);
92 };
93
94 // Trims the cwd from a path if applicable.
95 export fn cwdpath(path: str) str = {
96 static let cwd = "";
97 if (cwd == "") {
98 cwd = os::getcwd();
99 };
100 if (strings::hasprefix(path, cwd)) {
101 return strings::sub(path, len(cwd) + 1);
102 };
103 return path;
104 };