1use std::process::ExitCode;
6
7mod render;
8
9use trumly_core::report::{check, Report};
10use trumly_fs::read_model;
11
12fn load_report(dir: &str) -> Result<Report, String> {
13 Ok(check(read_model(dir)?))
14}
15
16fn packs_dir(args: &[String]) -> Option<std::path::PathBuf> {
18 args.iter().position(|a| a == "--packs").and_then(|i| args.get(i + 1)).map(std::path::PathBuf::from)
19}
20
21fn positional(args: &[String]) -> Vec<&String> {
23 let mut out = Vec::new();
24 let mut skip = false;
25 for a in args {
26 if skip { skip = false; } else if a == "--packs" || a == "--only" { skip = true; } else if !a.starts_with("--") { out.push(a); }
27 }
28 out
29}
30
31fn telemetry(args: &[String]) -> Result<i32, String> {
32 use trumly_fs::telemetry as t;
33 match args.first().map(String::as_str).unwrap_or("status") {
34 "status" => {
35 println!("usage data: {}{}", t::state().as_str(), if t::forced_off() { " (forced off by DO_NOT_TRACK or TRUMLY_TELEMETRY=off)" } else if t::chosen() == t::State::Unset { " (you have not been asked yet)" } else { "" });
36 println!("endpoint: {}", t::endpoint().unwrap_or_else(|| "none set (events stay on this computer)".to_string()));
37 println!("queued: {}", t::queued_count());
38 Ok(0)
39 }
40 "on" => { t::set_state(t::State::On)?; println!("usage data is on. See exactly what is kept with: trumly telemetry show"); Ok(0) }
41 "off" => { t::set_state(t::State::Off)?; println!("usage data is off; the install id and anything unsent were deleted"); Ok(0) }
42 "show" => {
43 println!("Kept: a random install id, the version, your OS, what was done (like pack_added) and rounded counts.\nNever kept: node ids, titles, field values, file paths or any model content.\n");
44 let q = t::queued(1000);
45 if q.is_empty() { println!("Nothing is queued."); }
46 for e in q { println!("{e}"); }
47 Ok(0)
48 }
49 "send" => {
50 let Some(url) = t::endpoint() else { return Err("no endpoint: set TRUMLY_TELEMETRY_URL (or \"endpoint\" in telemetry.json)".to_string()) };
51 if t::state() != t::State::On { return Err("usage data is not on".to_string()); }
52 let events = t::queued(200);
53 if events.is_empty() { println!("nothing to send"); return Ok(0); }
54 let n = events.len();
55 match ureq::post(&url).timeout(std::time::Duration::from_secs(5)).send_json(serde_json::json!({"events": events})) {
56 Ok(_) => { t::ack(n); println!("sent {n} events"); Ok(0) }
57 Err(e) => { println!("could not reach {url} ({e}); the events are kept and will be sent later"); Ok(0) }
58 }
59 }
60 _ => Err("usage: trumly telemetry [status|on|off|show|send]".to_string()),
61 }
62}
63
64fn pack(args: &[String]) -> Result<i32, String> {
65 use trumly_fs::library;
66 use trumly_fs::pack::{add, installed, read_pack, remove, status};
67 let packs = packs_dir(args);
68 let pos = positional(args);
69 match pos.first().map(|s| s.as_str()) {
70 Some("list") => {
71 let model = pos.get(1).map_or(".", |s| s.as_str());
72 let have = installed(std::path::Path::new(model)).unwrap_or_default();
73 for e in library::load(packs.as_deref())?.entries {
74 let p = e.pack;
75 let mark = match have.iter().find(|(n, _)| *n == p.name) { Some((_, v)) if *v == p.version => " [added]", Some((_, v)) => &format!(" [model has {v}]"), None => "" };
76 println!("{:<20} {:<5} {} {} nodes{}{}{} ({})", p.name, p.namespace, p.version, p.files.len() - 1, if p.includes.is_empty() { String::new() } else { format!(" includes {}", p.includes.join(", ")) }, if p.requires.is_empty() { String::new() } else { format!(" needs {}", p.requires.join(", ")) }, mark, e.source);
77 println!(" {}", p.description);
78 }
79 Ok(0)
80 }
81 Some("add") => {
82 let name = pos.get(1).ok_or("usage: trumly pack add NAME [DIR] [--only a,b] [--packs PACKS] [--force] [--use-existing | --replace-existing]")?;
83 let model = std::path::Path::new(pos.get(2).map_or(".", |s| s.as_str()));
84 let force = args.iter().any(|a| a == "--force");
85 let only: Option<Vec<String>> = args.iter().position(|a| a == "--only").and_then(|i| args.get(i + 1)).map(|v| v.split(',').map(str::to_string).collect());
86 let results = if read_pack(std::path::Path::new(name.as_str())).is_ok() {
88 let pack = read_pack(std::path::Path::new(name.as_str()))?;
89 vec![(pack.name.clone(), add(&pack, model, force)?)]
90 } else {
91 let all = library::load(packs.as_deref())?.packs();
92 let clash = if args.iter().any(|a| a == "--use-existing") { trumly_fs::pack::Clash::Skip } else if args.iter().any(|a| a == "--replace-existing") { trumly_fs::pack::Clash::Replace } else { trumly_fs::pack::Clash::Refuse };
93 trumly_fs::pack::add_tree_with(&all, name, only.as_deref(), model, force, clash)?
94 };
95 for (pack, r) in results {
96 println!("{pack}: {} added, {} updated", r.added.len(), r.updated.len());
97 if !r.kept.is_empty() {
98 println!(" you changed these and the pack did too; yours were kept (--force takes the pack's): {}", r.kept.join(", "));
99 }
100 if !r.skipped.is_empty() {
101 println!(" left out, the model already defines them: {}", r.skipped.join(", "));
102 }
103 if !r.replaced.is_empty() {
104 println!(" replaced definitions that were already there: {}", r.replaced.join(", "));
105 }
106 if !r.removed.is_empty() {
107 println!(" dropped by the pack and removed: {}", r.removed.join(", "));
108 }
109 if !r.no_longer_in_pack.is_empty() {
110 println!(" no longer in the pack, but changed by you (left in place): {}", r.no_longer_in_pack.join(", "));
111 }
112 }
113 Ok(0)
114 }
115 Some("remove") => {
116 let name = pos.get(1).ok_or("usage: trumly pack remove NAME [DIR] [--force]")?;
117 let model = std::path::Path::new(pos.get(2).map_or(".", |s| s.as_str()));
118 let r = remove(name, model, args.iter().any(|a| a == "--force"))?;
119 println!("{name}: removed {} nodes", r.removed.len());
120 Ok(0)
121 }
122 Some("check") => {
123 let mut all = library::load(packs.as_deref())?.packs();
125 let target = pos.get(1).map(|s| s.as_str());
126 let name = match target {
127 Some(t) if std::path::Path::new(t).join("").is_dir() && !all.iter().any(|p| p.name == t) => {
128 let p = read_pack(std::path::Path::new(t))?;
129 let n = p.name.clone();
130 all.retain(|x| x.name != n);
131 all.push(p);
132 Some(n)
133 }
134 other => other.map(str::to_string),
135 };
136 let problems: Vec<_> = trumly_fs::pack::lint(&all).into_iter().filter(|p| name.as_ref().is_none_or(|n| *n == p.pack)).collect();
137 for p in &problems {
138 println!("{:<8} {:<20} {}", p.severity, p.pack, p.message);
139 }
140 let errors = problems.iter().filter(|p| p.severity == "error").count();
141 println!("{} packs checked, {} errors, {} warnings", name.as_ref().map_or(all.len(), |_| 1), errors, problems.len() - errors);
142 Ok(if errors > 0 { 1 } else { 0 })
143 }
144 Some("status") => {
145 let model = std::path::Path::new(pos.get(1).map_or(".", |s| s.as_str()));
146 let all = status(model)?;
147 if all.is_empty() {
148 println!("no packs in this model");
149 }
150 for s in all {
151 println!("{:<20} {} {} as provided{}{}", s.name, s.version, s.clean,
152 if s.changed.is_empty() { String::new() } else { format!(", changed by you: {}", s.changed.join(", ")) },
153 if s.missing.is_empty() { String::new() } else { format!(", deleted by you: {}", s.missing.join(", ")) });
154 }
155 Ok(0)
156 }
157 _ => Err("usage:\n trumly pack list [DIR] [--packs PACKS]\n trumly pack add NAME [DIR] [--only a,b] [--packs PACKS] [--force] [--use-existing | --replace-existing]\n trumly pack remove NAME [DIR] [--force]\n trumly pack status [DIR]\n trumly pack check [NAME | PACK-FOLDER] [--packs PACKS]".to_string()),
158 }
159}
160
161fn rename(args: &[String]) -> Result<i32, String> {
163 let keep_ids = args.iter().any(|a| a == "--keep-ids");
164 let pos = positional(args);
165 let usage = "usage:\n trumly rename node FROM TO [DIR]\n trumly rename type OLD NEW [DIR] [--keep-ids]\n trumly rename link-type OLD NEW [DIR]";
166 let (what, a, b) = match (pos.first(), pos.get(1), pos.get(2)) {
167 (Some(w), Some(a), Some(b)) => (w.as_str(), a.as_str(), b.as_str()),
168 _ => return Err(usage.into()),
169 };
170 let dir = pos.get(3).map_or(".", |d| d.as_str());
171 let (graph, _) = trumly_core::load::load(read_model(dir)?);
172 let edit = match what {
173 "node" => trumly_core::ops::rename_node(&graph, a, b)?,
174 "type" | "link-type" => {
175 let def = graph.nodes().find(|n| n.kind.as_deref() == Some(what) && n.fields.get("name").and_then(|v| v.as_str()) == Some(a)).ok_or(format!("the model defines no {what} called '{a}'"))?;
176 trumly_core::ops::rename_def(&graph, &def.id.clone(), b, what == "type" && !keep_ids)?
177 }
178 _ => return Err(usage.into()),
179 };
180 let (w, r) = trumly_fs::apply_edit(dir, &edit)?;
181 println!("renamed {a} to {b}: {w} files written, {r} removed");
182 Ok(0)
183}
184
185const HELP: &str = "trumly a system's design, as a typed graph in git
187
188usage: trumly COMMAND [ARGS] (new here? run: trumly quickstart)
189
190Look at a model (DIR defaults to the current folder)
191 check [--json] [--no-color] [DIR]
192 run every rule and list the findings (exit 1 when one fails)
193 show ID [DIR] one node: its links in and out, and its rule results
194 index [DIR] [--write] a markdown map of the whole model; --write saves .trumly/INDEX.md
195
196Change a model
197 rename node FROM TO [DIR] give a node a new id; links, parents and rule filters follow
198 rename type OLD NEW [DIR] [--keep-ids] rename a type everywhere it is used
199 rename link-type OLD NEW [DIR] rename a link type everywhere it is used
200
201Packs (ready-made definitions: types, link types, rules, planes)
202 pack list [DIR] [--packs PACKS] the packs available, and which the model has
203 pack add NAME [DIR] [--only a,b] [--packs PACKS] [--force] [--use-existing | --replace-existing]
204 add a pack, with what it needs and includes
205 pack remove NAME [DIR] [--force] take a pack out of the model
206 pack status [DIR] which packs the model has and what you changed in them
207 pack check [NAME | PACK-FOLDER] [--packs PACKS] lint packs: clashing names, stray nodes, missing types
208
209Editor
210 serve [DIR] [--port N] [--page FILE] [--packs PACKS] [--browse FOLDER]
211 a local API over the folder, and the editor when --page is given.
212 --browse sets the folder the editor may open other models from
213 (your home folder by default)
214
215Anonymous usage data (off until you turn it on)
216 telemetry status whether it is on, and where it goes
217 telemetry on | off turn it on or off; off also deletes the install id and anything unsent
218 telemetry show exactly what has been kept and would be sent
219 telemetry send send what is waiting now (needs TRUMLY_TELEMETRY_URL)
220 collector [--port N] [--file FILE] [--host ADDR]
221 a small server that collects those events (default 127.0.0.1:4748)
222 DO_NOT_TRACK=1 or TRUMLY_TELEMETRY=off always wins.
223
224Colour is off for NO_COLOR, --no-color and output that is not a terminal; the words say the same either way.
225
226Other
227 quickstart a short guide to getting going (also in docs/QUICKSTART.md)
228 help, --help, -h this text
229 --version, -V the version
230
231--packs PACKS is a folder of packs (or set TRUMLY_PACKS). Without it trumly looks in ./packs, then
232~/.trumly/packs, ~/.trumly/community, and the official packs built in.
233";
234
235fn run(args: &[String]) -> Result<i32, String> {
237 match args.first().map(String::as_str) {
238 Some("help" | "--help" | "-h") => {
239 print!("{HELP}");
240 Ok(0)
241 }
242 Some("quickstart") => {
243 print!("{}", include_str!("../../../docs/QUICKSTART.md"));
244 Ok(0)
245 }
246 Some("--version" | "-V") => {
247 println!("trumly {}", env!("CARGO_PKG_VERSION"));
248 Ok(0)
249 }
250 Some("check") => {
251 let json = args.iter().any(|a| a == "--json");
252 let dir = args[1..].iter().find(|a| !a.starts_with("--")).map_or(".", String::as_str);
253 let report = load_report(dir)?;
254 if json {
255 let text = serde_json::to_string_pretty(&report.to_json()).map_err(|e| e.to_string())?;
256 println!("{text}");
257 } else {
258 let name = std::fs::canonicalize(dir).ok().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_else(|| dir.to_string());
259 print!("{}", render::check_text(&report, &name, render::Style::detect(args)));
260 }
261 let fails = |sev: bool| report.evaluation.results.iter().filter(|r| r.status == trumly_core::rules::Status::Fail && (r.severity == "error") == sev).count();
262 let (e, w) = (report.load_errors.len() + report.structure.errors.len() + fails(true), report.structure.warnings.len() + fails(false));
263 trumly_fs::telemetry::track("check_run", "cli", serde_json::json!({"errors": trumly_fs::telemetry::bucket(e), "warnings": trumly_fs::telemetry::bucket(w)}));
264 Ok(report.exit_code())
265 }
266 Some("show") => {
267 let id = args.get(1).ok_or("usage: trumly show ID [DIR]")?;
268 let report = load_report(args.get(2).map_or(".", String::as_str))?;
269 let text = report.show(id).ok_or(format!("no node with id '{id}'"))?;
270 print!("{text}");
271 Ok(0)
272 }
273 Some("index") => {
274 let write = args.iter().any(|a| a == "--write");
275 let dir = args[1..].iter().find(|a| !a.starts_with("--")).map_or(".", String::as_str);
276 let text = load_report(dir)?.index();
277 if write {
278 let path = std::path::Path::new(dir).join(".trumly").join("INDEX.md");
279 std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
280 std::fs::write(&path, &text).map_err(|e| e.to_string())?;
281 println!("wrote {}", path.display());
282 } else {
283 print!("{text}");
284 }
285 Ok(0)
286 }
287 Some("rename") => rename(&args[1..]),
288 Some("pack") => pack(&args[1..]),
289 Some("telemetry") => telemetry(&args[1..]),
290 Some("collector") => {
291 let (mut port, mut file, mut host) = (4748u16, std::path::PathBuf::from("trumly-events.jsonl"), "127.0.0.1".to_string());
292 let mut it = args[1..].iter();
293 while let Some(a) = it.next() {
294 match a.as_str() {
295 "--port" => port = it.next().and_then(|p| p.parse().ok()).ok_or("--port needs a number")?,
296 "--file" => file = it.next().ok_or("--file needs a path")?.into(),
297 "--host" => host = it.next().ok_or("--host needs an address")?.clone(),
298 other => return Err(format!("unknown option {other}")),
299 }
300 }
301 trumly_serve::collector::run(&format!("{host}:{port}"), file)?;
302 Ok(0)
303 }
304 Some("serve") => {
305 let mut dir = ".".to_string();
306 let (mut port, mut page, mut browse) = (4747u16, None, None);
307 let mut it = args[1..].iter();
308 while let Some(a) = it.next() {
309 match a.as_str() {
310 "--port" => port = it.next().and_then(|p| p.parse().ok()).ok_or("--port needs a number")?,
311 "--page" => page = Some(it.next().ok_or("--page needs a file")?.into()),
312 "--packs" => { it.next().ok_or("--packs needs a folder")?; }
313 "--browse" => browse = Some(it.next().ok_or("--browse needs a folder")?.into()),
314 other if other.starts_with("--") => return Err(format!("unknown option {other}")),
315 other => dir = other.to_string(),
316 }
317 }
318 trumly_serve::serve(trumly_serve::Options { root: dir.into(), addr: format!("127.0.0.1:{port}"), page, token: None, packs: packs_dir(&args[1..]), state: None, browse })?;
319 Ok(0)
320 }
321 None => Err(HELP.trim_end().to_string()),
322 Some(other) => Err(format!("unknown command '{other}'\n\n{HELP}", )),
323 }
324}
325
326fn main() -> ExitCode {
327 let args: Vec<String> = std::env::args().skip(1).collect();
328 match run(&args) {
329 Ok(code) => ExitCode::from(code as u8),
330 Err(msg) => {
331 eprintln!("{msg}");
332 ExitCode::from(2)
333 }
334 }
335}