Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 16.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! `braid hub settings`, `block`, `unblock` and `account`.
5//!
6//! `settings` shows a repository's settings, or changes those its flags
7//! name, as `PATCH /v1/r/{owner}/{name}` does (section 4 of `docs/hub.md`):
8//! its admins see and change them all. `block` and `unblock` block an
9//! account from every repository of the account signed in, or, with `-R`,
10//! from one repository it administers (section 22). `account` shows the
11//! account's own settings, or changes them (section 3). Exit statuses as
12//! the other hub commands: 0 done, 1 refused, 3 when the hub could not be
13//! reached or failed.
14
15use std::fmt::Write;
16use std::process::ExitCode;
17
18use anyhow::{Result, bail};
19use braid_hubproto::api::{Me, RepoInfo, RepoPatch};
20use braid_hubproto::moderation::{MePatch, TDM_ALLOWED, TDM_RESERVED};
21use braid_hubproto::names::is_owner;
22use clap::{Args, ValueEnum};
23use serde_json::json;
24
25use super::creds::{self, HubEnv};
26use super::http::HttpHub;
27use super::remote::{HubError, shown};
28use super::social_common::{HubRepoArg, exit_for, hub_repo, print};
29use crate::Cli;
30
31/// What making a repository public shows, said when it is done.
32const PUBLIC_NOTE: &str = "everything it ever stored is readable now by anyone who knows its id, not only what its branches hold: its whole history, branches deleted since, uploads that never landed, and its issues and change requests";
33
34/// The hub signed in to, for the commands about the account: BRAID_HUB_URL,
35/// else the hub signed in to last, else the public hub.
36fn signed_in_hub() -> Result<HttpHub> {
37 let env = HubEnv::from_process();
38 let creds = env.credentials()?;
39 let url = creds::hub_url(&env, &creds, None)?;
40 Ok(super::client(&env, &url)?.0)
41}
42
43/// What a command answers when the hub refused it or could not be
44/// reached: the error, and the exit status it calls for.
45fn failed(err: &HubError) -> ExitCode {
46 eprintln!("braid: error: {err}");
47 ExitCode::from(exit_for(err))
48}
49
50/// A login given on the command line, checked as the hub checks it.
51fn login_arg(login: &str) -> Result<String> {
52 if !is_owner(login) {
53 bail!(
54 "{login:?} is not a login: 1 to 39 letters, digits and hyphens, with no hyphen at either end and no two in a row"
55 );
56 }
57 Ok(login.to_ascii_lowercase())
58}
59
60/// On or off.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
62pub(crate) enum Switch {
63 On,
64 Off,
65}
66
67impl Switch {
68 fn on(self) -> bool {
69 self == Switch::On
70 }
71}
72
73/// Text and data mining of a repository's content.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
75pub(crate) enum Mining {
76 /// Anyone may mine it.
77 Allowed,
78 /// Its owner reserves it.
79 Reserved,
80}
81
82impl Mining {
83 fn as_str(self) -> &'static str {
84 match self {
85 Mining::Allowed => TDM_ALLOWED,
86 Mining::Reserved => TDM_RESERVED,
87 }
88 }
89}
90
91/// Who may open change requests.
92#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
93pub(crate) enum RequestsFrom {
94 /// Anyone who reads the repository.
95 Readers,
96 /// Its collaborators only.
97 Collaborators,
98 /// Nobody.
99 Off,
100}
101
102impl RequestsFrom {
103 fn as_str(self) -> &'static str {
104 match self {
105 RequestsFrom::Readers => "readers",
106 RequestsFrom::Collaborators => "collaborators",
107 RequestsFrom::Off => "off",
108 }
109 }
110}
111
112/// How the hub takes in what is pushed to a repository's GitHub mirror.
113#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
114pub(crate) enum Follow {
115 /// It publishes each landing, and takes nothing in by itself.
116 Off,
117 /// It also takes in what is pushed there while it has nothing new.
118 FfOnly,
119 /// It takes it in, merging when both sides moved.
120 Merge,
121}
122
123impl Follow {
124 fn as_str(self) -> &'static str {
125 match self {
126 Follow::Off => "off",
127 Follow::FfOnly => "ff-only",
128 Follow::Merge => "merge",
129 }
130 }
131}
132
133/// `hub settings`.
134#[derive(Debug, Args)]
135pub(crate) struct SettingsArgs {
136 #[command(flatten)]
137 pub(crate) repo: HubRepoArg,
138 /// Make it readable by anyone: everything it ever stored becomes
139 /// readable by id, not only what its branches hold now.
140 #[arg(long, conflicts_with = "private")]
141 pub(crate) public: bool,
142 /// Make it readable only by its owner and those given access.
143 #[arg(long)]
144 pub(crate) private: bool,
145 /// A new description.
146 #[arg(long, value_name = "TEXT")]
147 pub(crate) description: Option<String>,
148 /// A new default branch.
149 #[arg(long, value_name = "BRANCH")]
150 pub(crate) default_branch: Option<String>,
151 /// Its topics, separated by commas, in place of the old ones ("" for
152 /// none).
153 #[arg(long, value_name = "TOPICS")]
154 pub(crate) topics: Option<String>,
155 /// Text and data mining of its content.
156 #[arg(long, value_enum)]
157 pub(crate) tdm: Option<Mining>,
158 /// Whether it takes issues.
159 #[arg(long, value_enum, value_name = "ON|OFF")]
160 pub(crate) issues: Option<Switch>,
161 /// Who may open change requests.
162 #[arg(long, value_enum)]
163 pub(crate) requests_from: Option<RequestsFrom>,
164 /// Whether it may be forked.
165 #[arg(long, value_enum, value_name = "ON|OFF")]
166 pub(crate) forks: Option<Switch>,
167 /// The approvals a change request needs before it lands, 0 to 10.
168 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(0..=10))]
169 pub(crate) approvals: Option<u32>,
170 /// How what is pushed to its GitHub mirror is taken in.
171 #[arg(long, value_enum)]
172 pub(crate) follow: Option<Follow>,
173}
174
175impl SettingsArgs {
176 /// The change the flags ask for: none when they name nothing.
177 fn patch(&self) -> RepoPatch {
178 let private = match (self.public, self.private) {
179 (true, _) => Some(false),
180 (_, true) => Some(true),
181 _ => None,
182 };
183 RepoPatch {
184 private,
185 description: self.description.clone(),
186 default_branch: self.default_branch.clone(),
187 topics: self.topics.as_deref().map(|topics| {
188 topics
189 .split(',')
190 .map(str::trim)
191 .filter(|topic| !topic.is_empty())
192 .map(str::to_owned)
193 .collect()
194 }),
195 tdm: self.tdm.map(|tdm| tdm.as_str().to_owned()),
196 issues: self.issues.map(Switch::on),
197 requests_from: self.requests_from.map(|from| from.as_str().to_owned()),
198 allow_forks: self.forks.map(Switch::on),
199 require_approvals: self.approvals,
200 mirror_follow: self.follow.map(|follow| follow.as_str().to_owned()),
201 ..RepoPatch::default()
202 }
203 }
204}
205
206pub(crate) fn settings(cli: &Cli, args: &SettingsArgs) -> Result<ExitCode> {
207 let (hub, path) = hub_repo(cli, args.repo.hub_repo.as_deref())?;
208 let patch = args.patch();
209 let route = path.api_path();
210 let asked = if patch == RepoPatch::default() {
211 hub.call_json::<RepoInfo>("GET", &route, &[], None)
212 } else {
213 let body = serde_json::to_value(&patch)?;
214 hub.call_json::<RepoInfo>("PATCH", &route, &[], Some(&body))
215 };
216 let info = match asked {
217 Ok(info) => info,
218 Err(err) => return Ok(failed(&err)),
219 };
220 if args.public && !info.private {
221 eprintln!("braid: {path} is public: {PUBLIC_NOTE}.");
222 }
223 print(cli, &serde_json::to_value(&info)?, || settings_text(&info))?;
224 Ok(ExitCode::SUCCESS)
225}
226
227/// "on" or "off".
228fn on_off(on: bool) -> &'static str {
229 if on { "on" } else { "off" }
230}
231
232/// What `settings` prints without `--json`. What the hub says goes
233/// through [`shown`]: names and descriptions are anyone's text.
234fn settings_text(info: &RepoInfo) -> String {
235 let mut out = format!(
236 "{}/{} ({})",
237 shown(&info.owner),
238 shown(&info.name),
239 if info.private { "private" } else { "public" }
240 );
241 if !info.description.is_empty() {
242 let _ = write!(out, "\nDescription: {}", shown(&info.description));
243 }
244 let _ = write!(out, "\nDefault branch: {}", shown(&info.default_branch));
245 let topics = if info.topics.is_empty() {
246 "none".to_owned()
247 } else {
248 shown(&info.topics.join(", "))
249 };
250 let _ = write!(out, "\nTopics: {topics}");
251 if !info.tdm.is_empty() {
252 let _ = write!(out, "\nText and data mining: {}", shown(&info.tdm));
253 }
254 match &info.mirror {
255 Some(mirror) => {
256 let _ = write!(out, "\nMirror: {}", shown(&mirror.url));
257 }
258 None => out.push_str("\nMirror: none"),
259 }
260 if let Some(settings) = &info.settings {
261 let _ = write!(
262 out,
263 "\nIssues: {}\nChange requests from: {}\nForks: {}\nApprovals needed to land: {}",
264 on_off(settings.issues),
265 shown(&settings.requests_from),
266 on_off(settings.allow_forks),
267 settings.require_approvals
268 );
269 if let Some(follow) = &settings.mirror_follow {
270 let _ = write!(out, "\nMirror followed: {}", shown(follow));
271 }
272 }
273 out
274}
275
276/// `hub block`.
277#[derive(Debug, Args)]
278pub(crate) struct BlockArgs {
279 /// The account to block.
280 #[arg(value_name = "LOGIN")]
281 pub(crate) login: String,
282 /// Block it from this repository alone, OWNER/NAME, which you
283 /// administer (default: from every repository you own).
284 #[arg(short = 'R', long = "hub-repo", value_name = "OWNER/NAME")]
285 pub(crate) hub_repo: Option<String>,
286}
287
288pub(crate) fn block(cli: &Cli, args: &BlockArgs) -> Result<ExitCode> {
289 block_or_not(cli, &args.login, args.hub_repo.as_deref(), true)
290}
291
292/// `hub unblock`.
293#[derive(Debug, Args)]
294pub(crate) struct UnblockArgs {
295 /// The account to unblock.
296 #[arg(value_name = "LOGIN")]
297 pub(crate) login: String,
298 /// Lift the block of this repository, OWNER/NAME, which you administer
299 /// (default: your own block, on every repository you own).
300 #[arg(short = 'R', long = "hub-repo", value_name = "OWNER/NAME")]
301 pub(crate) hub_repo: Option<String>,
302}
303
304pub(crate) fn unblock(cli: &Cli, args: &UnblockArgs) -> Result<ExitCode> {
305 block_or_not(cli, &args.login, args.hub_repo.as_deref(), false)
306}
307
308/// Blocks `login`, or lifts its block: the account's own, or, with
309/// `repo`, that repository's.
310fn block_or_not(cli: &Cli, login: &str, repo: Option<&str>, block: bool) -> Result<ExitCode> {
311 let login = login_arg(login)?;
312 let (hub, route, repo) = match repo {
313 Some(text) => {
314 let (hub, path) = hub_repo(cli, Some(text))?;
315 let route = format!("{}/blocks/{login}", path.api_path());
316 (hub, route, Some(path.to_string()))
317 }
318 None => (signed_in_hub()?, format!("/v1/me/blocks/{login}"), None),
319 };
320 let method = if block { "PUT" } else { "DELETE" };
321 if let Err(err) = hub.call(method, &route, &[], None) {
322 return Ok(failed(&err));
323 }
324 let mut value = json!({"login": login, "blocked": block});
325 if let Some(repo) = &repo {
326 value["repo"] = json!(repo);
327 }
328 print(cli, &value, || match (block, &repo) {
329 (true, None) => format!("Blocked {login} from every repository you own."),
330 (true, Some(repo)) => format!("Blocked {login} from {repo}."),
331 (false, None) => format!("Unblocked {login}."),
332 (false, Some(repo)) => format!("Unblocked {login} on {repo}."),
333 })?;
334 Ok(ExitCode::SUCCESS)
335}
336
337/// `hub account`.
338#[derive(Debug, Args)]
339pub(crate) struct AccountArgs {
340 /// What text and data mining your new repositories start with.
341 #[arg(long, value_enum)]
342 pub(crate) tdm_default: Option<Mining>,
343 /// Whether the repositories you starred show on your profile.
344 #[arg(long, value_enum, value_name = "ON|OFF")]
345 pub(crate) stars_public: Option<Switch>,
346}
347
348pub(crate) fn account(cli: &Cli, args: &AccountArgs) -> Result<ExitCode> {
349 let hub = signed_in_hub()?;
350 let patch = MePatch {
351 tdm_default: args.tdm_default.map(|tdm| tdm.as_str().to_owned()),
352 stars_public: args.stars_public.map(Switch::on),
353 };
354 let asked = if patch == MePatch::default() {
355 hub.call_json::<Me>("GET", "/v1/me", &[], None)
356 } else {
357 let body = serde_json::to_value(&patch)?;
358 hub.call_json::<Me>("PATCH", "/v1/me", &[], Some(&body))
359 };
360 let me = match asked {
361 Ok(me) => me,
362 Err(err) => return Ok(failed(&err)),
363 };
364 print(cli, &serde_json::to_value(&me)?, || account_text(&me))?;
365 Ok(ExitCode::SUCCESS)
366}
367
368/// What `account` prints without `--json`.
369fn account_text(me: &Me) -> String {
370 let mut out = shown(&me.login);
371 if let Some(settings) = &me.settings {
372 let _ = write!(
373 out,
374 "\nStars: {}\nNew repositories start with text and data mining {}",
375 if settings.stars_public {
376 "shown on your profile"
377 } else {
378 "kept private"
379 },
380 shown(&settings.tdm_default)
381 );
382 }
383 match &me.github_scope {
384 Some(scope) if me.github_repo_access => {
385 let _ = write!(out, "\nGitHub access: granted ({})", shown(scope));
386 }
387 _ => out.push_str("\nGitHub access: not granted"),
388 }
389 out
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use braid_hubproto::api::{MeSettings, RepoSettingsInfo};
396
397 #[test]
398 fn flags_make_the_patch() {
399 let args = SettingsArgs {
400 repo: HubRepoArg::default(),
401 public: false,
402 private: true,
403 description: None,
404 default_branch: None,
405 topics: Some(" rust, ,cli ".into()),
406 tdm: Some(Mining::Reserved),
407 issues: Some(Switch::Off),
408 requests_from: Some(RequestsFrom::Collaborators),
409 forks: Some(Switch::On),
410 approvals: Some(2),
411 follow: Some(Follow::FfOnly),
412 };
413 let patch = args.patch();
414 assert_eq!(patch.private, Some(true));
415 assert_eq!(
416 patch.topics.as_deref(),
417 Some(&["rust".to_owned(), "cli".to_owned()][..])
418 );
419 assert_eq!(patch.tdm.as_deref(), Some("reserved"));
420 assert_eq!(patch.issues, Some(false));
421 assert_eq!(patch.requests_from.as_deref(), Some("collaborators"));
422 assert_eq!(patch.allow_forks, Some(true));
423 assert_eq!(patch.require_approvals, Some(2));
424 assert_eq!(patch.mirror_follow.as_deref(), Some("ff-only"));
425 let none = SettingsArgs {
426 private: false,
427 topics: None,
428 tdm: None,
429 issues: None,
430 requests_from: None,
431 forks: None,
432 approvals: None,
433 follow: None,
434 ..args
435 };
436 assert_eq!(none.patch(), RepoPatch::default());
437 // "" clears the topics.
438 let cleared = SettingsArgs {
439 topics: Some(String::new()),
440 ..none
441 };
442 assert_eq!(cleared.patch().topics, Some(Vec::new()));
443 }
444
445 #[test]
446 fn texts_escape_what_the_hub_says() {
447 let info = RepoInfo {
448 owner: "ada".into(),
449 name: "demo".into(),
450 description: "bell\u{7}".into(),
451 default_branch: "main".into(),
452 settings: Some(RepoSettingsInfo {
453 issues: false,
454 requests_from: "readers".into(),
455 allow_forks: true,
456 require_approvals: 1,
457 mirror_follow: None,
458 }),
459 ..RepoInfo::default()
460 };
461 let text = settings_text(&info);
462 assert!(text.starts_with("ada/demo (public)"), "{text}");
463 assert!(!text.contains('\u{7}'), "{text}");
464 assert!(
465 text.contains("Issues: off") && text.contains("Forks: on"),
466 "{text}"
467 );
468 assert!(text.contains("Topics: none"), "{text}");
469 let me = Me {
470 login: "ada".into(),
471 name: None,
472 avatar_url: None,
473 github_repo_access: false,
474 token: None,
475 settings: Some(MeSettings {
476 tdm_default: "reserved".into(),
477 stars_public: false,
478 }),
479 github_scope: None,
480 };
481 let text = account_text(&me);
482 assert!(text.contains("Stars: kept private"), "{text}");
483 assert!(text.contains("mining reserved"), "{text}");
484 assert!(text.ends_with("GitHub access: not granted"), "{text}");
485 assert_eq!(on_off(true), "on");
486 assert!(login_arg("bad--login").is_err());
487 assert_eq!(login_arg("Eve").unwrap(), "eve");
488 }
489}