Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 10.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub star`, `unstar`, `stars`, `watch`, `unwatch`, `follow` and
5//! `unfollow`.
6//!
7//! Each is one request of section 17 of `docs/hub.md`, and each may be sent
8//! again: starring a repository starred already, or following an account
9//! followed already, does nothing more. The repository is `-R OWNER/NAME`,
10//! else the one this repository is linked to. Exit statuses as the other
11//! hub commands: 0 done, 1 refused, 3 when the hub could not be reached or
12//! failed.
13
14use std::fmt::Write;
15use std::process::ExitCode;
16
17use anyhow::{Result, bail};
18use braid_hubproto::cards::RepoCards;
19use braid_hubproto::names::is_owner;
20use braid_hubproto::social::Subscription;
21use clap::{Args, ValueEnum};
22use serde_json::json;
23
24use super::creds::{self, HubEnv};
25use super::http::HttpHub;
26use super::remote::HubError;
27use super::social_common::{HubRepoArg, exit_for, hub_repo, print};
28use crate::Cli;
29
30/// The hub signed in to, for the commands about accounts: BRAID_HUB_URL,
31/// else the hub signed in to last, else the public hub.
32fn signed_in_hub() -> Result<HttpHub> {
33 let env = HubEnv::from_process();
34 let creds = env.credentials()?;
35 let url = creds::hub_url(&env, &creds, None)?;
36 Ok(super::client(&env, &url)?.0)
37}
38
39/// What a command answers when the hub refused it or could not be
40/// reached: the error, and the exit status it calls for.
41fn failed(err: &HubError) -> ExitCode {
42 eprintln!("braid: error: {err}");
43 ExitCode::from(exit_for(err))
44}
45
46/// `text` as a value of a query string: everything but letters, digits
47/// and `-._~` percent-encoded.
48fn query_value(text: &str) -> String {
49 let mut out = String::with_capacity(text.len());
50 for byte in text.bytes() {
51 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
52 out.push(char::from(byte));
53 } else {
54 let _ = write!(out, "%{byte:02X}");
55 }
56 }
57 out
58}
59
60/// A login given on the command line, checked as the hub checks it.
61fn login_arg(login: &str) -> Result<String> {
62 if !is_owner(login) {
63 bail!(
64 "{login:?} is not a login: 1 to 39 letters, digits and hyphens, with no hyphen at either end and no two in a row"
65 );
66 }
67 Ok(login.to_ascii_lowercase())
68}
69
70/// `hub star`.
71#[derive(Debug, Args)]
72pub(crate) struct StarArgs {
73 #[command(flatten)]
74 pub(crate) repo: HubRepoArg,
75}
76
77pub(crate) fn star(cli: &Cli, args: &StarArgs) -> Result<ExitCode> {
78 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
79 if let Err(err) = hub.call("PUT", &format!("{}/star", path.api_path()), &[], None) {
80 return Ok(failed(&err));
81 }
82 print(
83 cli,
84 &json!({"repo": path.to_string(), "starred": true}),
85 || format!("Starred {path}."),
86 )?;
87 Ok(ExitCode::SUCCESS)
88}
89
90/// `hub unstar`.
91#[derive(Debug, Args)]
92pub(crate) struct UnstarArgs {
93 #[command(flatten)]
94 pub(crate) repo: HubRepoArg,
95}
96
97pub(crate) fn unstar(cli: &Cli, args: &UnstarArgs) -> Result<ExitCode> {
98 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
99 if let Err(err) = hub.call("DELETE", &format!("{}/star", path.api_path()), &[], None) {
100 return Ok(failed(&err));
101 }
102 print(
103 cli,
104 &json!({"repo": path.to_string(), "starred": false}),
105 || format!("Took back the star of {path}."),
106 )?;
107 Ok(ExitCode::SUCCESS)
108}
109
110/// `hub stars`.
111#[derive(Debug, Args)]
112pub(crate) struct StarsArgs {
113 /// List what this account starred (default: your own stars).
114 #[arg(long, value_name = "LOGIN")]
115 pub(crate) user: Option<String>,
116 /// The most repositories to list, 1 to 100 (default: 30).
117 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=100))]
118 pub(crate) limit: Option<u32>,
119 /// Where to start: the `next` of the page before.
120 #[arg(long, value_name = "CURSOR")]
121 pub(crate) after: Option<String>,
122}
123
124pub(crate) fn stars(cli: &Cli, args: &StarsArgs) -> Result<ExitCode> {
125 let user = args.user.as_deref().map(login_arg).transpose()?;
126 let mut route = match &user {
127 Some(login) => format!("/v1/users/{login}/starred"),
128 None => "/v1/me/starred".to_owned(),
129 };
130 let mut query = Vec::new();
131 if let Some(limit) = args.limit {
132 query.push(format!("limit={limit}"));
133 }
134 if let Some(after) = &args.after {
135 query.push(format!("after={}", query_value(after)));
136 }
137 if !query.is_empty() {
138 route = format!("{route}?{}", query.join("&"));
139 }
140 let hub = signed_in_hub()?;
141 let page: RepoCards = match hub.call_json("GET", &route, &[], None) {
142 Ok(page) => page,
143 Err(err) => return Ok(failed(&err)),
144 };
145 print(cli, &serde_json::to_value(&page)?, || {
146 let mut out = String::new();
147 if page.repos.is_empty() {
148 out.push_str(match &user {
149 Some(_) => "No stars of repositories you can read.",
150 None => "No stars yet.",
151 });
152 }
153 for card in &page.repos {
154 if !out.is_empty() {
155 out.push('\n');
156 }
157 let _ = write!(out, "{}/{}", card.owner, card.name);
158 if card.private {
159 out.push_str(" (private)");
160 }
161 let _ = write!(
162 out,
163 ", {} {}",
164 card.stars,
165 if card.stars == 1 { "star" } else { "stars" }
166 );
167 if let Some(when) = &card.starred_at {
168 let _ = write!(out, ", starred {when}");
169 }
170 if !card.description.is_empty() {
171 let _ = write!(out, "\n {}", card.description);
172 }
173 }
174 if let Some(next) = &page.next {
175 let _ = write!(out, "\nMore: braid hub stars");
176 if let Some(login) = &user {
177 let _ = write!(out, " --user {login}");
178 }
179 let _ = write!(out, " --after {next}");
180 }
181 out
182 })?;
183 Ok(ExitCode::SUCCESS)
184}
185
186/// How to watch a repository.
187#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
188pub(crate) enum WatchLevel {
189 /// Everything that happens in it.
190 All,
191 /// What you take part in or are mentioned in.
192 Participating,
193 /// Nothing, not even what you take part in.
194 Ignore,
195}
196
197impl WatchLevel {
198 fn as_str(self) -> &'static str {
199 match self {
200 WatchLevel::All => braid_hubproto::social::ALL,
201 WatchLevel::Participating => braid_hubproto::social::PARTICIPATING,
202 WatchLevel::Ignore => braid_hubproto::social::IGNORE,
203 }
204 }
205}
206
207/// How `path` is watched at `level`, in words.
208fn watched(path: &impl std::fmt::Display, level: &str) -> String {
209 match level {
210 braid_hubproto::social::ALL => format!("Watching all of {path}."),
211 braid_hubproto::social::IGNORE => format!("Ignoring {path}: nothing of it notifies you."),
212 _ => format!("Watching what you take part in on {path}."),
213 }
214}
215
216/// `hub watch`.
217#[derive(Debug, Args)]
218pub(crate) struct WatchArgs {
219 #[command(flatten)]
220 pub(crate) repo: HubRepoArg,
221 /// What to watch: all of it, what you take part in, or nothing.
222 #[arg(long, value_enum, default_value_t = WatchLevel::All)]
223 pub(crate) level: WatchLevel,
224}
225
226pub(crate) fn watch(cli: &Cli, args: &WatchArgs) -> Result<ExitCode> {
227 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
228 let body = json!({"level": args.level.as_str()});
229 let route = format!("{}/subscription", path.api_path());
230 let subscription: Subscription = match hub.call_json("PUT", &route, &[], Some(&body)) {
231 Ok(subscription) => subscription,
232 Err(err) => return Ok(failed(&err)),
233 };
234 let mut value = serde_json::to_value(&subscription)?;
235 value["repo"] = json!(path.to_string());
236 print(cli, &value, || watched(&path, &subscription.level))?;
237 Ok(ExitCode::SUCCESS)
238}
239
240/// `hub unwatch`.
241#[derive(Debug, Args)]
242pub(crate) struct UnwatchArgs {
243 #[command(flatten)]
244 pub(crate) repo: HubRepoArg,
245}
246
247pub(crate) fn unwatch(cli: &Cli, args: &UnwatchArgs) -> Result<ExitCode> {
248 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
249 let route = format!("{}/subscription", path.api_path());
250 if let Err(err) = hub.call("DELETE", &route, &[], None) {
251 return Ok(failed(&err));
252 }
253 let level = braid_hubproto::social::PARTICIPATING;
254 print(
255 cli,
256 &json!({"repo": path.to_string(), "level": level}),
257 || watched(&path, level),
258 )?;
259 Ok(ExitCode::SUCCESS)
260}
261
262/// `hub follow`.
263#[derive(Debug, Args)]
264pub(crate) struct FollowArgs {
265 /// The account to follow.
266 #[arg(value_name = "LOGIN")]
267 pub(crate) login: String,
268}
269
270pub(crate) fn follow(cli: &Cli, args: &FollowArgs) -> Result<ExitCode> {
271 follow_or_not(cli, &args.login, true)
272}
273
274/// `hub unfollow`.
275#[derive(Debug, Args)]
276pub(crate) struct UnfollowArgs {
277 /// The account to stop following.
278 #[arg(value_name = "LOGIN")]
279 pub(crate) login: String,
280}
281
282pub(crate) fn unfollow(cli: &Cli, args: &UnfollowArgs) -> Result<ExitCode> {
283 follow_or_not(cli, &args.login, false)
284}
285
286/// Follows `login`, or stops following it.
287fn follow_or_not(cli: &Cli, login: &str, follow: bool) -> Result<ExitCode> {
288 let login = login_arg(login)?;
289 let hub = signed_in_hub()?;
290 let method = if follow { "PUT" } else { "DELETE" };
291 if let Err(err) = hub.call(method, &format!("/v1/users/{login}/follow"), &[], None) {
292 return Ok(failed(&err));
293 }
294 print(cli, &json!({"login": login, "following": follow}), || {
295 if follow {
296 format!("Following {login}.")
297 } else {
298 format!("No longer following {login}.")
299 }
300 })?;
301 Ok(ExitCode::SUCCESS)
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn query_values_and_logins() {
310 assert_eq!(query_value("s1700000000.42"), "s1700000000.42");
311 assert_eq!(query_value("wada/demo"), "wada%2Fdemo");
312 assert_eq!(query_value("a b&c=d"), "a%20b%26c%3Dd");
313 assert_eq!(login_arg("Ada").unwrap(), "ada");
314 for bad in ["", "-ada", "ada-", "a/b", "a b"] {
315 assert!(login_arg(bad).is_err(), "{bad:?}");
316 }
317 assert_eq!(WatchLevel::Participating.as_str(), "participating");
318 assert_eq!(watched(&"ada/demo", "all"), "Watching all of ada/demo.");
319 }
320}