semora_cli/commands/
docs.rs1use std::io::Write;
4use std::path::PathBuf;
5
6use anyhow::Context;
7use semora_proto::PatchDoc;
8
9use crate::client::ListQuery;
10use crate::{Ctx, docref, exit, output};
11
12pub async fn ls(
13 ctx: &Ctx,
14 query: Option<String>,
15 tag: Option<String>,
16 kind: Option<String>,
17 limit: u32,
18) -> anyhow::Result<i32> {
19 let client = ctx.client()?;
20 let list = client
21 .list(&ListQuery {
22 q: query,
23 tag,
24 kind,
25 limit: Some(limit),
26 cursor: None,
27 })
28 .await?;
29 if ctx.json {
30 output::json(&list);
31 return Ok(exit::OK);
32 }
33 if list.docs.is_empty() {
34 println!("No documents.");
35 return Ok(exit::OK);
36 }
37 for d in &list.docs {
38 let tags = if d.tags.is_empty() {
39 String::new()
40 } else {
41 format!(" [{}]", d.tags.join(", "))
42 };
43 println!(
44 "{} r{:<3} {:<6} {} {}{}",
45 d.id,
46 d.rev,
47 d.kind.as_str(),
48 output::ts(d.updated_at),
49 d.title,
50 tags
51 );
52 }
53 if list.next_cursor.is_some() {
54 println!("… more; raise --limit or narrow with -q/--tag");
55 }
56 Ok(exit::OK)
57}
58
59pub async fn show(ctx: &Ctx, doc: &str) -> anyhow::Result<i32> {
60 let client = ctx.client()?;
61 let id = docref::parse(doc)?;
62 let d = client.doc(&id).await?;
63 if ctx.json {
64 output::json(&d);
65 return Ok(exit::OK);
66 }
67 let s = &d.summary;
68 println!(
69 "{} ({}, r{}, {} revisions kept)",
70 s.title,
71 s.kind.as_str(),
72 s.rev,
73 s.revision_count
74 );
75 println!(" url {}", s.url);
76 println!(" ws {}", d.ws_url);
77 println!(" entry {}", d.entry_path);
78 if !s.tags.is_empty() {
79 println!(" tags {}", s.tags.join(", "));
80 }
81 println!("files:");
82 for f in &d.files {
83 println!(" {:<40} {:>9} {}", f.path, output::size(f.size), f.mime);
84 }
85 println!("revisions:");
86 for r in &d.revisions {
87 let by = r
88 .created_by
89 .as_deref()
90 .map(|b| format!(" by {b}"))
91 .unwrap_or_default();
92 let msg = r
93 .message
94 .as_deref()
95 .map(|m| format!(" {m}"))
96 .unwrap_or_default();
97 println!(" r{:<4} {}{}{}", r.rev, output::ts(r.created_at), msg, by);
98 }
99 Ok(exit::OK)
100}
101
102pub async fn get(
103 ctx: &Ctx,
104 doc: &str,
105 path: Option<String>,
106 rev: Option<i64>,
107 out: Option<PathBuf>,
108) -> anyhow::Result<i32> {
109 let client = ctx.client()?;
110 let id = docref::parse(doc)?;
111 let bytes = client.raw(&id, path.as_deref(), rev).await?;
112 match out {
113 Some(p) => {
114 std::fs::write(&p, &bytes).with_context(|| format!("writing {}", p.display()))?
115 }
116 None => {
117 let mut stdout = std::io::stdout().lock();
118 stdout.write_all(&bytes)?;
119 stdout.flush()?;
120 }
121 }
122 Ok(exit::OK)
123}
124
125pub fn tag_changes(changes: &[String]) -> PatchDoc {
127 let mut p = PatchDoc::default();
128 for c in changes {
129 for part in c.split(',').map(str::trim).filter(|s| !s.is_empty()) {
130 if let Some(t) = part.strip_prefix('-') {
131 p.remove_tags.push(t.to_string());
132 } else {
133 p.add_tags.push(part.trim_start_matches('+').to_string());
134 }
135 }
136 }
137 p
138}
139
140pub async fn tag(ctx: &Ctx, doc: &str, changes: &[String]) -> anyhow::Result<i32> {
141 let client = ctx.client()?;
142 let id = docref::parse(doc)?;
143 let s = client.patch(&id, &tag_changes(changes)).await?;
144 if ctx.json {
145 output::json(&s);
146 } else {
147 println!(
148 "{}: {}",
149 s.id,
150 if s.tags.is_empty() {
151 "(no tags)".to_string()
152 } else {
153 s.tags.join(", ")
154 }
155 );
156 }
157 Ok(exit::OK)
158}
159
160pub async fn rm(ctx: &Ctx, doc: &str) -> anyhow::Result<i32> {
161 let client = ctx.client()?;
162 let id = docref::parse(doc)?;
163 client.delete(&id).await?;
164 if !ctx.json {
165 println!("Deleted {id} (purged after 7 days)");
166 }
167 Ok(exit::OK)
168}
169
170pub async fn open(ctx: &Ctx, doc: &str) -> anyhow::Result<i32> {
171 let client = ctx.client()?;
172 let id = docref::parse(doc)?;
173 let d = client.doc(&id).await?;
174 println!("{}", d.summary.url);
175 if ctx.settings.open_browser
176 && let Err(e) = open::that(&d.summary.url)
177 {
178 output::warn(format!("could not open a browser: {e}"));
179 }
180 Ok(exit::OK)
181}
182
183#[cfg(test)]
184mod tests {
185 use super::tag_changes;
186
187 #[test]
188 fn parses_tag_changes() {
189 let p = tag_changes(&["+a".into(), "-b".into(), "c,d".into()]);
190 assert_eq!(p.add_tags, vec!["a", "c", "d"]);
191 assert_eq!(p.remove_tags, vec!["b"]);
192 }
193}