| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! BraidHub from the client's side (`docs/hub.md`, section 13): `braid |
| 5 | //! login` and `logout`, `braid hub publish`, `clone`, `fetch`, `status`, |
| 6 | //! `whoami` and `autopublish`, and what `land`, `update` and `change create |
| 7 | //! --land` do in a repository linked to a hub. |
| 8 | //! |
| 9 | //! - [`creds`]: hub URLs and tokens, from `hub.json` and the environment. |
| 10 | //! - [`link`]: `.braid/hub`, which links a repository to its hub. |
| 11 | //! - [`remote`]: the trait the transfer logic talks to, and its errors; |
| 12 | //! [`http`] speaks it over HTTP. |
| 13 | //! - [`transfer`], [`fetch`], [`publish`](mod@publish), [`land`]: moving |
| 14 | //! history. |
| 15 | //! - [`device`]: waiting for a device-flow sign-in; [`status`]: how |
| 16 | //! branches compare. |
| 17 | //! - [`browse`], [`history`], [`explore`], [`social`], [`issue`], |
| 18 | //! [`inbox`], [`fork`], [`request`], [`github`] and [`settings`]: reading |
| 19 | //! a repository without cloning it, finding repositories, stars, |
| 20 | //! watching and following, issues, the inbox, forks, change requests, |
| 21 | //! GitHub sync and settings; [`social_common`]: what they share; [`api`]: |
| 22 | //! any route of the API. |
| 23 | //! - [`mod@verify`]: keeping a repository's default branch green. |
| 24 | |
| 25 | pub(crate) mod api; |
| 26 | pub(crate) mod browse; |
| 27 | pub(crate) mod creds; |
| 28 | pub(crate) mod device; |
| 29 | pub(crate) mod explore; |
| 30 | pub(crate) mod fetch; |
| 31 | pub(crate) mod fork; |
| 32 | pub(crate) mod github; |
| 33 | pub(crate) mod history; |
| 34 | pub(crate) mod http; |
| 35 | pub(crate) mod inbox; |
| 36 | pub(crate) mod issue; |
| 37 | pub(crate) mod land; |
| 38 | pub(crate) mod link; |
| 39 | pub(crate) mod publish; |
| 40 | pub(crate) mod remote; |
| 41 | pub(crate) mod request; |
| 42 | #[cfg(test)] |
| 43 | mod resilience_tests; |
| 44 | pub(crate) mod settings; |
| 45 | pub(crate) mod social; |
| 46 | pub(crate) mod social_common; |
| 47 | pub(crate) mod status; |
| 48 | #[cfg(test)] |
| 49 | pub(crate) mod testing; |
| 50 | pub(crate) mod transfer; |
| 51 | pub(crate) mod verify; |
| 52 | |
| 53 | use std::fs; |
| 54 | use std::io; |
| 55 | use std::path::{Path, PathBuf}; |
| 56 | use std::process::ExitCode; |
| 57 | |
| 58 | use anyhow::{Context, Result, bail}; |
| 59 | use braid_hubproto::api::RepoCreate; |
| 60 | use braid_hubproto::names::is_repo_name; |
| 61 | use braid_hubproto::{RepoPath, Token}; |
| 62 | use braid_repo::{Repo, WorkspaceLink}; |
| 63 | use braid_wc::Workspace; |
| 64 | use clap::{Args, Subcommand}; |
| 65 | use serde_json::{Value, json}; |
| 66 | |
| 67 | use crate::work::{branches, count, hex, short}; |
| 68 | use crate::{Cli, open_repo, print_json}; |
| 69 | use creds::{Credentials, HubEnv, Saved, TokenSource}; |
| 70 | use fetch::{Fetched, Outcome, RefFetched, is_tag}; |
| 71 | use http::HttpHub; |
| 72 | use link::Link; |
| 73 | use remote::{HubError, Remote}; |
| 74 | |
| 75 | /// The long help of `login`. |
| 76 | pub(crate) const LOGIN_HELP: &str = |
| 77 | "Sign in to a hub with GitHub's device flow, run through the hub, so that |
| 78 | no browser is needed on this machine: braid prints a web address and a code |
| 79 | on standard error; open the address anywhere, enter the code and approve. |
| 80 | braid polls the hub until then, at the interval it asks for, and saves the |
| 81 | token it gets. |
| 82 | |
| 83 | The token is saved in hub.json in braid's configuration directory |
| 84 | ($XDG_CONFIG_HOME/braid, or ~/.config/braid), which only you can read, and |
| 85 | that hub becomes the one `braid hub publish` and `braid hub clone` use. The |
| 86 | token reads, writes and lands on every repository the account can, for 90 |
| 87 | days. BRAID_TOKEN and BRAID_HUB_URL take precedence over the file: an agent |
| 88 | or CI job can set them instead of signing in. |
| 89 | |
| 90 | The hub is --hub, else BRAID_HUB_URL, else the hub signed in to last, else |
| 91 | https://braidhub.elffuss.com. Only https:// is taken, and http:// to this |
| 92 | machine. |
| 93 | |
| 94 | With --json it prints hub, login and expires."; |
| 95 | |
| 96 | /// The long help of `logout`. |
| 97 | pub(crate) const LOGOUT_HELP: &str = |
| 98 | "Revoke the token saved for a hub, on the hub when it can be reached, and |
| 99 | delete it here. BRAID_TOKEN is left alone: unset it yourself. |
| 100 | |
| 101 | With --json it prints hub, signed_in (whether a token was saved), revoked |
| 102 | (whether the hub revoked it) and detail (why it could not, or null)."; |
| 103 | |
| 104 | /// The long help of `hub publish`. |
| 105 | pub(crate) const PUBLISH_HELP: &str = |
| 106 | "Create the repository on the hub signed in to, upload every branch and |
| 107 | tag, and link the repository to it: .braid/hub names the hub and the |
| 108 | repository, and from then on `braid land`, `braid update` and `braid change |
| 109 | create --land` go through the hub. |
| 110 | |
| 111 | NAME defaults to the name of the repository's directory, made valid: 1 to |
| 112 | 100 ASCII letters, digits, '.', '_' and '-'. The repository is private |
| 113 | unless --public. --mirror names a git repository the hub publishes the |
| 114 | default branch to after each landing, with the account's GitHub access. |
| 115 | |
| 116 | What the branches and tags reach is uploaded, less what the hub has, in |
| 117 | requests no larger than the hub takes (it says so, at most 256 MiB), or |
| 118 | than BRAID_HUB_MAX_BODY bytes, for a proxy in front of the hub that takes |
| 119 | less; and each ref is created on the hub at its head. |
| 120 | A ref that names no changeset, such as an annotated tag imported from git, |
| 121 | cannot be created through the hub protocol: it is reported and skipped. If |
| 122 | an upload fails, run the command again: in a linked repository it uploads |
| 123 | what the hub lacks and creates the refs it misses. |
| 124 | |
| 125 | With --json it prints hub, repo, url (the repository's address on the hub, |
| 126 | <hub>/<owner>/<name>), created (whether the repository was made now), |
| 127 | objects and bytes (what was uploaded), refs (each with name, id, outcome, |
| 128 | head_before and head) and skipped (each with name and reason)."; |
| 129 | |
| 130 | /// The long help of `hub clone`. |
| 131 | pub(crate) const CLONE_HELP: &str = |
| 132 | "Make a repository in DIR (default: NAME, in the current directory) from |
| 133 | OWNER/NAME on the hub, linked to it, with every branch and tag, and a |
| 134 | first workspace in .braid/work/<name> on the hub's default branch, named by |
| 135 | --workspace, or else after the branch. |
| 136 | |
| 137 | --paths takes path prefixes: only the trees under them come, with the |
| 138 | directories on the way to them. Such a sparse repository serves `braid |
| 139 | cat-object`, `braid log` and `braid change create --land`, but holds no |
| 140 | workspace, since a workspace is a whole checkout. Give DIR before --paths. |
| 141 | |
| 142 | The hub is BRAID_HUB_URL, else the hub signed in to last, else |
| 143 | https://braidhub.elffuss.com. A public repository needs no sign-in. |
| 144 | |
| 145 | With --json it prints hub, repo, root, paths, objects, refs (as `braid hub |
| 146 | fetch` prints them) and workspace (name, path, branch, base and files, or |
| 147 | null)."; |
| 148 | |
| 149 | /// The long help of `hub fetch`. |
| 150 | pub(crate) const FETCH_HELP: &str = |
| 151 | "Bring the hub's branches and tags into the linked repository. A local |
| 152 | branch moves to the hub's head when it does not exist yet, or when its head |
| 153 | is on the first-parent chain of the hub's; a branch with changesets the hub |
| 154 | does not have stays where it is, and is reported as ahead or diverged. A |
| 155 | tag is created, and never moved. remote/hub/<ref> records where each of the |
| 156 | hub's refs was seen, so `braid log remote/hub/main` shows the hub's main |
| 157 | even when the local one was kept back. Tags that name no changeset are |
| 158 | skipped: the hub protocol carries changesets only. Of the hub's own refs, |
| 159 | only braid/green/<branch> and braid/red/<branch>, which say how the hub |
| 160 | verifies a branch, are recorded so (remote/hub/braid/green/<branch>), and |
| 161 | `braid status --json` gives them as hub_green and hub_red. |
| 162 | |
| 163 | `braid land` and `braid update` fetch by themselves in a linked repository. |
| 164 | |
| 165 | With --json it prints hub, repo, seq (the hub's op log sequence number), |
| 166 | objects (how many came), operation (the local op log operation that moved |
| 167 | refs, or null) and refs, each with name, hub, before, after and outcome: |
| 168 | created, moved, same, ahead, diverged, or skipped with a reason."; |
| 169 | |
| 170 | /// The long help of `hub status`. |
| 171 | pub(crate) const STATUS_HELP: &str = |
| 172 | "Show the hub and the repository this one is linked to, who is signed in, |
| 173 | and how each branch compares with the hub's: same; behind, when the hub's |
| 174 | has changesets on top of this one (`braid hub fetch` brings them in); |
| 175 | ahead, when this one has changesets the hub lacks (`braid land` from a |
| 176 | workspace on the branch sends them); or diverged. A branch only the hub has |
| 177 | is behind, and one only this repository has is ahead. |
| 178 | |
| 179 | A repository with a mirror shows where the hub publishes its default |
| 180 | branch, and how the last sync ended: diverged means someone pushed to the |
| 181 | mirror directly, and the hub's owner takes those commits in on the hub. |
| 182 | |
| 183 | A branch the hub verifies shows its green, the newest changeset with a pass |
| 184 | the hub accepts, and while the hub holds it red, its red (`braid hub verify |
| 185 | status` says more). |
| 186 | |
| 187 | With --json it prints hub, repo, paths, login (null when not signed in), |
| 188 | token (environment, file or null), mirror (url, last_sync, outcome and |
| 189 | detail, or null), seq (the hub's op log sequence number) and branches, each |
| 190 | with name, local, hub, state, green and red (null when the hub has none)."; |
| 191 | |
| 192 | /// The long help of `hub whoami`. |
| 193 | pub(crate) const WHOAMI_HELP: &str = |
| 194 | "Say who is signed in to the hub, as the hub sees the token: the account's |
| 195 | login and when the token expires (GET /v1/me). The exit status is 1 when no |
| 196 | token is saved for the hub and BRAID_TOKEN is not set for it, or when the |
| 197 | hub refuses the token because it expired or was revoked: then `braid login` |
| 198 | is needed. It is 3 when braid cannot tell, because the hub cannot be reached |
| 199 | or failed, or its answer is not one: then signing in again would not help. |
| 200 | |
| 201 | The hub is the one `braid login` signs in to: --hub, else BRAID_HUB_URL, |
| 202 | else the hub signed in to last, else https://braidhub.elffuss.com. |
| 203 | |
| 204 | With --json it prints hub, login, name (or null), expires and token (where |
| 205 | the token came from: environment or file)."; |
| 206 | |
| 207 | /// The long help of `hub autopublish`. |
| 208 | pub(crate) const AUTOPUBLISH_HELP: &str = |
| 209 | "Say, or record, whether coding agents publish the new projects they start |
| 210 | for you to the hub, privately, so that agents on your other machines can |
| 211 | work on them too. With no argument it prints on, off or unset; on or off |
| 212 | records the answer, and prints it. The answer holds for every project and |
| 213 | every hub, and is kept in hub.json, next to the tokens. |
| 214 | |
| 215 | braid never publishes by itself: an agent reads the answer, and runs `braid |
| 216 | hub publish` when it is on (the hub's guide for agents, /agents.md, says |
| 217 | when). |
| 218 | |
| 219 | With --json it prints autopublish: on, off or unset."; |
| 220 | |
| 221 | /// `login` and `logout`. |
| 222 | #[derive(Debug, Args)] |
| 223 | pub(crate) struct LoginArgs { |
| 224 | /// The hub (default: BRAID_HUB_URL, else the hub signed in to last, |
| 225 | /// else the public hub). |
| 226 | #[arg(long, value_name = "URL")] |
| 227 | pub(crate) hub: Option<String>, |
| 228 | } |
| 229 | |
| 230 | /// `braid hub`. |
| 231 | #[derive(Debug, Subcommand)] |
| 232 | pub(crate) enum HubAction { |
| 233 | /// Create the repository on the hub, upload every branch and tag, and |
| 234 | /// link this repository to it. |
| 235 | #[command(long_about = PUBLISH_HELP)] |
| 236 | Publish(PublishArgs), |
| 237 | /// Make a repository from one on the hub, linked to it. |
| 238 | #[command(long_about = CLONE_HELP)] |
| 239 | Clone(CloneArgs), |
| 240 | /// Bring the hub's branches and tags in, moving local branches forward. |
| 241 | #[command(long_about = FETCH_HELP)] |
| 242 | Fetch, |
| 243 | /// Show the link, who is signed in, and how each branch compares. |
| 244 | #[command(long_about = STATUS_HELP)] |
| 245 | Status, |
| 246 | /// Say who is signed in to the hub (exit status 1 when no one is). |
| 247 | #[command(long_about = WHOAMI_HELP)] |
| 248 | Whoami(LoginArgs), |
| 249 | /// Say, or record, whether agents publish the new projects they start. |
| 250 | #[command(long_about = AUTOPUBLISH_HELP)] |
| 251 | Autopublish(AutopublishArgs), |
| 252 | /// Show a repository on the hub: its description, default branch, |
| 253 | /// counts and README. |
| 254 | Show(browse::ShowArgs), |
| 255 | /// List a directory of a repository on the hub, without cloning it. |
| 256 | Ls(browse::LsArgs), |
| 257 | /// Print a file of a repository on the hub, without cloning it. |
| 258 | Cat(browse::CatArgs), |
| 259 | /// Show the changesets of a branch on the hub, newest first. |
| 260 | Log(history::LogArgs), |
| 261 | /// Show what a changeset on the hub changed. |
| 262 | Diff(history::DiffArgs), |
| 263 | /// Find public repositories on the hub. |
| 264 | Explore(explore::ExploreArgs), |
| 265 | /// Show an account on the hub: its repositories, stars and follows. |
| 266 | User(explore::UserArgs), |
| 267 | /// Star a repository. |
| 268 | Star(social::StarArgs), |
| 269 | /// Take back a star. |
| 270 | Unstar(social::UnstarArgs), |
| 271 | /// List the repositories you, or an account, starred. |
| 272 | Stars(social::StarsArgs), |
| 273 | /// Watch a repository: all of it, what you take part in, or nothing. |
| 274 | Watch(social::WatchArgs), |
| 275 | /// Stop watching a repository: back to what you take part in. |
| 276 | Unwatch(social::UnwatchArgs), |
| 277 | /// Follow an account. |
| 278 | Follow(social::FollowArgs), |
| 279 | /// Stop following an account. |
| 280 | Unfollow(social::UnfollowArgs), |
| 281 | /// List, show, open, comment on and close a repository's issues. |
| 282 | Issue(issue::IssueArgs), |
| 283 | /// List, create and delete a repository's labels. |
| 284 | Label(issue::LabelArgs), |
| 285 | /// Show your notifications; mark them read or done; mute a thread. |
| 286 | Inbox(inbox::InboxArgs), |
| 287 | /// Fork a repository into your account. |
| 288 | Fork(fork::ForkArgs), |
| 289 | /// Bring what the upstream of a fork landed into the fork. |
| 290 | SyncFork(fork::SyncForkArgs), |
| 291 | /// Show your jobs, such as forks being made, or wait for one. |
| 292 | Jobs(fork::JobsArgs), |
| 293 | /// Open, review, update and land change requests. |
| 294 | #[command(long_about = request::REQUEST_HELP)] |
| 295 | Request(request::RequestArgs), |
| 296 | /// Grant the hub GitHub access, and sync your GitHub repositories to |
| 297 | /// it. |
| 298 | Github(github::GithubArgs), |
| 299 | /// Show or change a repository's settings. |
| 300 | Settings(settings::SettingsArgs), |
| 301 | /// Block an account from your repositories, or from one of them. |
| 302 | Block(settings::BlockArgs), |
| 303 | /// Lift a block. |
| 304 | Unblock(settings::UnblockArgs), |
| 305 | /// Show or change your account's settings. |
| 306 | Account(settings::AccountArgs), |
| 307 | /// Keep a repository's default branch green: its status, what CI |
| 308 | /// reports, the policy, the log and resets. |
| 309 | #[command(long_about = verify::VERIFY_HELP)] |
| 310 | Verify(verify::VerifyArgs), |
| 311 | /// Send a request to the hub's API and print its answer. |
| 312 | #[command(long_about = api::API_HELP)] |
| 313 | Api(api::ApiArgs), |
| 314 | } |
| 315 | |
| 316 | /// `hub autopublish`. |
| 317 | #[derive(Debug, Args)] |
| 318 | pub(crate) struct AutopublishArgs { |
| 319 | /// Record the answer (default: print it). |
| 320 | #[arg(value_enum)] |
| 321 | pub(crate) answer: Option<Switch>, |
| 322 | } |
| 323 | |
| 324 | /// An answer to `hub autopublish`. |
| 325 | #[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)] |
| 326 | pub(crate) enum Switch { |
| 327 | /// Agents publish the new projects they start, privately. |
| 328 | On, |
| 329 | /// Agents publish only when asked. |
| 330 | Off, |
| 331 | } |
| 332 | |
| 333 | /// `hub publish`. |
| 334 | #[derive(Debug, Args)] |
| 335 | pub(crate) struct PublishArgs { |
| 336 | /// The repository's name on the hub (default: the directory's name, |
| 337 | /// made valid). |
| 338 | pub(crate) name: Option<String>, |
| 339 | /// Let anyone read it. |
| 340 | #[arg(long)] |
| 341 | pub(crate) public: bool, |
| 342 | /// A description, for people. |
| 343 | #[arg(long, value_name = "TEXT")] |
| 344 | pub(crate) description: Option<String>, |
| 345 | /// A git repository the hub publishes the default branch to after each |
| 346 | /// landing. |
| 347 | #[arg(long, value_name = "URL")] |
| 348 | pub(crate) mirror: Option<String>, |
| 349 | } |
| 350 | |
| 351 | /// `hub clone`. |
| 352 | #[derive(Debug, Args)] |
| 353 | pub(crate) struct CloneArgs { |
| 354 | // Not named `repo`: that is the id of the global --repo. |
| 355 | /// The repository: OWNER/NAME. |
| 356 | #[arg(value_name = "OWNER/NAME")] |
| 357 | pub(crate) source: String, |
| 358 | /// The directory to make it in, which must not exist or be empty |
| 359 | /// (default: NAME). |
| 360 | pub(crate) dir: Option<PathBuf>, |
| 361 | /// Take only the trees under these path prefixes. |
| 362 | #[arg(long, value_name = "PREFIX", num_args = 1..)] |
| 363 | pub(crate) paths: Vec<String>, |
| 364 | } |
| 365 | |
| 366 | pub(crate) fn hub(cli: &Cli, action: &HubAction) -> Result<ExitCode> { |
| 367 | match action { |
| 368 | HubAction::Publish(args) => publish(cli, args), |
| 369 | HubAction::Clone(args) => clone(cli, args), |
| 370 | HubAction::Fetch => fetch_command(cli), |
| 371 | HubAction::Status => status_command(cli), |
| 372 | HubAction::Whoami(args) => whoami(cli, args), |
| 373 | HubAction::Autopublish(args) => autopublish(cli, args), |
| 374 | HubAction::Show(args) => browse::show(cli, args), |
| 375 | HubAction::Ls(args) => browse::ls(cli, args), |
| 376 | HubAction::Cat(args) => browse::cat(cli, args), |
| 377 | HubAction::Log(args) => history::log(cli, args), |
| 378 | HubAction::Diff(args) => history::diff(cli, args), |
| 379 | HubAction::Explore(args) => explore::explore(cli, args), |
| 380 | HubAction::User(args) => explore::user(cli, args), |
| 381 | HubAction::Star(args) => social::star(cli, args), |
| 382 | HubAction::Unstar(args) => social::unstar(cli, args), |
| 383 | HubAction::Stars(args) => social::stars(cli, args), |
| 384 | HubAction::Watch(args) => social::watch(cli, args), |
| 385 | HubAction::Unwatch(args) => social::unwatch(cli, args), |
| 386 | HubAction::Follow(args) => social::follow(cli, args), |
| 387 | HubAction::Unfollow(args) => social::unfollow(cli, args), |
| 388 | HubAction::Issue(args) => issue::issue(cli, args), |
| 389 | HubAction::Label(args) => issue::label(cli, args), |
| 390 | HubAction::Inbox(args) => inbox::inbox(cli, args), |
| 391 | HubAction::Fork(args) => fork::fork(cli, args), |
| 392 | HubAction::SyncFork(args) => fork::sync_fork(cli, args), |
| 393 | HubAction::Jobs(args) => fork::jobs(cli, args), |
| 394 | HubAction::Request(args) => request::request(cli, args), |
| 395 | HubAction::Github(args) => github::github(cli, args), |
| 396 | HubAction::Settings(args) => settings::settings(cli, args), |
| 397 | HubAction::Block(args) => settings::block(cli, args), |
| 398 | HubAction::Unblock(args) => settings::unblock(cli, args), |
| 399 | HubAction::Account(args) => settings::account(cli, args), |
| 400 | HubAction::Verify(args) => verify::verify(cli, args), |
| 401 | HubAction::Api(args) => api::api(cli, args), |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// A client for the hub at `url`, with the token the environment or the |
| 406 | /// credentials file give for it, if any. |
| 407 | fn client(env: &HubEnv, url: &str) -> Result<(HttpHub, TokenSource)> { |
| 408 | let creds = env.credentials()?; |
| 409 | let (token, source) = creds::token_for(env, &creds, url)?; |
| 410 | let hub = HttpHub::new(url, token)? |
| 411 | .with_max_body(env.max_body()?) |
| 412 | .with_source(source) |
| 413 | .with_withheld(creds::withheld_for(env, &creds, url)); |
| 414 | Ok((hub, source)) |
| 415 | } |
| 416 | |
| 417 | /// A client for the hub a repository is linked to. |
| 418 | pub(crate) fn connect(link: &Link) -> Result<HttpHub> { |
| 419 | Ok(client(&HubEnv::from_process(), &link.url)?.0) |
| 420 | } |
| 421 | |
| 422 | /// The hub `repo` lands on: its link, unless `local` or `BRAID_HUB=off` |
| 423 | /// keeps the command in this repository. |
| 424 | pub(crate) fn linked(repo: &Repo, local: bool) -> Result<Option<Link>> { |
| 425 | if local || HubEnv::from_process().hub_off()? { |
| 426 | return Ok(None); |
| 427 | } |
| 428 | Link::read(repo) |
| 429 | } |
| 430 | |
| 431 | /// The link of a repository that must have one. |
| 432 | fn require_link(repo: &Repo) -> Result<Link> { |
| 433 | Link::read(repo)?.context( |
| 434 | "this repository is not linked to a hub: `braid hub publish` puts it on one, and `braid hub clone` makes a linked one", |
| 435 | ) |
| 436 | } |
| 437 | |
| 438 | /// ` --hub <url>`, or nothing for the hub used by default. |
| 439 | fn hub_flag(url: &str) -> String { |
| 440 | if url == braid_hubproto::DEFAULT_HUB_URL { |
| 441 | String::new() |
| 442 | } else { |
| 443 | format!(" --hub {url}") |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | pub(crate) fn login(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> { |
| 448 | let env = HubEnv::from_process(); |
| 449 | let path = env.credentials_path()?; |
| 450 | let mut creds = Credentials::load(&path)?; |
| 451 | let url = creds::hub_url(&env, &creds, args.hub.as_deref())?; |
| 452 | let hub = HttpHub::new(&url, None)?; |
| 453 | let start = hub.device_start()?; |
| 454 | eprintln!( |
| 455 | "To sign in to {url}, open {} and enter the code {}", |
| 456 | remote::shown(&start.verification_uri), |
| 457 | remote::shown(&start.user_code) |
| 458 | ); |
| 459 | eprintln!( |
| 460 | "Waiting for the approval; the code expires in {}.", |
| 461 | count(start.expires_in.div_ceil(60), "minute") |
| 462 | ); |
| 463 | let signed = device::wait_for_approval(&hub, &start, std::thread::sleep)?; |
| 464 | let replaced = creds.hubs.insert( |
| 465 | url.clone(), |
| 466 | Saved { |
| 467 | token: signed.token.expose(), |
| 468 | login: signed.login.clone(), |
| 469 | expires: signed.expires.clone(), |
| 470 | }, |
| 471 | ); |
| 472 | creds.default = Some(url.clone()); |
| 473 | creds.save(&path)?; |
| 474 | if env.token.is_some() { |
| 475 | eprintln!("braid: note: BRAID_TOKEN is set, and commands use it rather than this token"); |
| 476 | } |
| 477 | // The token this one replaces is revoked, so that signing in again |
| 478 | // leaves no live token behind; one the hub refuses is gone already. |
| 479 | let revoked_before = match replaced { |
| 480 | Some(old) if old.token != signed.token.expose() => match revoke_token(&url, &old) { |
| 481 | Ok(()) => true, |
| 482 | Err(err) => { |
| 483 | if !err |
| 484 | .downcast_ref::<HubError>() |
| 485 | .is_some_and(HubError::unauthorized) |
| 486 | { |
| 487 | eprintln!( |
| 488 | "braid: note: the token saved before for {url} could not be revoked ({err:#}); it stops working when it expires" |
| 489 | ); |
| 490 | } |
| 491 | false |
| 492 | } |
| 493 | }, |
| 494 | _ => false, |
| 495 | }; |
| 496 | if cli.json { |
| 497 | print_json(&json!({ |
| 498 | "hub": url, |
| 499 | "login": signed.login, |
| 500 | "expires": signed.expires, |
| 501 | }))?; |
| 502 | } else { |
| 503 | println!( |
| 504 | "Signed in to {url} as {}; the token expires {}", |
| 505 | remote::shown(&signed.login), |
| 506 | remote::shown(&signed.expires) |
| 507 | ); |
| 508 | if revoked_before { |
| 509 | println!("The token saved before was revoked on the hub."); |
| 510 | } |
| 511 | } |
| 512 | Ok(ExitCode::SUCCESS) |
| 513 | } |
| 514 | |
| 515 | pub(crate) fn logout(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> { |
| 516 | let env = HubEnv::from_process(); |
| 517 | let path = env.credentials_path()?; |
| 518 | let mut creds = Credentials::load(&path)?; |
| 519 | let url = creds::hub_url(&env, &creds, args.hub.as_deref())?; |
| 520 | if env.token.is_some() { |
| 521 | eprintln!("braid: note: BRAID_TOKEN is set; logout leaves it alone"); |
| 522 | } |
| 523 | let Some(saved) = creds.hubs.remove(&url) else { |
| 524 | if cli.json { |
| 525 | print_json(&json!({ |
| 526 | "hub": url, |
| 527 | "signed_in": false, |
| 528 | "revoked": false, |
| 529 | "detail": null, |
| 530 | }))?; |
| 531 | } else { |
| 532 | println!("Not signed in to {url}: no token is saved for it"); |
| 533 | } |
| 534 | return Ok(ExitCode::SUCCESS); |
| 535 | }; |
| 536 | let revoked = revoke(&url, &saved); |
| 537 | if creds.default.as_deref() == Some(url.as_str()) { |
| 538 | creds.default = None; |
| 539 | } |
| 540 | creds.save(&path)?; |
| 541 | if cli.json { |
| 542 | print_json(&json!({ |
| 543 | "hub": url, |
| 544 | "signed_in": true, |
| 545 | "revoked": revoked.is_ok(), |
| 546 | "detail": revoked.as_ref().err(), |
| 547 | }))?; |
| 548 | } else { |
| 549 | match &revoked { |
| 550 | Ok(()) => { |
| 551 | println!("Signed out of {url}: the hub revoked the token, and it was deleted here") |
| 552 | } |
| 553 | Err(why) => println!( |
| 554 | "Signed out of {url}: the token was deleted here, but the hub did not revoke it ({why}); it stops working when it expires{}", |
| 555 | if saved.expires.is_empty() { |
| 556 | String::new() |
| 557 | } else { |
| 558 | format!(", {}", saved.expires) |
| 559 | } |
| 560 | ), |
| 561 | } |
| 562 | } |
| 563 | Ok(ExitCode::SUCCESS) |
| 564 | } |
| 565 | |
| 566 | fn whoami(cli: &Cli, args: &LoginArgs) -> Result<ExitCode> { |
| 567 | let env = HubEnv::from_process(); |
| 568 | let creds = env.credentials()?; |
| 569 | let url = creds::hub_url(&env, &creds, args.hub.as_deref())?; |
| 570 | let (token, source) = creds::token_for(&env, &creds, &url)?; |
| 571 | if token.is_none() { |
| 572 | match creds::withheld_for(&env, &creds, &url) { |
| 573 | Some(meant) => bail!( |
| 574 | "no one is signed in to {url}: BRAID_TOKEN is for {meant}; set BRAID_HUB_URL={url} to use it with this hub, or run `braid login{}`", |
| 575 | hub_flag(&url) |
| 576 | ), |
| 577 | None => bail!( |
| 578 | "no one is signed in to {url}: run `braid login{}`, or set BRAID_TOKEN", |
| 579 | hub_flag(&url) |
| 580 | ), |
| 581 | } |
| 582 | } |
| 583 | let hub = HttpHub::new(&url, token)?.with_source(source); |
| 584 | let me = match hub.me() { |
| 585 | Ok(me) => me, |
| 586 | Err(HubError::Api { status: 401, body }) => match source { |
| 587 | TokenSource::Environment => bail!( |
| 588 | "the hub at {url} refused BRAID_TOKEN ({}): it expired or was revoked; set another, or unset it and run `braid login{}`", |
| 589 | remote::shown(&body.detail), |
| 590 | hub_flag(&url) |
| 591 | ), |
| 592 | _ => bail!( |
| 593 | "the hub at {url} refused the token saved for it ({}): it expired or was revoked; run `braid login{}`", |
| 594 | remote::shown(&body.detail), |
| 595 | hub_flag(&url) |
| 596 | ), |
| 597 | }, |
| 598 | Err(err @ HubError::Refused { .. }) => return Err(err.into()), |
| 599 | // Neither yes nor no: the hub did not say whether the token is |
| 600 | // good, so signing in again would not help. Its own exit status |
| 601 | // keeps `braid login` for when it does. |
| 602 | Err(err) => { |
| 603 | eprintln!( |
| 604 | "braid: error: cannot tell who is signed in to {url}: {err}; try again once the hub answers" |
| 605 | ); |
| 606 | return Ok(ExitCode::from(CANNOT_TELL)); |
| 607 | } |
| 608 | }; |
| 609 | let expires = me.token.as_ref().map(|info| info.expires.clone()); |
| 610 | if cli.json { |
| 611 | print_json(&json!({ |
| 612 | "hub": url, |
| 613 | "login": me.login, |
| 614 | "name": me.name, |
| 615 | "expires": expires, |
| 616 | "token": source.code(), |
| 617 | }))?; |
| 618 | return Ok(ExitCode::SUCCESS); |
| 619 | } |
| 620 | let from = match source { |
| 621 | TokenSource::Environment => " (BRAID_TOKEN)", |
| 622 | _ => "", |
| 623 | }; |
| 624 | let login = remote::shown(&me.login); |
| 625 | match expires { |
| 626 | Some(expires) => println!( |
| 627 | "Signed in to {url} as {login}{from}; the token expires {}", |
| 628 | remote::shown(&expires) |
| 629 | ), |
| 630 | None => println!("Signed in to {url} as {login}{from}"), |
| 631 | } |
| 632 | Ok(ExitCode::SUCCESS) |
| 633 | } |
| 634 | |
| 635 | /// The exit status of `hub whoami` when the hub did not say whether the |
| 636 | /// token is good: it could not be reached, failed, or did not answer as |
| 637 | /// the protocol says. |
| 638 | const CANNOT_TELL: u8 = 3; |
| 639 | |
| 640 | fn autopublish(cli: &Cli, args: &AutopublishArgs) -> Result<ExitCode> { |
| 641 | let env = HubEnv::from_process(); |
| 642 | let creds = match args.answer { |
| 643 | Some(answer) => { |
| 644 | let path = env.credentials_path()?; |
| 645 | let mut creds = Credentials::load(&path)?; |
| 646 | creds.autopublish = Some(answer == Switch::On); |
| 647 | creds.save(&path)?; |
| 648 | creds |
| 649 | } |
| 650 | None => env.credentials()?, |
| 651 | }; |
| 652 | let answer = match creds.autopublish { |
| 653 | Some(true) => "on", |
| 654 | Some(false) => "off", |
| 655 | None => "unset", |
| 656 | }; |
| 657 | if cli.json { |
| 658 | print_json(&json!({ "autopublish": answer }))?; |
| 659 | } else { |
| 660 | println!("{answer}"); |
| 661 | } |
| 662 | Ok(ExitCode::SUCCESS) |
| 663 | } |
| 664 | |
| 665 | /// Revokes a saved token on its hub, saying why it could not. |
| 666 | fn revoke(url: &str, saved: &Saved) -> Result<(), String> { |
| 667 | revoke_token(url, saved).map_err(|err| format!("{err:#}")) |
| 668 | } |
| 669 | |
| 670 | /// Revokes a saved token on its hub: `GET /v1/me` names its id, and |
| 671 | /// `DELETE /v1/tokens/{id}` revokes it. |
| 672 | fn revoke_token(url: &str, saved: &Saved) -> Result<()> { |
| 673 | let token = Token::parse(&saved.token) |
| 674 | .map_err(|_| anyhow::anyhow!("the saved token is not a braid hub token"))?; |
| 675 | let own_id = token.id().to_owned(); |
| 676 | let hub = HttpHub::new(url, Some(token))?; |
| 677 | let me = hub.me()?; |
| 678 | let id = me.token.map_or(own_id, |info| info.id); |
| 679 | hub.delete_token(&id)?; |
| 680 | Ok(()) |
| 681 | } |
| 682 | |
| 683 | /// A repository name made from `text`, such as a directory's name: every |
| 684 | /// character other than ASCII letters, digits, `.`, `_` and `-` becomes |
| 685 | /// `-`, a run of `-` one, and a leading `.` or `-`, a trailing `-` and a |
| 686 | /// trailing `.git` go; at most 100 characters stay. |
| 687 | pub(crate) fn repo_name_from(text: &str) -> String { |
| 688 | let mut name = String::new(); |
| 689 | for c in text.chars() { |
| 690 | let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { |
| 691 | c |
| 692 | } else { |
| 693 | '-' |
| 694 | }; |
| 695 | if !(c == '-' && name.ends_with('-')) { |
| 696 | name.push(c); |
| 697 | } |
| 698 | } |
| 699 | let mut name = name.trim_start_matches(['.', '-']).to_owned(); |
| 700 | loop { |
| 701 | let trimmed = name.trim_end_matches('-').len(); |
| 702 | name.truncate(trimmed); |
| 703 | if name.to_ascii_lowercase().ends_with(".git") { |
| 704 | name.truncate(name.len() - 4); |
| 705 | } else { |
| 706 | break; |
| 707 | } |
| 708 | } |
| 709 | // Only ASCII is left, so this cuts between characters. |
| 710 | name.truncate(100); |
| 711 | name |
| 712 | } |
| 713 | |
| 714 | fn publish(cli: &Cli, args: &PublishArgs) -> Result<ExitCode> { |
| 715 | let repo = open_repo(cli)?; |
| 716 | let env = HubEnv::from_process(); |
| 717 | let existing = Link::read(&repo)?; |
| 718 | let creds = env.credentials()?; |
| 719 | let url = match &existing { |
| 720 | Some(link) => link.url.clone(), |
| 721 | None => creds::hub_url(&env, &creds, None)?, |
| 722 | }; |
| 723 | let (token, _) = creds::token_for(&env, &creds, &url)?; |
| 724 | if token.is_none() { |
| 725 | bail!( |
| 726 | "publishing needs signing in to {url}: run `braid login{}`, or set BRAID_TOKEN", |
| 727 | hub_flag(&url) |
| 728 | ); |
| 729 | } |
| 730 | if let Some(mirror) = &args.mirror |
| 731 | && let Some((_, rest)) = mirror.split_once("://") |
| 732 | && rest |
| 733 | .split('/') |
| 734 | .next() |
| 735 | .is_some_and(|host| host.contains('@')) |
| 736 | { |
| 737 | bail!( |
| 738 | "the mirror URL holds a user name or password: give it without, as the hub pushes with the account's GitHub access" |
| 739 | ); |
| 740 | } |
| 741 | let hub = HttpHub::new(&url, token)?.with_max_body(env.max_body()?); |
| 742 | let (link, created) = match existing { |
| 743 | Some(link) => { |
| 744 | if args.public || args.description.is_some() || args.mirror.is_some() { |
| 745 | bail!( |
| 746 | "this repository is published already, as {} on {}: --public, --description and --mirror apply only when it is created", |
| 747 | link.repo, |
| 748 | link.url |
| 749 | ); |
| 750 | } |
| 751 | if let Some(name) = &args.name |
| 752 | && *name != link.repo.name |
| 753 | { |
| 754 | bail!( |
| 755 | "this repository is published already, as {} on {}", |
| 756 | link.repo, |
| 757 | link.url |
| 758 | ); |
| 759 | } |
| 760 | (link, false) |
| 761 | } |
| 762 | None => { |
| 763 | let name = match &args.name { |
| 764 | Some(name) if is_repo_name(name) => name.clone(), |
| 765 | Some(name) => bail!( |
| 766 | "{name:?} is not a repository name: 1 to 100 of letters, digits, '.', '_' and '-', not starting with '.' or ending with \".git\"" |
| 767 | ), |
| 768 | None => { |
| 769 | let root = |
| 770 | fs::canonicalize(repo.root()).unwrap_or_else(|_| repo.root().to_path_buf()); |
| 771 | let dir = root |
| 772 | .file_name() |
| 773 | .map(|name| name.to_string_lossy().into_owned()) |
| 774 | .unwrap_or_default(); |
| 775 | let name = repo_name_from(&dir); |
| 776 | if !is_repo_name(&name) { |
| 777 | bail!( |
| 778 | "cannot make a repository name from the directory's name {dir:?}: give NAME" |
| 779 | ); |
| 780 | } |
| 781 | name |
| 782 | } |
| 783 | }; |
| 784 | let made = hub.create_repo(&RepoCreate { |
| 785 | name: name.clone(), |
| 786 | private: !args.public, |
| 787 | description: args.description.clone().unwrap_or_default(), |
| 788 | import: None, |
| 789 | mirror: args.mirror.clone(), |
| 790 | }); |
| 791 | let info = match made { |
| 792 | Ok(info) => info, |
| 793 | Err(HubError::Api { status: 409, body }) if body.error == "exists" => { |
| 794 | taken_up(&hub, &name)? |
| 795 | } |
| 796 | Err(err) if err.may_have_happened() => { |
| 797 | return Err(anyhow::Error::new(err).context(format!( |
| 798 | "the hub may have made {name} before its answer was lost: run `braid hub publish` again, which takes it up if it holds nothing yet" |
| 799 | ))); |
| 800 | } |
| 801 | Err(err) => return Err(err.into()), |
| 802 | }; |
| 803 | let path = RepoPath::new(&info.owner, &info.name) |
| 804 | .context("the hub named the new repository in a way braid cannot read")?; |
| 805 | let link = Link { |
| 806 | url: url.clone(), |
| 807 | repo: path, |
| 808 | paths: None, |
| 809 | }; |
| 810 | link.write(&repo)?; |
| 811 | (link, true) |
| 812 | } |
| 813 | }; |
| 814 | let remote = hub.repo(link.repo.clone()); |
| 815 | let published = publish::publish_refs(&repo, &remote, &cli.agent).with_context(|| { |
| 816 | if created { |
| 817 | format!( |
| 818 | "{} was created on the hub and linked here, but not all of it is there: run `braid hub publish` again", |
| 819 | link.repo |
| 820 | ) |
| 821 | } else { |
| 822 | format!("cannot publish to {}", link.repo) |
| 823 | } |
| 824 | })?; |
| 825 | // Where the hub's refs are now, for `braid hub status`. |
| 826 | fetch::fetch(&repo, &remote, &link, &cli.agent, None)?; |
| 827 | |
| 828 | let address = format!("{}/{}", link.url, link.repo); |
| 829 | if cli.json { |
| 830 | print_json(&json!({ |
| 831 | "hub": link.url, |
| 832 | "repo": link.repo.to_string(), |
| 833 | "url": address, |
| 834 | "created": created, |
| 835 | "objects": published.sent.objects, |
| 836 | "bytes": published.sent.bytes, |
| 837 | "refs": published.refs.iter().map(|r| json!({ |
| 838 | "name": r.name, |
| 839 | "id": r.id.to_hex(), |
| 840 | "outcome": r.outcome, |
| 841 | "head_before": hex(r.head_before), |
| 842 | "head": hex(r.head), |
| 843 | })).collect::<Vec<_>>(), |
| 844 | "skipped": published.skipped.iter().map(|(name, reason)| json!({ |
| 845 | "name": name, |
| 846 | "reason": reason, |
| 847 | })).collect::<Vec<_>>(), |
| 848 | }))?; |
| 849 | return Ok(ExitCode::SUCCESS); |
| 850 | } |
| 851 | println!( |
| 852 | "{} {} at {address}: {} uploaded ({})", |
| 853 | if created { "Published" } else { "Updated" }, |
| 854 | link.repo, |
| 855 | count(published.sent.objects, "object"), |
| 856 | count(published.sent.bytes, "byte") |
| 857 | ); |
| 858 | for r in &published.refs { |
| 859 | let what = match (r.outcome.as_str(), r.head_before) { |
| 860 | ("fast-forward", None) => format!("created at {}", r.id.short()), |
| 861 | ("fast-forward", Some(before)) => format!("{} -> {}", before.short(), r.id.short()), |
| 862 | ("already-applied", _) => format!("on the hub already, at {}", short(r.head)), |
| 863 | ("refused", _) if is_tag(&r.name) => format!( |
| 864 | "kept: the hub's names {}, and a tag never moves", |
| 865 | short(r.head) |
| 866 | ), |
| 867 | ("refused", _) => format!( |
| 868 | "refused: the hub's is at {}, which is not on this one's first-parent chain; `braid hub fetch` brings it in", |
| 869 | short(r.head) |
| 870 | ), |
| 871 | (other, _) => other.to_owned(), |
| 872 | }; |
| 873 | println!(" {:<24} {what}", remote::shown(&r.name)); |
| 874 | } |
| 875 | for (name, reason) in &published.skipped { |
| 876 | println!(" {:<24} skipped: {reason}", remote::shown(name)); |
| 877 | } |
| 878 | if created { |
| 879 | println!( |
| 880 | "Linked: `braid land` and `braid update` go through the hub now (--local keeps them here)." |
| 881 | ); |
| 882 | } |
| 883 | Ok(ExitCode::SUCCESS) |
| 884 | } |
| 885 | |
| 886 | /// The caller's repository `name`, which the hub says exists already: one |
| 887 | /// an earlier `braid hub publish` made before its answer was lost is taken |
| 888 | /// up when the caller owns it and it holds no ref yet. Any other is |
| 889 | /// refused, so that nothing is linked to, or uploaded into, a repository |
| 890 | /// with a history of its own. |
| 891 | fn taken_up(hub: &HttpHub, name: &str) -> Result<braid_hubproto::api::RepoInfo> { |
| 892 | let me = hub.me()?; |
| 893 | let path = RepoPath::new(&me.login, name) |
| 894 | .with_context(|| format!("the hub names the account {:?}", remote::shown(&me.login)))?; |
| 895 | let repository = hub.repo(path.clone()); |
| 896 | let info = repository.info()?; |
| 897 | let refs = repository.refs()?; |
| 898 | if !info.owner.eq_ignore_ascii_case(&me.login) || !refs.refs.is_empty() { |
| 899 | bail!( |
| 900 | "{path} exists on the hub already{}: give another NAME, or, if it is yours and holds nothing you need, delete it on the hub first", |
| 901 | if refs.refs.is_empty() { |
| 902 | "" |
| 903 | } else { |
| 904 | ", with refs of its own" |
| 905 | } |
| 906 | ); |
| 907 | } |
| 908 | Ok(info) |
| 909 | } |
| 910 | |
| 911 | /// What `hub clone` did to the directory before making the repository. |
| 912 | #[derive(Clone, Copy, Debug)] |
| 913 | enum Made { |
| 914 | Created, |
| 915 | WasEmpty, |
| 916 | } |
| 917 | |
| 918 | /// Makes `dir`, or checks that it is empty. |
| 919 | fn prepare(dir: &Path) -> Result<Made> { |
| 920 | match fs::read_dir(dir) { |
| 921 | Ok(mut entries) => { |
| 922 | if entries.next().is_some() { |
| 923 | bail!("{} exists and is not empty", dir.display()); |
| 924 | } |
| 925 | Ok(Made::WasEmpty) |
| 926 | } |
| 927 | Err(err) if err.kind() == io::ErrorKind::NotFound => { |
| 928 | fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?; |
| 929 | Ok(Made::Created) |
| 930 | } |
| 931 | Err(err) => Err(err).with_context(|| format!("cannot read {}", dir.display())), |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /// Takes back what a failed clone made in `dir`. |
| 936 | fn unmake(dir: &Path, made: Made) { |
| 937 | match made { |
| 938 | Made::Created => { |
| 939 | let _ = fs::remove_dir_all(dir); |
| 940 | } |
| 941 | Made::WasEmpty => { |
| 942 | if let Ok(entries) = fs::read_dir(dir) { |
| 943 | for entry in entries.flatten() { |
| 944 | let path = entry.path(); |
| 945 | let _ = match entry.file_type() { |
| 946 | Ok(kind) if kind.is_dir() => fs::remove_dir_all(&path), |
| 947 | _ => fs::remove_file(&path), |
| 948 | }; |
| 949 | } |
| 950 | } |
| 951 | } |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | /// A workspace a clone made. |
| 956 | struct NewWorkspace { |
| 957 | name: String, |
| 958 | path: PathBuf, |
| 959 | branch: String, |
| 960 | base: Option<braid_format::ObjectId>, |
| 961 | files: usize, |
| 962 | } |
| 963 | |
| 964 | /// The branch a clone's first workspace tracks: the hub's default branch |
| 965 | /// when the repository has it, or has no branch at all; else `main`, |
| 966 | /// `master`, its only branch, or its first. |
| 967 | fn first_branch(names: &[&str], default_branch: &str) -> String { |
| 968 | if names.contains(&default_branch) |
| 969 | || (names.is_empty() && braid_git::is_branch_name(default_branch)) |
| 970 | { |
| 971 | return default_branch.to_owned(); |
| 972 | } |
| 973 | ["main", "master"] |
| 974 | .into_iter() |
| 975 | .find(|preferred| names.contains(preferred)) |
| 976 | .or_else(|| names.first().copied()) |
| 977 | .unwrap_or("main") |
| 978 | .to_owned() |
| 979 | } |
| 980 | |
| 981 | /// Makes a clone's first workspace, the way `braid workspace add` makes |
| 982 | /// one: in `.braid/work/<name>`, at the head of the branch it tracks. |
| 983 | fn first_workspace(cli: &Cli, repo: &Repo, default_branch: &str) -> Result<NewWorkspace> { |
| 984 | let refs = repo.store().refs()?; |
| 985 | let branch = first_branch(&branches(&refs), default_branch); |
| 986 | let name = match &cli.workspace { |
| 987 | Some(name) => name.clone(), |
| 988 | None if WorkspaceLink::is_valid_name(&branch) => branch.clone(), |
| 989 | None => "work".to_owned(), |
| 990 | }; |
| 991 | let base = refs.get(&branch); |
| 992 | let dir = Workspace::default_dir(repo, &name); |
| 993 | let (workspace, files) = Workspace::create(repo, &name, &dir, base, &branch)?; |
| 994 | Ok(NewWorkspace { |
| 995 | name, |
| 996 | path: workspace.dir().to_path_buf(), |
| 997 | branch, |
| 998 | base, |
| 999 | files, |
| 1000 | }) |
| 1001 | } |
| 1002 | |
| 1003 | fn clone(cli: &Cli, args: &CloneArgs) -> Result<ExitCode> { |
| 1004 | let path: RepoPath = args.source.parse()?; |
| 1005 | let paths = if args.paths.is_empty() { |
| 1006 | None |
| 1007 | } else { |
| 1008 | Some( |
| 1009 | args.paths |
| 1010 | .iter() |
| 1011 | .map(|path| link::path_prefix(path)) |
| 1012 | .collect::<Result<Vec<_>>>()?, |
| 1013 | ) |
| 1014 | }; |
| 1015 | let env = HubEnv::from_process(); |
| 1016 | let creds = env.credentials()?; |
| 1017 | let url = creds::hub_url(&env, &creds, None)?; |
| 1018 | let (hub, _) = client(&env, &url)?; |
| 1019 | let remote = hub.repo(path.clone()); |
| 1020 | // Asked first, so that nothing is made for a repository the hub does |
| 1021 | // not show. |
| 1022 | let info = remote.info()?; |
| 1023 | let dir = args |
| 1024 | .dir |
| 1025 | .clone() |
| 1026 | .unwrap_or_else(|| PathBuf::from(&path.name)); |
| 1027 | let made = prepare(&dir)?; |
| 1028 | let link = Link { |
| 1029 | url: url.clone(), |
| 1030 | repo: path, |
| 1031 | paths, |
| 1032 | }; |
| 1033 | let cloned = (|| -> Result<_> { |
| 1034 | let repo = Repo::init_with(&dir, cli.store_options())?; |
| 1035 | link.write(&repo)?; |
| 1036 | let fetched = fetch::fetch(&repo, &remote, &link, &cli.agent, None)?; |
| 1037 | let workspace = match link.paths { |
| 1038 | Some(_) => None, |
| 1039 | None => Some(first_workspace(cli, &repo, &info.default_branch)?), |
| 1040 | }; |
| 1041 | let root = fs::canonicalize(repo.root()).unwrap_or_else(|_| repo.root().to_path_buf()); |
| 1042 | Ok((root, fetched, workspace)) |
| 1043 | })(); |
| 1044 | let (root, fetched, workspace) = match cloned { |
| 1045 | Ok(cloned) => cloned, |
| 1046 | Err(err) => { |
| 1047 | unmake(&dir, made); |
| 1048 | return Err(err); |
| 1049 | } |
| 1050 | }; |
| 1051 | if cli.json { |
| 1052 | print_json(&json!({ |
| 1053 | "hub": link.url, |
| 1054 | "repo": link.repo.to_string(), |
| 1055 | "root": root.to_string_lossy(), |
| 1056 | "paths": link.paths, |
| 1057 | "objects": fetched.objects, |
| 1058 | "refs": refs_json(&fetched), |
| 1059 | "workspace": workspace.as_ref().map(|ws| json!({ |
| 1060 | "name": ws.name, |
| 1061 | "path": ws.path.to_string_lossy(), |
| 1062 | "branch": ws.branch, |
| 1063 | "base": hex(ws.base), |
| 1064 | "files": ws.files, |
| 1065 | })), |
| 1066 | }))?; |
| 1067 | return Ok(ExitCode::SUCCESS); |
| 1068 | } |
| 1069 | let branch_count = fetched |
| 1070 | .refs |
| 1071 | .iter() |
| 1072 | .filter(|r| !is_tag(&r.name) && r.after.is_some()) |
| 1073 | .count(); |
| 1074 | let tag_count = fetched |
| 1075 | .refs |
| 1076 | .iter() |
| 1077 | .filter(|r| is_tag(&r.name) && r.after.is_some()) |
| 1078 | .count(); |
| 1079 | println!( |
| 1080 | "Cloned {} from {} into {}: {}, {} and {}", |
| 1081 | link.repo, |
| 1082 | link.url, |
| 1083 | root.display(), |
| 1084 | count(fetched.objects, "object"), |
| 1085 | count(branch_count as u64, "branch"), |
| 1086 | count(tag_count as u64, "tag") |
| 1087 | ); |
| 1088 | print_skipped(&fetched); |
| 1089 | match (&workspace, &link.paths) { |
| 1090 | (Some(ws), _) => println!( |
| 1091 | "Workspace {} in {} on {} at {}, {}", |
| 1092 | ws.name, |
| 1093 | ws.path.display(), |
| 1094 | remote::shown(&ws.branch), |
| 1095 | short(ws.base), |
| 1096 | count(ws.files as u64, "file") |
| 1097 | ), |
| 1098 | (None, Some(paths)) => println!( |
| 1099 | "Sparse: only the trees under {} came, so no workspace was made (a workspace is a whole checkout)", |
| 1100 | remote::shown(&paths.join(", ")) |
| 1101 | ), |
| 1102 | (None, None) => {} |
| 1103 | } |
| 1104 | Ok(ExitCode::SUCCESS) |
| 1105 | } |
| 1106 | |
| 1107 | /// The refs of a fetch, as JSON. |
| 1108 | fn refs_json(fetched: &Fetched) -> Vec<Value> { |
| 1109 | fetched |
| 1110 | .refs |
| 1111 | .iter() |
| 1112 | .map(|r| { |
| 1113 | let mut value = json!({ |
| 1114 | "name": r.name, |
| 1115 | "hub": r.hub.to_hex(), |
| 1116 | "before": hex(r.before), |
| 1117 | "after": hex(r.after), |
| 1118 | "outcome": r.outcome.code(), |
| 1119 | }); |
| 1120 | if let Outcome::Skipped(reason) = r.outcome { |
| 1121 | value["reason"] = Value::String(reason.to_owned()); |
| 1122 | } |
| 1123 | value |
| 1124 | }) |
| 1125 | .collect() |
| 1126 | } |
| 1127 | |
| 1128 | /// What became of a ref, for people. |
| 1129 | fn describe(r: &RefFetched) -> String { |
| 1130 | match r.outcome { |
| 1131 | Outcome::Created => format!("created at {}", r.hub.short()), |
| 1132 | Outcome::Moved => format!("{} -> {}", short(r.before), r.hub.short()), |
| 1133 | Outcome::Same => format!("up to date at {}", r.hub.short()), |
| 1134 | Outcome::Ahead => format!( |
| 1135 | "kept at {}: it has changesets the hub does not have, on top of the hub's {}; `braid land` from a workspace on it sends them", |
| 1136 | short(r.before), |
| 1137 | r.hub.short() |
| 1138 | ), |
| 1139 | Outcome::Diverged if is_tag(&r.name) => format!( |
| 1140 | "kept at {}: the hub's names {}, and a tag never moves", |
| 1141 | short(r.before), |
| 1142 | r.hub.short() |
| 1143 | ), |
| 1144 | Outcome::Diverged => format!( |
| 1145 | "kept at {}: it and the hub's, at {}, each have changesets the other does not", |
| 1146 | short(r.before), |
| 1147 | r.hub.short() |
| 1148 | ), |
| 1149 | Outcome::Skipped(reason) => format!("skipped: {reason}"), |
| 1150 | } |
| 1151 | } |
| 1152 | |
| 1153 | fn print_skipped(fetched: &Fetched) { |
| 1154 | for r in &fetched.refs { |
| 1155 | if matches!(r.outcome, Outcome::Skipped(_)) { |
| 1156 | println!(" {:<24} {}", remote::shown(&r.name), describe(r)); |
| 1157 | } |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | fn fetch_command(cli: &Cli) -> Result<ExitCode> { |
| 1162 | let repo = open_repo(cli)?; |
| 1163 | let link = require_link(&repo)?; |
| 1164 | let hub = connect(&link)?; |
| 1165 | let remote = hub.repo(link.repo.clone()); |
| 1166 | let fetched = fetch::fetch(&repo, &remote, &link, &cli.agent, None)?; |
| 1167 | if cli.json { |
| 1168 | print_json(&json!({ |
| 1169 | "hub": link.url, |
| 1170 | "repo": link.repo.to_string(), |
| 1171 | "seq": fetched.seq, |
| 1172 | "objects": fetched.objects, |
| 1173 | "operation": fetched.operation, |
| 1174 | "refs": refs_json(&fetched), |
| 1175 | }))?; |
| 1176 | return Ok(ExitCode::SUCCESS); |
| 1177 | } |
| 1178 | let changed: Vec<&RefFetched> = fetched |
| 1179 | .refs |
| 1180 | .iter() |
| 1181 | .filter(|r| r.outcome != Outcome::Same) |
| 1182 | .collect(); |
| 1183 | if fetched.objects == 0 && changed.is_empty() { |
| 1184 | println!("Up to date with {}", link.repo); |
| 1185 | return Ok(ExitCode::SUCCESS); |
| 1186 | } |
| 1187 | println!( |
| 1188 | "Fetched {} from {}", |
| 1189 | count(fetched.objects, "object"), |
| 1190 | link.repo |
| 1191 | ); |
| 1192 | for r in changed { |
| 1193 | println!(" {:<24} {}", remote::shown(&r.name), describe(r)); |
| 1194 | } |
| 1195 | Ok(ExitCode::SUCCESS) |
| 1196 | } |
| 1197 | |
| 1198 | fn status_command(cli: &Cli) -> Result<ExitCode> { |
| 1199 | let repo = open_repo(cli)?; |
| 1200 | let link = require_link(&repo)?; |
| 1201 | let env = HubEnv::from_process(); |
| 1202 | let (hub, source) = client(&env, &link.url)?; |
| 1203 | let login = if hub.has_token() { |
| 1204 | Some(hub.me().map(|me| me.login)) |
| 1205 | } else { |
| 1206 | None |
| 1207 | }; |
| 1208 | let remote = hub.repo(link.repo.clone()); |
| 1209 | let info = remote.info()?; |
| 1210 | let refs = remote.refs()?; |
| 1211 | let states = status::compare(&repo, &refs.refs)?; |
| 1212 | if cli.json { |
| 1213 | print_json(&json!({ |
| 1214 | "hub": link.url, |
| 1215 | "repo": link.repo.to_string(), |
| 1216 | "paths": link.paths, |
| 1217 | "login": login.as_ref().and_then(|login| login.as_ref().ok()), |
| 1218 | "token": source.code(), |
| 1219 | "mirror": info.mirror, |
| 1220 | "seq": refs.seq, |
| 1221 | "branches": states.iter().map(|s| json!({ |
| 1222 | "name": s.name, |
| 1223 | "local": hex(s.local), |
| 1224 | "hub": hex(s.hub), |
| 1225 | "state": s.state.code(), |
| 1226 | "green": hex(s.green), |
| 1227 | "red": hex(s.red), |
| 1228 | })).collect::<Vec<_>>(), |
| 1229 | }))?; |
| 1230 | return Ok(ExitCode::SUCCESS); |
| 1231 | } |
| 1232 | match &link.paths { |
| 1233 | Some(paths) => println!( |
| 1234 | "Linked to {} on {}, sparse: {}", |
| 1235 | link.repo, |
| 1236 | link.url, |
| 1237 | paths.join(", ") |
| 1238 | ), |
| 1239 | None => println!("Linked to {} on {}", link.repo, link.url), |
| 1240 | } |
| 1241 | let from = match source { |
| 1242 | TokenSource::Environment => " (BRAID_TOKEN)", |
| 1243 | _ => "", |
| 1244 | }; |
| 1245 | match &login { |
| 1246 | Some(Ok(login)) => println!("Signed in as {}{from}", remote::shown(login)), |
| 1247 | Some(Err(err)) => println!("Signed in, but {err}"), |
| 1248 | None => println!( |
| 1249 | "Not signed in: public repositories only (`braid login{}` signs in)", |
| 1250 | hub_flag(&link.url) |
| 1251 | ), |
| 1252 | } |
| 1253 | if let Some(mirror) = &info.mirror { |
| 1254 | let state = match (&mirror.outcome, &mirror.last_sync) { |
| 1255 | (Some(outcome), Some(when)) => format!("{outcome} at {when}"), |
| 1256 | (Some(outcome), None) => outcome.clone(), |
| 1257 | _ => "not synced yet".to_owned(), |
| 1258 | }; |
| 1259 | println!( |
| 1260 | "Mirror of {}: {} ({})", |
| 1261 | remote::shown(&info.default_branch), |
| 1262 | remote::shown(&mirror.url), |
| 1263 | remote::shown(&state) |
| 1264 | ); |
| 1265 | if let Some(detail) = &mirror.detail { |
| 1266 | println!(" {}", remote::shown(detail)); |
| 1267 | } |
| 1268 | } |
| 1269 | for s in &states { |
| 1270 | let mut heads = match (s.local, s.hub) { |
| 1271 | (Some(here), Some(there)) if here == there => here.short(), |
| 1272 | (here, there) => format!("here {}, hub {}", short(here), short(there)), |
| 1273 | }; |
| 1274 | // How the hub verifies it, when it does. |
| 1275 | if let Some(red) = s.red { |
| 1276 | heads.push_str(&format!(", red at {}", red.short())); |
| 1277 | } |
| 1278 | if let Some(green) = s.green { |
| 1279 | heads.push_str(&format!(", green at {}", green.short())); |
| 1280 | } |
| 1281 | println!( |
| 1282 | " {:<24} {:<9} {heads}", |
| 1283 | remote::shown(&s.name), |
| 1284 | s.state.code() |
| 1285 | ); |
| 1286 | } |
| 1287 | Ok(ExitCode::SUCCESS) |
| 1288 | } |
| 1289 | |
| 1290 | #[cfg(test)] |
| 1291 | mod tests { |
| 1292 | use super::*; |
| 1293 | |
| 1294 | #[test] |
| 1295 | fn names_from_directories() { |
| 1296 | for (dir, name) in [ |
| 1297 | ("demo", "demo"), |
| 1298 | ("My Project", "My-Project"), |
| 1299 | (".hidden", "hidden"), |
| 1300 | ("repo.git", "repo"), |
| 1301 | ("a.git.git", "a"), |
| 1302 | ("x y", "x-y"), |
| 1303 | ("ñandú", "and"), |
| 1304 | ("trailing-", "trailing"), |
| 1305 | ] { |
| 1306 | assert_eq!(repo_name_from(dir), name, "{dir}"); |
| 1307 | assert!(is_repo_name(name)); |
| 1308 | } |
| 1309 | assert_eq!(repo_name_from(&"a".repeat(150)).len(), 100); |
| 1310 | assert_eq!(repo_name_from("???"), ""); |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn the_first_workspace_tracks_the_default_branch() { |
| 1315 | assert_eq!(first_branch(&["dev", "trunk"], "trunk"), "trunk"); |
| 1316 | assert_eq!(first_branch(&[], "trunk"), "trunk"); |
| 1317 | assert_eq!(first_branch(&["dev", "master"], "trunk"), "master"); |
| 1318 | assert_eq!(first_branch(&["dev", "main", "master"], "trunk"), "main"); |
| 1319 | assert_eq!(first_branch(&["dev", "zeta"], "trunk"), "dev"); |
| 1320 | } |
| 1321 | } |