Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ rusqlite = { version = "0.32", features = ["bundled"] }

# CLI
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
clap_complete = { version = "4.5", features = ["unstable-dynamic"] }
indicatif = "0.17"
dialoguer = "0.11"
console = "0.15"
Expand Down
1 change: 1 addition & 0 deletions atomic-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ atomic-teams = { workspace = true, optional = true }

# CLI
clap = { workspace = true }
clap_complete = { workspace = true }
indicatif = { workspace = true }
dialoguer = { workspace = true }
console = { workspace = true }
Expand Down
8 changes: 6 additions & 2 deletions atomic-cli/src/commands/change/command.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use clap_complete::engine::ArgValueCompleter;

use crate::commands::complete::{complete_change_hashes, complete_view_names};

use super::*;

// Change Command
Expand Down Expand Up @@ -35,14 +39,14 @@ pub struct ChangeCmd {
///
/// If omitted, shows the most recent change on the current view.
/// Sequence numbers can be prefixed with `#` (e.g., `#42`).
#[arg(value_name = "HASH_OR_SEQ")]
#[arg(value_name = "HASH_OR_SEQ", add = ArgValueCompleter::new(complete_change_hashes))]
pub identifier: Option<String>,

/// View to use for sequence lookup.
///
/// When looking up by sequence number, use this view instead
/// of the current view.
#[arg(long = "view", value_name = "NAME")]
#[arg(long = "view", value_name = "NAME", add = ArgValueCompleter::new(complete_view_names))]
pub view: Option<String>,

/// Output format.
Expand Down
83 changes: 45 additions & 38 deletions atomic-cli/src/commands/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ pub fn remote_err(e: atomic_remote::RemoteError) -> CliError {
/// Resolution order:
/// 1. `--org` override (if `Some(non-empty)`)
/// 2. `server.default_org` from the resolved server profile
/// 3. Error with a hint to run `atomic org set`
/// 3. The default identity's personal org (the identity name), so commands
/// always target the tenant associated with the active identity even
/// before any `atomic org set`
///
/// An explicit empty string (`--org ""`) is an error: the user asked for "no
/// org" which never makes sense.
Expand All @@ -236,19 +238,27 @@ pub fn resolve_org_with_server(
return Ok(s.to_string());
}

server
.default_org
.clone()
.ok_or_else(|| CliError::InvalidArgument {
message: "No organization specified.\n \
Use --org or set a default with: atomic org set <slug>"
.to_string(),
})
if let Some(org) = &server.default_org {
return Ok(org.clone());
}

// Fall back to the personal org of the identity this server authenticates
// as. Registration seeds the personal org slug from the identity name, so
// the identity name is the correct default until the user runs
// `atomic org set` to switch to a team org.
let identity = resolve_identity_for_server(server).map_err(|_| CliError::InvalidArgument {
message: "No organization specified.\n \
Use --org or set a default with: atomic org set <slug>"
.to_string(),
})?;
Ok(identity.name)
}

/// Resolve the org slug using the legacy (single-server) config path.
/// Resolve the org slug for callers that don't already hold a server config.
///
/// Kept for callers that don't yet pass a server override.
/// Loads global config, resolves the active server profile, and delegates to
/// [`resolve_org_with_server`] so the identity-personal-org fallback applies
/// consistently.
pub fn resolve_org(org_override: Option<&str>) -> CliResult<String> {
if let Some(s) = org_override {
if s.is_empty() {
Expand All @@ -262,14 +272,11 @@ pub fn resolve_org(org_override: Option<&str>) -> CliResult<String> {
let config = GlobalConfig::load()
.map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {}", e)))?;

config
.server
.default_org
.ok_or_else(|| CliError::InvalidArgument {
message: "No organization specified.\n \
Use --org or set a default with: atomic org set <slug>"
.to_string(),
})
let (server, _name) = config
.resolve_server(None)
.map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?;

resolve_org_with_server(None, server)
}

/// Resolve the workspace slug for a command, with fallback to the
Expand Down Expand Up @@ -310,22 +317,28 @@ pub fn resolve_workspace_with_server(
}

/// Resolve the workspace slug for a command, with fallback to the
/// org-scoped default workspace from global config.
/// org-scoped default workspace from the **active** server profile.
///
/// Uses the legacy (single-server) config path. Prefer
/// [`resolve_workspace_with_server`] when you have already resolved the
/// active server.
/// Loads global config, resolves the active server profile (honouring
/// `server_override` → `default_server` → legacy `[server]`), and delegates
/// to [`resolve_workspace_with_server`]. This keeps reads aligned with
/// `atomic workspace set`, which writes into that same active profile —
/// otherwise a default set on a named profile would be invisible here.
///
/// Resolution order:
/// 1. `--workspace` override (if `Some(non-empty)`)
/// 2. `server.default_workspaces[org_slug]` from global config
/// 2. `server.default_workspaces[org_slug]` from the active server profile
/// 3. Error with a hint to run `atomic workspace set`
///
/// An explicit empty string (`--workspace ""`) is an error: the user
/// explicitly asked for "no workspace", which is meaningless. Distinguishing
/// `None` (not provided → fall back to default) from `Some("")` (provided
/// empty → error) prevents a class of confusing bugs.
pub fn resolve_workspace(org_slug: &str, workspace_override: Option<&str>) -> CliResult<String> {
pub fn resolve_workspace(
org_slug: &str,
workspace_override: Option<&str>,
server_override: Option<&str>,
) -> CliResult<String> {
if let Some(s) = workspace_override {
if s.is_empty() {
return Err(CliError::InvalidArgument {
Expand All @@ -338,17 +351,11 @@ pub fn resolve_workspace(org_slug: &str, workspace_override: Option<&str>) -> Cl
let config = GlobalConfig::load()
.map_err(|e| CliError::Internal(anyhow::anyhow!("Failed to load global config: {}", e)))?;

config
.server
.default_workspaces
.get(org_slug)
.cloned()
.ok_or_else(|| CliError::InvalidArgument {
message: format!(
"No workspace specified for org '{org_slug}'.\n \
Use --workspace or set a default with: atomic workspace set <slug>"
),
})
let (server, _name) = config
.resolve_server(server_override)
.map_err(|e| CliError::Internal(anyhow::anyhow!("{}", e)))?;

resolve_workspace_with_server(org_slug, None, server)
}

/// Resolve a flexible identity reference to a UUID.
Expand Down Expand Up @@ -487,13 +494,13 @@ mod tests {

#[test]
fn resolve_workspace_passes_through_explicit_override() {
let result = resolve_workspace("acme", Some("backend")).unwrap();
let result = resolve_workspace("acme", Some("backend"), None).unwrap();
assert_eq!(result, "backend");
}

#[test]
fn resolve_workspace_rejects_explicit_empty_override() {
let err = resolve_workspace("acme", Some("")).unwrap_err();
let err = resolve_workspace("acme", Some(""), None).unwrap_err();
match err {
CliError::InvalidArgument { message } => {
assert!(message.contains("cannot be empty"));
Expand Down
140 changes: 140 additions & 0 deletions atomic-cli/src/commands/complete.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//! Dynamic shell-completion helpers.
//!
//! These back the `clap_complete` dynamic engine (see `main.rs`'s
//! `CompleteEnv`). Commands attach them to individual arguments with
//! `#[arg(add = ArgValueCompleter::new(...))]` so that, at completion time,
//! the binary offers live values from the repository — view names and change
//! hashes — instead of nothing.
//!
//! The pure `*_candidates` functions take a `&Repository` and are unit-tested
//! directly. The `complete_*` wrappers open the repository from the current
//! working directory and return an empty list (never an error) when there is
//! no repository there, so completion is always safe to invoke.

use std::ffi::OsStr;

use clap_complete::engine::CompletionCandidate;

use atomic_core::types::Base32;
use atomic_repository::Repository;

use crate::commands::require_repository;

/// Maximum number of change-hash completion candidates to return.
///
/// Bounds the per-keystroke cost (we load a header per candidate) on repos
/// with large histories. Users typically type a hash prefix, which filters
/// the set down well before this cap.
const MAX_CHANGE_CANDIDATES: usize = 50;

/// View-name completion candidates matching `prefix`, sorted.
///
/// Pure over the repository so it can be unit-tested without the shell
/// completion machinery.
pub(crate) fn view_name_candidates(repo: &Repository, prefix: &str) -> Vec<String> {
let mut names = match repo.list_views() {
Ok(v) => v,
Err(_) => return Vec::new(),
};
names.retain(|n| n.starts_with(prefix));
names.sort();
names
}

/// Change-hash completion candidates drawn from the change store.
///
/// Commands that address a change by hash can reference *any* change that
/// exists in the repo, so the candidate source is the change store rather than
/// a single view's log. Returns `(base32_hash, optional_message)` pairs
/// filtered by `prefix` and capped at [`MAX_CHANGE_CANDIDATES`]. Pure over the
/// repository for unit testing.
pub(crate) fn change_hash_candidates(
repo: &Repository,
prefix: &str,
) -> Vec<(String, Option<String>)> {
let mut out = Vec::new();
for result in repo.iter_changes() {
let Ok(hash) = result else { continue };
let b32 = hash.to_base32();
if !prefix.is_empty() && !b32.starts_with(prefix) {
continue;
}
let message = repo
.load_change(&hash)
.ok()
.map(|c| c.hashed.header.message.clone());
out.push((b32, message));
if out.len() >= MAX_CHANGE_CANDIDATES {
break;
}
}
out
}

/// Dynamic completer for view-name arguments.
///
/// Runs in the user's CWD during completion; if there is no repository there
/// it returns no candidates rather than erroring.
pub(crate) fn complete_view_names(current: &OsStr) -> Vec<CompletionCandidate> {
let prefix = current.to_string_lossy();
let Ok(repo) = require_repository(None) else {
return Vec::new();
};
view_name_candidates(&repo, &prefix)
.into_iter()
.map(CompletionCandidate::new)
.collect()
}

/// Dynamic completer for change-hash arguments, annotating each hash with its
/// commit message as the completion description.
pub(crate) fn complete_change_hashes(current: &OsStr) -> Vec<CompletionCandidate> {
let prefix = current.to_string_lossy();
let Ok(repo) = require_repository(None) else {
return Vec::new();
};
change_hash_candidates(&repo, &prefix)
.into_iter()
.map(|(hash, msg)| {
let cand = CompletionCandidate::new(hash);
match msg {
Some(m) => cand.help(Some(m.into())),
None => cand,
}
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn view_name_candidates_filter_and_sort() {
let tmp = tempfile::tempdir().unwrap();
let repo = Repository::init(tmp.path()).unwrap();

// A freshly initialised repo has the default `dev` view.
let all = view_name_candidates(&repo, "");
assert!(
all.iter().any(|v| v == "dev"),
"expected default view: {all:?}"
);

// Prefix filtering.
let d = view_name_candidates(&repo, "d");
assert!(d.iter().all(|v| v.starts_with('d')));
assert!(d.iter().any(|v| v == "dev"));

// Non-matching prefix yields nothing.
assert!(view_name_candidates(&repo, "zzz").is_empty());
}

#[test]
fn change_hash_candidates_empty_repo_is_empty() {
let tmp = tempfile::tempdir().unwrap();
let repo = Repository::init(tmp.path()).unwrap();
// No changes recorded yet -> no candidates, and no error/panic.
assert!(change_hash_candidates(&repo, "").is_empty());
}
}
Loading
Loading