Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Improve CLI help, command migration guidance and output contracts

Manav Rathi1daee31a8542
diff --git a/rust/apps/cli-next/Cargo.toml b/rust/apps/cli-next/Cargo.toml
index 80f4ff093e..3e355d6075 100644
--- a/rust/apps/cli-next/Cargo.toml
+++ b/rust/apps/cli-next/Cargo.toml
@@ -10,7 +10,7 @@ museum = []
[dependencies]
anyhow.workspace = true
chrono = { workspace = true, features = ["std", "clock"] }
-clap = { workspace = true, features = ["derive"] }
+clap = { workspace = true, features = ["derive", "string"] }
clap_complete.workspace = true
dialoguer = { workspace = true, features = ["password"] }
dirs.workspace = true
diff --git a/rust/apps/cli-next/src/account.rs b/rust/apps/cli-next/src/account.rs
index fd856c4e2b..74c269f008 100644
--- a/rust/apps/cli-next/src/account.rs
+++ b/rust/apps/cli-next/src/account.rs
@@ -53,7 +53,7 @@ pub async fn request_otp(
.await?;
output::action(
options.json,
- &json!({"email": email, "host": origin, "app": app, "purpose": purpose, "verificationRequested": true}),
+ &json!({"email": email, "host": origin, "app": app, "purpose": purpose}),
&format!(
"Verification code sent to {}.",
output::escape_controls(&email)
@@ -299,7 +299,7 @@ pub async fn totp(
if matches!(command, TotpCommand::Status) {
return output::action(
options.json,
- &json!({"enabled": enabled}),
+ &json!({"totpEnabled": enabled}),
if enabled {
"Authenticator protection is enabled."
} else {
@@ -351,7 +351,7 @@ pub async fn totp(
}
output::action(
options.json,
- &json!({"enabled": true}),
+ &json!({"totpEnabled": true}),
"Authenticator protection is enabled.",
)
}
diff --git a/rust/apps/cli-next/src/admin.rs b/rust/apps/cli-next/src/admin.rs
index f8bc2245b4..ad3441bb15 100644
--- a/rust/apps/cli-next/src/admin.rs
+++ b/rust/apps/cli-next/src/admin.rs
@@ -113,7 +113,7 @@ async fn execute(
output::action(
options.json,
&json!({"user": {"id": result.user_id.to_string(), "email": email},
- "deleted": true, "cleanupScheduled": true,
+ "cleanupScheduled": true,
"subscriptionCancelled": result.is_subscription_cancelled}),
&format!(
"{target} ({}): Account deleted; data cleanup scheduled. Subscription cancelled: {}.",
@@ -144,10 +144,7 @@ async fn execute(
}
AdminUserCommand::RemovePasskeys(_) => {
client.admin_remove_passkeys(user.id).await?;
- (
- json!({"user": view, "passkeysRemoved": true}),
- "All passkeys removed.",
- )
+ (json!({"user": view}), "All passkeys removed.")
}
_ => unreachable!(),
};
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rs
index 3bd5d99450..847753fde3 100644
--- a/rust/apps/cli-next/src/args.rs
+++ b/rust/apps/cli-next/src/args.rs
@@ -5,38 +5,43 @@ use clap_complete::Shell;
use serde::{Deserialize, Serialize};
#[derive(Parser)]
-#[command(
- version,
- about = "Use Ente from the command line",
- override_usage = "ente-cli-next [OPTIONS] <COMMAND>",
- after_help = "Photos:
- ente-cli-next account login --app photos
- ente-cli-next photos album list
- ente-cli-next photos file list --album <ID>
- ente-cli-next photos export <DIR>
-Auth:
- ente-cli-next account login --app auth
- ente-cli-next auth code list
- ente-cli-next auth code view <CODE>
- ente-cli-next auth export <DIR>
-Paste:
- ente-cli-next paste create --input <PATH>
- ente-cli-next paste consume <URL>"
-)]
+#[command(version, about = "Ente client for terminals and agents")]
pub struct Cli {
- #[command(flatten)]
+ #[command(flatten, next_help_heading = "Global options")]
pub options: Options,
#[command(subcommand)]
pub command: Command,
}
pub fn command() -> clap::Command {
- Cli::command().subcommand_required(false).arg(
- Arg::new("help-all")
- .long("help-all")
- .action(ArgAction::SetTrue)
- .help("Print help for all commands"),
- )
+ let command = Cli::command().disable_help_subcommand(true);
+ let help = help_command(&command)
+ .name("help")
+ .about("Print help for a command or topic")
+ .disable_help_flag(false)
+ .arg(
+ Arg::new("all")
+ .long("all")
+ .action(ArgAction::SetTrue)
+ .help("Print help for all commands"),
+ )
+ .subcommand(clap::Command::new("migration").about("Show changes from earlier CLI versions"))
+ .subcommand(clap::Command::new("help").about("Show help options and topics"));
+ command
+ // Restore nested help after Clap propagates the root's setting.
+ .mut_subcommands(|child| child.defer(|child| child.disable_help_subcommand(false)))
+ .subcommand(help)
+}
+
+fn help_command(command: &clap::Command) -> clap::Command {
+ clap::Command::new(command.get_name().to_owned())
+ .about(command.get_about().cloned().unwrap_or_default())
+ .aliases(command.get_all_aliases().map(str::to_owned))
+ .hide(command.is_hide_set())
+ .display_order(command.get_display_order())
+ .disable_help_subcommand(true)
+ .disable_help_flag(true)
+ .subcommands(command.get_subcommands().map(help_command))
}
#[derive(Args)]
@@ -112,7 +117,7 @@ pub enum Command {
#[command(subcommand)]
command: AuthCommand,
},
- #[command(about = "Share and consume one-time encrypted text without an account")]
+ #[command(about = "Share text through one-time encrypted links")]
Paste {
#[command(subcommand)]
command: PasteCommand,
@@ -162,7 +167,7 @@ Prints the script to stdout, including when --json is set."
long,
global = true,
value_enum,
- help = "Saved app session; defaults to the sole app, otherwise Photos"
+ help = "Saved app login; defaults to the only app, otherwise Photos"
)]
app: Option<App>,
#[command(subcommand)]
@@ -176,11 +181,14 @@ pub enum PasteCommand {
about = "Create a one-time encrypted paste",
after_long_help = "Supply TEXT or --input PATH; --input - reads stdin verbatim.
With neither, reads piped stdin.
-Text must be nonblank and at most 4,000 Unicode scalar values.
+Text cannot be blank. Limit: 4,000 characters; some emoji count as more than one.
Pastes expire after 24 hours.
With --password, uses ENTE_CLI_PASSWORD when set; otherwise prompts for a paste password and confirmation.
With --password --no-input, ENTE_CLI_PASSWORD is required.
-Prints the paste URL. With --json: {\"url\": \"...\"}. Requires network access."
+Prints the paste URL. With --json: {\"url\": \"...\"}. Requires network access.
+
+Example:
+ ente-cli-next paste create --input notes.txt"
)]
Create {
#[arg(
@@ -207,10 +215,10 @@ Prints the paste URL. With --json: {\"url\": \"...\"}. Requires network access."
paste_origin: url::Url,
},
#[command(
- about = "Consume a paste and permanently remove its server copy",
+ about = "Read a paste and delete it from the server",
after_long_help = "Supply a URL including its #key fragment, or TOKEN --key KEY.
Protected pastes use ENTE_CLI_PASSWORD when set; otherwise prompt for the paste password.
-Consumes the paste before decryption, even with a wrong password or key.
+Deletes the server copy before decryption, even if the password or key is wrong.
A wrong ENTE_CLI_PASSWORD fails immediately; prompted retries work only while this command stays running.
Prints the text without adding a newline. Terminal controls are escaped except tabs and newlines.
With --json: {\"text\": \"...\"}. --raw affects plain terminal output only. Requires network access."
@@ -242,14 +250,19 @@ pub enum AuthCommand {
Encrypted export uses ENTE_CLI_PASSWORD when set; otherwise prompts for an export password.
With --no-input, encrypted export requires ENTE_CLI_PASSWORD.
DIR receives dated backups. --output writes a new file, or backup bytes to stdout with -.
---json formats file/directory summaries; stdout backups contain only the artifact."
+JSON summary fields: output, codes, failures.total. --json does not change backup contents.
+Backups written to stdout have no summary.
+
+Examples:
+ ente-cli-next auth export ~/Backups/Auth
+ ente-cli-next auth export --plaintext --output codes.txt"
)]
Export(AuthExportArgs),
#[command(about = "Decrypt an Auth export without an account")]
#[command(after_long_help = "Reads a backup without network access.
Uses ENTE_CLI_PASSWORD as the export password when set; otherwise prompts.
With --no-input, ENTE_CLI_PASSWORD is required.
-Writes readable URI lines to stdout, or a new --output file. --json only formats the file summary.")]
+Writes the decrypted backup to stdout, or a new --output file. --json only formats the file summary.")]
Decrypt {
#[arg(value_name = "PATH", help = "Encrypted Auth backup to decrypt")]
input: PathBuf,
@@ -292,7 +305,11 @@ Quote queries containing spaces.
A code in Trash must be restored in Ente Auth first.
JSON fields: id, name, issuer, accountName, type, otp, validUntil (UTC).
HOTP values are not supported yet.
-Codes use your computer's clock. Make sure its date and time are correct."
+Codes use your computer's clock. Make sure its date and time are correct.
+
+Examples:
+ ente-cli-next auth code view github
+ ente-cli-next auth code view \"GitHub ([email protected])\""
)]
View {
#[arg(
@@ -326,7 +343,7 @@ pub struct AuthExportArgs {
help = "Write to a new file, or stdout with -"
)]
pub output: Option<PathBuf>,
- #[arg(long, help = "Export readable URI lines without encryption")]
+ #[arg(long, help = "Export unencrypted otpauth:// links, one per line")]
pub plaintext: bool,
}
@@ -337,7 +354,15 @@ pub enum PhotosCommand {
#[command(about = "Maintain an independent copy of your Photos library")]
#[command(
after_long_help = "Refreshes metadata and downloads originals to DESTINATION; requires network access.
-Progress goes to stderr; the result goes to stdout. Use --json for a structured result."
+Progress goes to stderr; the result goes to stdout. Use --json for a structured result.
+JSON fields: output, complete, files, copies, changes, failures.
+files counts distinct photos and videos; copies counts album copies (expected, completed, pending).
+files and copies are null when the full export size could not be determined.
+changes contains exported, metadataUpdated, renamed and movedToTrash counts; failures contains total and conflicts.
+
+Examples:
+ ente-cli-next photos export ~/Pictures/Ente
+ ente-cli-next photos export ~/Pictures/Ente --album Holidays --account personal"
)]
Export(PhotosExportArgs),
#[command(about = "Manage albums")]
@@ -372,19 +397,19 @@ pub struct PhotosExportArgs {
#[arg(
long,
help = "Exclude albums owned by other accounts",
- long_help = "Exclude albums owned by other accounts, including albums explicitly included with --album. Albums you own remain included when shared with others. Excluded output is left alone. Removed albums use their last known category; an unknown category is reported as incomplete. Applies only to this invocation."
+ long_help = "Exclude albums owned by other accounts, including albums explicitly included with --album. Albums you own remain included when shared with others. Existing files in excluded albums are left unchanged. For removed albums, uses their last known ownership; if unknown, reports the export as incomplete. Applies only to this invocation."
)]
pub exclude_shared: bool,
#[arg(
long,
help = "Exclude hidden albums, including the Hidden album",
- long_help = "Exclude albums hidden for this account, including the Hidden album and albums explicitly included with --album. Archived albums and individually hidden files in included albums remain included. Excluded output is left alone. Removed albums use their last known category; an unknown category is reported as incomplete. Applies only to this invocation."
+ long_help = "Exclude albums hidden for this account, including the Hidden album and albums explicitly included with --album. Archived albums and individually hidden files in included albums remain included. Existing files in excluded albums are left unchanged. For removed albums, uses whether they were last seen as hidden; if unknown, reports the export as incomplete. Applies only to this invocation."
)]
pub exclude_hidden: bool,
#[arg(
long,
- help = "Take over an old CLI/Desktop export or reconnect an existing one",
- long_help = "Take over an old CLI/Desktop export or reconnect an existing one. Taking over an old export requires filters to select exactly its recorded albums. Reconnecting a native export associates the whole export, then applies filters to this invocation."
+ help = "Take over an export from an earlier CLI or Ente Desktop, or reconnect one",
+ long_help = "Take over an export made by an earlier CLI version or Ente Desktop, or reconnect an export after moving it or losing this CLI's local data. Taking over an earlier export requires filters to select exactly its recorded albums. Reconnecting checks the whole export before applying filters."
)]
pub adopt: bool,
#[arg(
@@ -558,10 +583,16 @@ A new entry becomes selected; logging into an existing entry keeps the selection
Non-interactive login reads JSON from --input:
{\"email\": \"...\", \"password\": \"...\", \"otp\": \"123456\", \"totp\": \"654321\"}
-All fields are strings. --email can supply the email instead. otp is the email code; totp is the authenticator code.
-Request an email code with account request-otp --email EMAIL --purpose login.
-With --no-input, supply email and password through --input PATH or --input -.
-For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help)."
+All fields are strings. Supply password and email; --email can supply the email instead.
+Supply otp (email code) or totp (authenticator code) only when required.
+Request an email code with account request-otp --email EMAIL --app APP --purpose login [--host URL].
+Use the same email, app and server as login.
+With --no-input, supply credentials through --input PATH or --input -.
+For unattended vault access, set ENTE_CLI_VAULT_KEY (see vault --help).
+
+Examples:
+ ente-cli-next account login --app photos
+ ente-cli-next account login --app auth --account personal"
)]
Login(LoginArgs),
#[command(
@@ -595,7 +626,8 @@ Defaults to creation; use --purpose login for an existing account."
after_long_help = "Creates and selects a new account, named after its email unless --account is supplied.
Prompts for email, consent, verification code and password.
Unattended creation requires --accept-terms and --input with email, password and otp strings.
---email can supply the email instead. Request the code first with account request-otp.
+--email can supply the email instead.
+Request the code first with account request-otp --email EMAIL [--app APP] [--host URL], using the same app and server as creation.
Repeating an unfinished creation resumes with its saved keys and the same password.
Terms: https://ente.io/terms Privacy: https://ente.io/privacy
Print the recovery key later with account recovery-key."
@@ -680,10 +712,7 @@ Without --app, logs out of all this account's saved app logins on this device.
},
#[command(
about = "Set up authenticator protection for your Ente account",
- after_long_help = "Protects account login, separate from codes stored in Ente Auth.
-Use enable interactively, or setup then enable --input with secret and totp strings.
-Setup secrets expire after ten minutes. If confirmation is interrupted, check status.
---app chooses a saved login: the only app, otherwise Photos. Requires network access."
+ after_long_help = "Protects account login, separate from codes stored in Ente Auth."
)]
Totp {
#[command(flatten)]
@@ -692,7 +721,7 @@ Setup secrets expire after ten minutes. If confirmation is interrupted, check st
long,
global = true,
value_enum,
- help = "Saved app login to authenticate with"
+ help = "Saved app login; defaults to the only app, otherwise Photos"
)]
app: Option<App>,
#[command(subcommand)]
@@ -715,11 +744,18 @@ With --json, returns {\"recoveryKey\":\"...\"}."
#[derive(Subcommand)]
pub enum TotpCommand {
- #[command(about = "Print a new authenticator setup secret")]
+ #[command(
+ about = "Print a new authenticator setup secret",
+ after_long_help = "Requires network access. The secret expires after ten minutes.
+Add it to your authenticator, then run account totp enable --input PATH|- with secret and totp strings."
+ )]
Setup,
#[command(
about = "Confirm and enable authenticator protection",
- after_long_help = "Verifying an authenticator code requires your computer's date and time to be correct."
+ after_long_help = "Without --input, creates a setup secret and prompts for an authenticator code.
+With --input, reads JSON containing secret from account totp setup and totp from your authenticator.
+Requires network access. If confirmation is interrupted, run account totp status.
+Verifying an authenticator code requires your computer's date and time to be correct."
)]
Enable {
#[arg(
@@ -729,7 +765,11 @@ pub enum TotpCommand {
)]
input: Option<PathBuf>,
},
- #[command(about = "Show whether authenticator protection is enabled")]
+ #[command(
+ about = "Show whether authenticator protection is enabled",
+ after_long_help = "Checks the current setting on the server; requires network access.
+JSON field: totpEnabled (boolean)."
+ )]
Status,
}
@@ -752,16 +792,10 @@ const ADMIN_HELP: &str =
"Uses the selected account's server and saved login; the server grants administrator access.
Log in with: ente-cli-next account login --account NAME --app photos --host URL
--account selects a saved account by name; otherwise uses the selected or sole account.
---app selects its session; otherwise uses the sole saved app, then Photos.
+--app selects its saved login; otherwise uses the only saved app, then Photos.
With multiple apps and no Photos login, supply --app.
-Listing users, deleting users and disabling TOTP require a login less than ten minutes old.
Changes to users require confirmation; --yes approves them, --no-input only disables prompts.
-All admin commands require network access. --json prints results, not prompts or errors.
-
-Examples:
- ente-cli-next admin --account home user view [email protected]
- ente-cli-next admin --account home user update-subscription [email protected] --no-limit
- ente-cli-next admin --account home user list --all --no-input --json";
+All admin commands require network access. --json prints results, not prompts or errors.";
#[derive(Subcommand)]
pub enum AdminCommand {
@@ -784,7 +818,10 @@ pub enum AdminUserCommand {
after_long_help = "Requires a login less than ten minutes old.
Lists users in creation order. Fetches all users matching --since before applying --limit.
--since accepts YYYY-MM-DD (midnight UTC) or RFC3339 with a timezone.
-JSON returns an array: id and email (strings), createdAt (RFC3339)."
+JSON returns an array: id and email (strings), createdAt (RFC3339).
+
+Example:
+ ente-cli-next admin --account home user list --all --no-input --json"
)]
List {
#[command(flatten)]
@@ -796,7 +833,10 @@ JSON returns an array: id and email (strings), createdAt (RFC3339)."
about = "Show a user's ID and subscription",
after_long_help = "JSON returns id, email, createdAt and subscription.
subscription contains productId, storageBytes and expiresAt, or null when unavailable.
-IDs are strings; timestamps are RFC3339; storageBytes is an integer."
+IDs are strings; timestamps are RFC3339; storageBytes is an integer.
+
+Example:
+ ente-cli-next admin --account home user view [email protected]"
)]
View {
#[arg(value_name = "USER", help = "User email or numeric ID")]
@@ -815,12 +855,12 @@ Requires a login less than ten minutes old. Reports the deleted account's ID and
},
#[command(
about = "Disable authenticator-code two-factor authentication",
- after_long_help = "Requires a login less than ten minutes old. Leaves passkeys enabled."
+ after_long_help = "Requires a login less than ten minutes old. Does not change passkeys."
)]
DisableTotp(AdminTarget),
#[command(
about = "Remove all of a user's passkeys",
- after_long_help = "Leaves authenticator-code two-factor authentication enabled."
+ after_long_help = "Does not change authenticator-code two-factor authentication."
)]
RemovePasskeys(AdminTarget),
#[command(
@@ -830,7 +870,10 @@ Alternatively supply --storage, --expires or both; omitted values stay unchanged
With neither, prompts to choose the preset or custom values. --no-input requires explicit values and --yes.
Sizes accept MB, GB and TB, case-insensitive, using powers of 1024; fractions are allowed.
Dates accept YYYY-MM-DD (00:00 UTC at the start of that date) or RFC3339 with a timezone.
-Shows old and new limits before confirmation. Paid plans are rejected."
+Shows old and new limits before confirmation. Paid plans are rejected.
+
+Example:
+ ente-cli-next admin --account home user update-subscription [email protected] --no-limit"
)]
UpdateSubscription(SubscriptionArgs),
}
diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rs
index 8bd57b9e38..a49c0b2ad4 100644
--- a/rust/apps/cli-next/src/auth/mod.rs
+++ b/rust/apps/cli-next/src/auth/mod.rs
@@ -73,7 +73,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)
if !matches!(destination, Destination::Stdout) {
crate::output::action(
options.json,
- &json!({"output": null, "codes": 0, "failures": payload.failed}),
+ &json!({"output": null, "codes": 0, "failures": {"total": payload.failed}}),
&format!(
"{} unreadable Auth code{plural}; no new backup was written.",
payload.failed
@@ -93,7 +93,7 @@ async fn export(args: AuthExportArgs, selected: Option<&str>, options: &Options)
if let Some(path) = destination.publish(&artifact)? {
crate::output::action(
options.json,
- &json!({"output": path.to_string_lossy(), "codes": payload.records, "failures": 0}),
+ &json!({"output": path.to_string_lossy(), "codes": payload.records, "failures": {"total": 0}}),
&format!(
"Exported {} code{} to {}.",
payload.records,
diff --git a/rust/apps/cli-next/src/auth/replica.rs b/rust/apps/cli-next/src/auth/replica.rs
index 3f6009724c..68ab19fbb9 100644
--- a/rust/apps/cli-next/src/auth/replica.rs
+++ b/rust/apps/cli-next/src/auth/replica.rs
@@ -114,7 +114,7 @@ pub async fn refresh(db: &mut Db, session: &Session) -> Result<()> {
}
ensure!(
next > cursor,
- "Auth diff timestamp boundary did not advance"
+ "cannot finish syncing Auth codes: the server's next page did not advance"
);
cursor = next;
}
diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rs
index 0b45950fb6..643a032183 100644
--- a/rust/apps/cli-next/src/main.rs
+++ b/rust/apps/cli-next/src/main.rs
@@ -7,6 +7,7 @@ mod core_db;
mod db;
mod home;
mod login;
+mod migration;
mod output;
mod password;
mod paste;
@@ -35,10 +36,16 @@ async fn main() {
.format(|out, record| writeln!(out, "{}", record.args()))
.init();
let mut command = args::command();
- let matches = command.get_matches_mut();
- let result = if matches.get_flag("help-all") {
+ let arguments: Vec<_> = std::env::args_os().collect();
+ let matches = command
+ .try_get_matches_from_mut(&arguments)
+ .unwrap_or_else(|mut error| {
+ migration::hint(&command, &arguments, &mut error);
+ error.exit()
+ });
+ let result = if let Some(help) = matches.subcommand_matches("help") {
command.build();
- print_all_help(&mut command, &mut std::io::stdout().lock())
+ print_help(&mut command, help, &mut std::io::stdout().lock())
} else {
let cli = Cli::from_arg_matches(&matches)
.unwrap_or_else(|error| error.format(&mut command).exit());
@@ -50,6 +57,41 @@ async fn main() {
}
}
+fn print_help(
+ command: &mut clap::Command,
+ mut matches: &clap::ArgMatches,
+ output: &mut impl Write,
+) -> Result<()> {
+ if matches.get_flag("all") {
+ if matches.subcommand_name().is_some() {
+ command
+ .find_subcommand_mut("help")
+ .context("missing help command")?
+ .error(
+ clap::error::ErrorKind::ArgumentConflict,
+ "help --all cannot be combined with a command or topic",
+ )
+ .exit();
+ }
+ return print_all_help(command, output);
+ }
+ if matches.subcommand_name() == Some("migration") {
+ return migration::print(
+ command.get_bin_name().unwrap_or_else(|| command.get_name()),
+ output,
+ );
+ }
+ let mut target = command;
+ while let Some((name, child)) = matches.subcommand() {
+ target = target
+ .find_subcommand_mut(name)
+ .context("unknown help command")?;
+ matches = child;
+ }
+ write!(output, "{}", target.render_long_help())?;
+ Ok(())
+}
+
fn print_all_help(command: &mut clap::Command, output: &mut impl Write) -> Result<()> {
writeln!(
output,
@@ -128,7 +170,7 @@ async fn account_command(command: AccountCommand, options: &Options) -> Result<(
let account = AccountView::new(&state.accounts[index], state.selected);
output::action(
options.json,
- &json!({"account": account, "app": app, "created": true}),
+ &json!({"account": account, "app": app}),
&format!(
"Created {} and signed into {}.",
output::escape_controls(&state.accounts[index].name),
diff --git a/rust/apps/cli-next/src/migration.rs b/rust/apps/cli-next/src/migration.rs
new file mode 100644
index 0000000000..434ccc9153
--- /dev/null
+++ b/rust/apps/cli-next/src/migration.rs
@@ -0,0 +1,307 @@
+use std::{ffi::OsString, io::Write};
+
+use clap::{
+ Command, Error,
+ error::{ContextKind, ContextValue, ErrorKind},
+};
+
+struct Change {
+ commands: &'static [&'static str],
+ hint: Option<&'static str>,
+ flags: &'static [(&'static [&'static str], &'static str)],
+ guide: &'static str,
+}
+
+const CHANGES: &[Change] = &[
+ Change {
+ commands: &["account add", "account login"],
+ hint: Some("'{command}' has been replaced by 'account login'.
+
+For Photos:
+ {binary} account login --app photos"),
+ flags: &[
+ (&["--password", "--otp", "--totp-code"], "Supply passwords and verification codes through prompts or --input PATH|-.
+The JSON fields are email, password, otp (email code) and totp (authenticator code)."),
+ (&["--endpoint"], "Use --host instead of --endpoint."),
+ (&["--export-dir"], "Choose the destination when running {binary} photos export DIR or {binary} auth export DIR."),
+ (&["--second-factor"], "Choose the second factor interactively, or supply totp in --input JSON. Passkey login is interactive."),
+ ],
+ guide: "Use {binary} account login --app APP [--email EMAIL] [--host URL].
+Supply passwords and verification codes through prompts or --input PATH|-.
+
+Use --account NAME to name a new local account or choose an existing one.",
+ },
+ Change {
+ commands: &["account signup", "account create"],
+ hint: Some("'{command}' has been replaced by 'account create'.
+
+ {binary} account create"),
+ flags: &[
+ (&["--password", "--otp"], "Supply credentials through prompts or --input PATH|- with --accept-terms.
+The JSON fields are email, password and otp (email code)."),
+ (&["--endpoint"], "Use --host instead of --endpoint."),
+ (&["--export-dir"], "Choose the destination when running {binary} photos export DIR or {binary} auth export DIR."),
+ (&["--setup-2fa", "--totp-code"], "Run {binary} account totp enable after creation to set up authenticator protection.
+For automation, run {binary} account totp setup, then {binary} account totp enable --input PATH|- with secret and totp strings."),
+ (&["--show-recovery-key"], "Print the recovery key with {binary} account recovery-key."),
+ (&["--source"], "--source has no equivalent."),
+ ],
+ guide: "Use {binary} account create [--email EMAIL] [--app APP] [--host URL]; the default app is Photos.
+Supply credentials through prompts or --input PATH|- with --accept-terms.
+
+For automation:
+ {binary} account request-otp --email EMAIL
+ {binary} account create --input PATH --accept-terms
+The input JSON contains email, password and otp.",
+ },
+ Change {
+ commands: &["account list"],
+ hint: None,
+ flags: &[],
+ guide: "{binary} account list lists accounts saved on this computer.
+Use {binary} account switch NAME to select one, or --account NAME on individual commands.",
+ },
+ Change {
+ commands: &["account update"],
+ hint: Some("export destinations are now supplied with each export command.
+
+ {binary} photos export DIR --account NAME
+ {binary} auth export DIR --account NAME"),
+ flags: &[],
+ guide: "Export destinations are now supplied on each invocation:
+ {binary} photos export DIR --account NAME
+ {binary} auth export DIR --account NAME
+There is no saved export-directory setting.",
+ },
+ Change {
+ commands: &["account get-token"],
+ hint: Some("'{command}' has been replaced by 'account token'.
+
+For Photos:
+ {binary} account token --app photos"),
+ flags: &[],
+ guide: "Use {binary} account token --app APP [--account NAME].
+
+--app is required. --account selects a local name, not an email lookup.
+Omit --account to use the selected or only saved account.",
+ },
+ Change {
+ commands: &["account two-factor", "account 2fa"],
+ hint: Some("'{command}' has been replaced by 'account totp enable'.
+
+ {binary} account totp enable"),
+ flags: &[],
+ guide: "Use {binary} account totp enable [--account NAME] [--app APP] interactively.
+
+For automation, run {binary} account totp setup, then {binary} account totp enable --input PATH|-.
+The input JSON contains secret and totp strings. Check progress with {binary} account totp status.
+Print the recovery key separately with {binary} account recovery-key.",
+ },
+ Change {
+ commands: &["export", "photos export"],
+ hint: Some("export now requires an app and a destination.
+
+ {binary} photos export DIR --account NAME
+ {binary} auth export DIR --account NAME
+
+Run a separate command for each account you want to export."),
+ flags: &[
+ (&["--albums"], "Use --album ALBUM instead of --albums, repeating --album for multiple albums."),
+ (&["--exclude-albums"], "Use --exclude-album ALBUM instead of --exclude-albums, repeating it for multiple albums."),
+ (&["--shared"], "Shared albums are included by default. Use --exclude-shared instead of --shared=false."),
+ (&["--hidden"], "Hidden albums are included by default. Use --exclude-hidden instead of --hidden=false."),
+ (&["--emails"], "Run a separate export for each account, selecting its local name with --account NAME instead of --emails."),
+ ],
+ guide: "Run a separate export for each app and account:
+ {binary} photos export DIR --account NAME
+ {binary} auth export DIR --account NAME
+
+Saved export jobs are no longer used. Update scheduled commands with explicit destinations.
+To take over an earlier Photos export, log in and run {binary} photos export DIR --adopt.
+Stop the old export job first. Taking over covers all recorded albums; filters must match that set.
+Auth: backups are dated and encrypted by default; use --plaintext for URI text.
+For scheduled encrypted backups, set ENTE_CLI_PASSWORD. Locker export is not available.",
+ },
+ Change {
+ commands: &["auth decrypt"],
+ hint: Some("auth decrypt now takes its output path through --output.
+
+ {binary} auth decrypt INPUT --output OUTPUT"),
+ flags: &[
+ (&["--password", "-p"], "Supply the password through the prompt or ENTE_CLI_PASSWORD instead of --password/-p."),
+ ],
+ guide: "Use {binary} auth decrypt INPUT --output OUTPUT instead of two positional paths.
+The password is prompted or read from ENTE_CLI_PASSWORD.
+
+Omitting --output writes to stdout. An existing output file is refused.",
+ },
+ Change {
+ commands: &["paste create"],
+ hint: None,
+ flags: &[
+ (&["--file", "-f"], "Use --input PATH|- instead of --file/-f."),
+ (&["--endpoint"], "Use --host instead of --endpoint."),
+ ],
+ guide: "Use {binary} paste create [TEXT] [--input PATH|-] [--host URL].
+
+--password and --paste-origin keep their meanings.",
+ },
+ Change {
+ commands: &["paste read", "paste consume"],
+ hint: Some("'{command}' has been replaced by 'paste consume'.
+
+ {binary} paste consume URL"),
+ flags: &[
+ (&["--endpoint"], "Use --host instead of --endpoint."),
+ ],
+ guide: "Use {binary} paste consume URL|TOKEN [--key KEY] [--host URL].
+
+--raw keeps its meaning.",
+ },
+ Change {
+ commands: &["version"],
+ hint: Some("'version' has been replaced by '--version'.
+
+ {binary} --version"),
+ flags: &[],
+ guide: "Use {binary} --version.",
+ },
+ Change {
+ commands: &["admin get-user-id"],
+ hint: Some("'{command}' has been replaced by 'admin user view'.
+
+ {binary} admin user view EMAIL"),
+ flags: &[],
+ guide: "Use {binary} admin user view EMAIL|ID.",
+ },
+ Change {
+ commands: &["admin list-users"],
+ hint: Some("'{command}' has been replaced by 'admin user list'.
+
+ {binary} admin user list --all"),
+ flags: &[],
+ guide: "Use {binary} admin user list --all for every user; the default limit is 100.",
+ },
+ Change {
+ commands: &["admin delete-user"],
+ hint: Some("'{command}' has been replaced by 'admin user delete'.
+
+ {binary} admin user delete EMAIL"),
+ flags: &[],
+ guide: "Use {binary} admin user delete EMAIL. Add --yes to approve without prompting.",
+ },
+ Change {
+ commands: &["admin disable-2fa"],
+ hint: Some("'{command}' has been replaced by 'admin user disable-totp'.
+
+ {binary} admin user disable-totp EMAIL"),
+ flags: &[],
+ guide: "Use {binary} admin user disable-totp EMAIL|ID. Add --yes to approve without prompting.",
+ },
+ Change {
+ commands: &["admin disable-passkey"],
+ hint: Some("'{command}' has been replaced by 'admin user remove-passkeys'.
+
+ {binary} admin user remove-passkeys EMAIL"),
+ flags: &[],
+ guide: "Use {binary} admin user remove-passkeys EMAIL|ID. Add --yes to approve without prompting.",
+ },
+ Change {
+ commands: &["admin update-subscription"],
+ hint: Some("'{command}' has been replaced by 'admin user update-subscription'.
+
+ {binary} admin user update-subscription EMAIL --no-limit"),
+ flags: &[],
+ guide: "Use {binary} admin user update-subscription EMAIL|ID --no-limit for the old default preset.
+For custom limits, use --storage SIZE and/or --expires DATE. Add --yes for automation.",
+ },
+ Change {
+ commands: &["admin send-mail"],
+ hint: Some("'{command}' has been replaced by 'admin email test'.
+
+ {binary} admin email test --to EMAIL --from EMAIL --from-name NAME"),
+ flags: &[],
+ guide: "Use {binary} admin email test --to EMAIL --from EMAIL --from-name NAME.",
+ },
+];
+
+pub fn print(binary: &str, output: &mut impl Write) -> anyhow::Result<()> {
+ writeln!(output, "Command changes")?;
+ writeln!(
+ output,
+ "
+Log in again with {binary} account login; old saved logins and config.yaml are not imported.
+APP is photos, auth or locker. NAME is a local account name.
+Choose the server with --host on login or creation; later commands use the saved server.
+Use the same app and server when requesting an email code and completing login or creation.
+ENTE_CLI_HOME replaces ENTE_CLI_CONFIG_DIR for choosing this CLI's local storage.
+For unattended access, see {binary} vault --help for ENTE_CLI_VAULT_KEY.
+Admin commands use --account NAME instead of --admin-user/-a; USER is positional.
+Use --json for structured results. Old output formats are not preserved."
+ )?;
+ for change in CHANGES {
+ writeln!(output, "\n{}", change.commands.join(" / "))?;
+ for line in change.guide.replace("{binary}", binary).lines() {
+ if !line.is_empty() {
+ write!(output, " {line}")?;
+ }
+ writeln!(output)?;
+ }
+ for (flags, guidance) in change.flags {
+ writeln!(output, " {}:", flags.join(", "))?;
+ for line in guidance.replace("{binary}", binary).lines() {
+ writeln!(output, " {line}")?;
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn hint(command: &Command, arguments: &[OsString], error: &mut Error) {
+ let context = match error.kind() {
+ ErrorKind::InvalidSubcommand => ContextKind::InvalidSubcommand,
+ ErrorKind::UnknownArgument => ContextKind::InvalidArg,
+ _ => return,
+ };
+ let Some(ContextValue::String(invalid)) = error.get(context) else {
+ return;
+ };
+ let Ok(matches) = crate::args::command()
+ .ignore_errors(true)
+ .try_get_matches_from(arguments)
+ else {
+ return;
+ };
+ let mut path = Vec::new();
+ let mut current = &matches;
+ while let Some((name, child)) = current.subcommand() {
+ path.push(name);
+ current = child;
+ }
+ if context == ContextKind::InvalidSubcommand {
+ path.push(invalid);
+ }
+ let path = path.join(" ");
+ let Some(change) = CHANGES
+ .iter()
+ .find(|change| change.commands.contains(&path.as_str()))
+ else {
+ return;
+ };
+ if context != ContextKind::InvalidSubcommand
+ && !(path == "auth decrypt" && !invalid.starts_with('-'))
+ {
+ return;
+ }
+ let Some(summary) = change.hint else {
+ return;
+ };
+ let binary = command.get_bin_name().unwrap_or_else(|| command.get_name());
+ let summary = summary
+ .replace("{command}", &path)
+ .replace("{binary}", binary);
+ *error = Error::raw(
+ error.kind(),
+ format!("{summary}\n\nSee all command changes with:\n {binary} help migration\n"),
+ );
+}
diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli-next/src/output.rs
index e0ebfc1a12..fd5021f164 100644
--- a/rust/apps/cli-next/src/output.rs
+++ b/rust/apps/cli-next/src/output.rs
@@ -232,7 +232,7 @@ pub fn albums(
[
album.id,
escape_controls(&album.name),
- album.kind.to_owned(),
+ type_label(album.kind).to_owned(),
album.visibility.to_owned(),
album.owner_id,
album.updated_at,
@@ -244,7 +244,7 @@ pub fn albums(
pub fn album(album: &AlbumView) -> Result<()> {
write_fields(&[
("Name", escape_controls(&album.name)),
- ("Type", album.kind.to_owned()),
+ ("Type", type_label(album.kind).to_owned()),
("Visibility", album.visibility.to_owned()),
("Owner", album.owner_id.clone()),
("Updated", album.updated_at.clone()),
@@ -267,7 +267,7 @@ pub fn files(
[
file.id,
escape_controls(&file.name),
- file.kind.to_owned(),
+ type_label(file.kind).to_owned(),
file.created_at,
file.album_ids.join(","),
]
@@ -278,7 +278,7 @@ pub fn files(
pub fn file(file: &FileView) -> Result<()> {
let mut fields = vec![
("Name", escape_controls(&file.name)),
- ("Type", file.kind.to_owned()),
+ ("Type", type_label(file.kind).to_owned()),
(
"Visibility",
file.visibility.unwrap_or("unavailable").to_owned(),
@@ -371,6 +371,15 @@ pub fn storage_size(bytes: i64) -> String {
format!("{bytes} bytes")
}
+fn type_label(kind: &str) -> &str {
+ match kind {
+ "defaultHidden" => "hidden album",
+ "quicklink" => "quick link",
+ "livephoto" => "live photo",
+ _ => kind,
+ }
+}
+
fn timestamp(micros: i64) -> Result<String> {
Ok(DateTime::from_timestamp_micros(micros)
.context("timestamp is outside the supported range")?
diff --git a/rust/apps/cli-next/src/photos/export/mod.rs b/rust/apps/cli-next/src/photos/export/mod.rs
index 5dc0a85b5e..2e4862a7cb 100644
--- a/rust/apps/cli-next/src/photos/export/mod.rs
+++ b/rust/apps/cli-next/src/photos/export/mod.rs
@@ -96,21 +96,24 @@ async fn run_locked(args: PhotosExportArgs, selected: Option<&str>, as_json: boo
signal.abort();
let summary = result?;
let progress = if summary.json["copies"].is_null() {
- "inventory incomplete".to_owned()
+ "could not determine the full export size".to_owned()
} else {
- format!("{}/{} copies complete", summary.completed, summary.expected)
+ format!(
+ "{}/{} album copies complete",
+ summary.completed, summary.expected
+ )
};
let changes = &summary.json["changes"];
output::action(
as_json,
&summary.json,
&format!(
- "{}: {progress}, {} exported, {} retained, {} failures, {} conflicts.",
+ "{}: {progress}, {} exported, {} moved to Trash, {} failures ({} conflicts).",
export.destination().display(),
changes["exported"],
- changes["retained"],
- summary.json["failures"],
- summary.json["conflicts"],
+ changes["movedToTrash"],
+ summary.json["failures"]["total"],
+ summary.json["failures"]["conflicts"],
),
)?;
ensure!(summary.complete, "export is incomplete");
diff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli-next/src/vault.rs
index 5ba99bd0e1..2edac84f27 100644
--- a/rust/apps/cli-next/src/vault.rs
+++ b/rust/apps/cli-next/src/vault.rs
@@ -320,8 +320,7 @@ fn keyring_error(error: keyring::Error, exists: bool) -> anyhow::Error {
}
fn decrypt(bytes: &[u8], key: &Key, home: &Path) -> Result<State> {
- let unlock_error =
- || anyhow::anyhow!("cannot unlock CLI vault: wrong key or damaged ciphertext");
+ let unlock_error = || anyhow::anyhow!("cannot unlock CLI vault: wrong key or damaged file");
let encrypted: EncryptedVault =
parse_json(bytes).context("unsupported or invalid CLI vault format")?;
let ciphertext = b64::decode(&encrypted.data)
@@ -332,7 +331,7 @@ fn decrypt(bytes: &[u8], key: &Key, home: &Path) -> Result<State> {
parse_json(&plaintext).context("invalid CLI vault contents")?;
ensure!(
version.schema_version == SCHEMA_VERSION,
- "unsupported CLI vault schema {}; this build supports {SCHEMA_VERSION}.\nTo start fresh, move {} aside, then log in again.",
+ "cannot read CLI vault format {}; this CLI supports {SCHEMA_VERSION}.\nTo start fresh, move {} aside, then log in again.",
version.schema_version,
home.join(VAULT_FILE).display(),
);
diff --git a/rust/apps/cli-next/tests/cli/account.rs b/rust/apps/cli-next/tests/cli/account.rs
index 066d35d871..49135b57fa 100644
--- a/rust/apps/cli-next/tests/cli/account.rs
+++ b/rust/apps/cli-next/tests/cli/account.rs
@@ -33,7 +33,7 @@ fn request_otp_is_independent_of_the_vault_and_reports_request_acceptance() {
let value: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(
value,
- json!({"email": "[email protected]", "host": server.url(), "app": "auth", "purpose": "create", "verificationRequested": true})
+ json!({"email": "[email protected]", "host": server.url(), "app": "auth", "purpose": "create"})
);
assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 0);
request.assert();
@@ -232,7 +232,6 @@ async fn creation_retry_preserves_keys_and_recovers_after_an_accepted_upload() {
));
let result: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(result["account"]["name"], "personal");
- assert_eq!(result["created"], true);
let complete = home.read_vault();
assert_eq!(
complete["accounts"][0]["identity"]["master_key"],
@@ -337,7 +336,7 @@ fn creation_enrollment_and_login_across_processes() -> ente_test_support::TestRe
let secret = setup["secret"].as_str().unwrap();
assert_eq!(
home.json(&["account", "totp", "status"]),
- json!({"enabled": false})
+ json!({"totpEnabled": false})
);
let error = failure(&home.with_input(
&["account", "totp", "enable", "--input", "-"],
@@ -350,11 +349,11 @@ fn creation_enrollment_and_login_across_processes() -> ente_test_support::TestRe
));
assert_eq!(
serde_json::from_slice::<Value>(&output.stdout)?,
- json!({"enabled": true})
+ json!({"totpEnabled": true})
);
assert_eq!(
home.json(&["account", "totp", "status"]),
- json!({"enabled": true})
+ json!({"totpEnabled": true})
);
assert!(failure(&home.run(&["account", "totp", "setup"])).contains("already enabled"));
let second = TestHome::new();
@@ -410,7 +409,7 @@ fn interactive_creation_password_retry_and_enrollment() -> ente_test_support::Te
assert_eq!(home.json(&["account", "view"])["name"], email);
assert_eq!(
home.json(&["account", "totp", "status"]),
- json!({"enabled": true})
+ json!({"totpEnabled": true})
);
assert_eq!(
home.json(&["photos", "api", "/users/details/v2"])["email"],
diff --git a/rust/apps/cli-next/tests/cli/admin.rs b/rust/apps/cli-next/tests/cli/admin.rs
index f1109f99a5..d7ef477af2 100644
--- a/rust/apps/cli-next/tests/cli/admin.rs
+++ b/rust/apps/cli-next/tests/cli/admin.rs
@@ -119,7 +119,7 @@ fn admin_deletion_uses_email_and_reports_deleted_id() {
args.push("--yes");
assert_eq!(
home.json(&args),
- json!({"user": {"id": USER_ID.to_string(), "email": EMAIL}, "deleted": true,
+ json!({"user": {"id": USER_ID.to_string(), "email": EMAIL},
"cleanupScheduled": true, "subscriptionCancelled": false})
);
delete.assert();
@@ -127,13 +127,9 @@ fn admin_deletion_uses_email_and_reports_deleted_id() {
#[test]
fn admin_security_mutations_require_confirmation_and_use_resolved_target() {
- for (command, path, field) in [
- ("disable-totp", "/admin/user/disable-2fa", "totpEnabled"),
- (
- "remove-passkeys",
- "/admin/user/disable-passkeys",
- "passkeysRemoved",
- ),
+ for (command, path) in [
+ ("disable-totp", "/admin/user/disable-2fa"),
+ ("remove-passkeys", "/admin/user/disable-passkeys"),
] {
let mut server = Server::new();
let home = TestHome::new();
@@ -156,7 +152,6 @@ fn admin_security_mutations_require_confirmation_and_use_resolved_target() {
args.push("--yes");
let result = home.json(&args);
assert_eq!(result["user"]["email"], EMAIL);
- assert_eq!(result[field], command != "disable-totp");
get.assert();
change.assert();
}
diff --git a/rust/apps/cli-next/tests/cli/admin_museum.rs b/rust/apps/cli-next/tests/cli/admin_museum.rs
index 9641a4b271..8b749aa9ed 100644
--- a/rust/apps/cli-next/tests/cli/admin_museum.rs
+++ b/rust/apps/cli-next/tests/cli/admin_museum.rs
@@ -243,7 +243,6 @@ fn admin_user_lifecycle() -> TestResult {
let deleted = home.json(&["admin", "user", "delete", &email, "--yes", "--no-input"]);
assert_eq!(deleted["user"]["id"], id);
assert_eq!(deleted["user"]["email"], email);
- assert_eq!(deleted["deleted"], true);
assert_eq!(deleted["cleanupScheduled"], true);
assert_eq!(deleted["subscriptionCancelled"], true);
assert!(failure(&home.run(&view)).contains("HTTP 404"));
@@ -365,17 +364,14 @@ fn admin_security_resets() -> TestResult {
.len(),
2
);
- assert_eq!(
- home.json(&[
- "admin",
- "user",
- "remove-passkeys",
- &email,
- "--yes",
- "--no-input"
- ])["passkeysRemoved"],
- true
- );
+ home.json(&[
+ "admin",
+ "user",
+ "remove-passkeys",
+ &email,
+ "--yes",
+ "--no-input",
+ ]);
assert!(api_json(&origin, token, "GET", "/passkeys", None).await["passkeys"].is_null());
assert!(client.get_two_factor_status().await?);
register_passkey(&origin, token).await;
diff --git a/rust/apps/cli-next/tests/cli/auth.rs b/rust/apps/cli-next/tests/cli/auth.rs
index 4d16c32aee..871b9c8207 100644
--- a/rust/apps/cli-next/tests/cli/auth.rs
+++ b/rust/apps/cli-next/tests/cli/auth.rs
@@ -331,7 +331,7 @@ fn refresh_keeps_progress_and_refuses_unreadable_codes_until_updated() {
assert!(!stderr.contains("JBSWY3DPEHPK3PXP"));
assert_eq!(
serde_json::from_slice::<Value>(&failed.stdout).unwrap(),
- json!({"output": null, "codes": 0, "failures": 2})
+ json!({"output": null, "codes": 0, "failures": {"total": 2}})
);
assert_eq!(fs::read_dir(output_dir.path()).unwrap().count(), 1);
changed.assert();
@@ -459,7 +459,7 @@ fn key_resets_and_unadvanceable_pages_cannot_publish_stale_data() {
let first = page(&mut server, 0, rows.clone());
let stuck = page(&mut server, 9, rows);
let failed = home.run(EXPORT);
- assert!(failure(&failed).contains("boundary did not advance"));
+ assert!(failure(&failed).contains("the server's next page did not advance"));
assert!(failed.stdout.is_empty());
assert!(
failure(&home.command(EXPORT).arg("--offline").output().unwrap()).contains("incomplete")
@@ -553,7 +553,7 @@ fn encrypted_export_and_independent_decrypt_keep_artifacts_separate_from_summari
);
let summary: Value = serde_json::from_slice(&result.stdout).unwrap();
assert_eq!(summary["codes"], 1);
- assert_eq!(summary["failures"], 0);
+ assert_eq!(summary["failures"]["total"], 0);
let encoded = fs::read(&encrypted).unwrap();
let stream = success(
home.command(&["auth", "export", "--offline", "--output", "-", "--json"])
diff --git a/rust/apps/cli-next/tests/cli/export.rs b/rust/apps/cli-next/tests/cli/export.rs
index f992a8bdca..d685ded084 100644
--- a/rust/apps/cli-next/tests/cli/export.rs
+++ b/rust/apps/cli-next/tests/cli/export.rs
@@ -151,12 +151,12 @@ fn export_metadata_updates_and_repairs_preserve_source_values() -> TestResult {
assert_eq!(record["modificationTime"]["timestamp"],"1700000001");
assert_eq!(fs::read(root.join("Family/A.jpg"))?,original);
let unchanged=export(&home,&root,&["--album","Family"]);
- assert_eq!(unchanged["changes"],json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0}));
+ assert_eq!(unchanged["changes"],json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0}));
assert_eq!(fs::metadata(&sidecar)?.modified()?,sidecar_time);
assert_eq!(fs::metadata(root.join("Family/A.jpg"))?.modified()?,original_time);
let before_locale=fs::read(&sidecar)?;
let localized=success(home.command(&["photos","export",root.to_str().unwrap(),"--album","Family","--json"]).env("LC_ALL","tr_TR.UTF-8").env("TZ","Pacific/Honolulu").output()?);
- assert_eq!(serde_json::from_slice::<Value>(&localized.stdout)?["changes"],json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0}));
+ assert_eq!(serde_json::from_slice::<Value>(&localized.stdout)?["changes"],json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0}));
assert_eq!(fs::read(&sidecar)?,before_locale);
assert_eq!(fs::metadata(&sidecar)?.modified()?,sidecar_time);
fs::File::options().write(true).open(root.join("Family/A.jpg"))?.set_modified(UNIX_EPOCH+Duration::from_secs(99))?;
@@ -209,7 +209,7 @@ fn export_metadata_updates_and_repairs_preserve_source_values() -> TestResult {
assert!(failure(&output).contains("locally changed media"));
let result: Value=serde_json::from_slice(&output.stdout)?;
assert_eq!(result["complete"],false);
- assert_eq!(result["conflicts"],1);
+ assert_eq!(result["failures"]["conflicts"],1);
assert_eq!(fs::read(root.join("Family/Renamed.jpg"))?,vec![0;original.len()]);
assert_eq!(read_json(&root.join("Travel/metadata/Renamed.jpg.json"))["description"],"source advanced");
let after: i64=replica.query_row("SELECT files_cursor FROM photos_collections WHERE id=?1",[family],|r|r.get(0))?;
@@ -278,7 +278,7 @@ fn export_metadata_failure_does_not_block_an_independent_album() -> TestResult {
result["copies"],
json!({"expected":2,"completed":1,"pending":1})
);
- assert_eq!(result["failures"], 1);
+ assert_eq!(result["failures"]["total"], 1);
assert!(
read_json(&root.join("Family/metadata/A.jpg.json"))
.get("custom")
@@ -309,12 +309,12 @@ fn export_retention_restoration_and_album_removal_preserve_history() -> TestResu
export(&home, &root, &["--album", "Travel"]);
move_file(origin,&account,family,(travel,&travel_key),(file,&key)).await;
let result=export(&home,&root,&["--album","Family"]);
- assert_eq!(result["changes"]["retained"],1);
+ assert_eq!(result["changes"]["movedToTrash"],1);
let retained=root.join("Trash/Family/Renamed.jpg");
assert_eq!(fs::read(&retained)?,original);
let retained_record=fs::read(root.join("Trash/Family/metadata/Renamed.jpg.json"))?;
let retained_time=fs::metadata(&retained)?.modified()?;
- assert_eq!(export(&home,&root,&["--album","Family"])["changes"]["retained"],0);
+ assert_eq!(export(&home,&root,&["--album","Family"])["changes"]["movedToTrash"],0);
place(origin,&account,family,&family_key,file,&key,"add-files").await;
export(&home,&root,&["--album","Family"]);
assert_eq!(objects.reads(),initial_reads+1);
@@ -404,7 +404,7 @@ fn export_adopts_relocated_output_and_verifies_later_selections() -> TestResult
]);
assert!(failure(&output).contains("locally changed media"));
assert_eq!(
- serde_json::from_slice::<Value>(&output.stdout)?["conflicts"],
+ serde_json::from_slice::<Value>(&output.stdout)?["failures"]["conflicts"],
1
);
assert_eq!(fs::read(relocated.join("Work/Work.jpg"))?, b"xxxx");
@@ -448,7 +448,7 @@ fn export_restores_a_trashed_original_from_retained_output() -> TestResult {
.await;
let trashed = export(&home, &root, &["--album", "Work"]);
assert_eq!(trashed["copies"]["expected"], 0);
- assert_eq!(trashed["changes"]["retained"], 1);
+ assert_eq!(trashed["changes"]["movedToTrash"], 1);
assert!(!root.join("Work/Work.jpg").exists());
assert!(!root.join("Work/metadata/Work.jpg.json").exists());
assert_eq!(fs::read(root.join("Trash/Work/Work.jpg"))?, b"work");
@@ -540,7 +540,7 @@ fn export_destination_conflicts_do_not_block_other_jobs() -> TestResult {
"2",
"--json",
]);
- assert!(failure(&output).contains("unrelated occupant"));
+ assert!(failure(&output).contains("exists and is not part of this export"));
let result: Value = serde_json::from_slice(&output.stdout)?;
assert_eq!(result["copies"]["completed"], 1);
assert_eq!(result["copies"]["pending"], total);
@@ -971,7 +971,7 @@ fn export_live_pairs_retry_and_reuse_without_rewriting_unchanged_output() -> Tes
);
assert_eq!(
result["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
assert_eq!(objects.reads(), reads);
for (path, before) in paths.iter().zip(unchanged) {
@@ -1205,7 +1205,7 @@ fn export_rejects_invalid_live_archives_and_component_hashes() -> TestResult {
result["copies"],
json!({"expected":8,"completed":1,"pending":7})
);
- assert_eq!(result["failures"], 7);
+ assert_eq!(result["failures"]["total"], 7);
assert_eq!(fs::read(root.join("Album/Good.jpg"))?, b"independent");
assert_eq!(fs::read_dir(root.join("Album/metadata"))?.count(), 1);
for index in 0..archives.len() {
@@ -1400,7 +1400,7 @@ fn export_names_are_portable_and_stable() -> TestResult {
);
assert_eq!(
export(&home, &root, &[])["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
let fresh = TestHome::new();
fresh.write_vault(&home.read_vault());
@@ -1421,7 +1421,7 @@ fn export_names_are_portable_and_stable() -> TestResult {
);
assert_eq!(
export(&fresh, &root, &[])["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
Ok(())
})
@@ -1524,7 +1524,7 @@ fn export_allocates_live_pairs_from_their_actual_extensions() -> TestResult {
let reads = objects.reads();
assert_eq!(
export(&home, &root, &[])["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
let fresh = TestHome::new();
fresh.write_vault(&home.read_vault());
@@ -1672,7 +1672,7 @@ fn export_refills_transfers(live: bool) -> TestResult {
}
assert_eq!(
export(&home, &root, &["--album", &album.to_string()])["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
Ok(())
})
diff --git a/rust/apps/cli-next/tests/cli/export_adoption.rs b/rust/apps/cli-next/tests/cli/export_adoption.rs
index 2a4c8bc8e1..83e922f739 100644
--- a/rust/apps/cli-next/tests/cli/export_adoption.rs
+++ b/rust/apps/cli-next/tests/cli/export_adoption.rs
@@ -606,7 +606,7 @@ fn adoption_requires_initial_presence_and_never_treats_a_failed_refresh_as_histo
.err()
.unwrap()
.to_string()
- .contains("at least one")
+ .contains("no existing original could be matched to this account")
);
assert_eq!(snapshot(&root), before);
}
@@ -1074,7 +1074,7 @@ fn adoption_leaves_unmatched_old_rust_live_files_for_ordinary_conflict_handling(
format!("export fixture {PAIR} component 1").as_bytes(),
);
} else {
- assert_eq!(result.json["conflicts"], 1);
+ assert_eq!(result.json["failures"]["conflicts"], 1);
fs::remove_file(root.join("Family/Pair.mov")).unwrap();
assert!(engine.run(false, &[]).unwrap().complete);
assert_component(
diff --git a/rust/apps/cli-next/tests/cli/export_maintenance.rs b/rust/apps/cli-next/tests/cli/export_maintenance.rs
index 242a392336..ea17263510 100644
--- a/rust/apps/cli-next/tests/cli/export_maintenance.rs
+++ b/rust/apps/cli-next/tests/cli/export_maintenance.rs
@@ -364,13 +364,13 @@ fn export_local_inventory_failure_preserves_output_and_reports_unknown_totals()
let result = run_failure(&home, &root, &[], "missing field `remote`");
assert!(result["files"].is_null());
assert!(result["copies"].is_null());
- assert_eq!(result["failures"], 1);
+ assert_eq!(result["failures"]["total"], 1);
let output = home.run(&["photos", "export", root.to_str().unwrap()]);
assert!(failure(&output).contains("missing field `remote`"));
assert!(
String::from_utf8(output.stdout)
.unwrap()
- .contains("inventory incomplete")
+ .contains("could not determine the full export size")
);
for (path, bytes) in published {
assert_eq!(fs::read(root.join(path)).unwrap(), bytes);
@@ -449,7 +449,7 @@ fn export_snapshot_uses_current_healthy_memberships_and_preserves_raw_bytes() {
assert_eq!(unchanged["copies"], result["copies"]);
assert_eq!(
unchanged["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
for table in ["sources", "album_sources"] {
for action in ["INSERT", "UPDATE", "DELETE"] {
@@ -549,7 +549,10 @@ fn export_keeps_latest_deleted_album_selector_without_rewriting_retained_history
json!([revision(collection(2, "Travel", &key), 70)]),
);
page(&mut server, 2, 0, json!([]), false).create();
- assert_eq!(run(&home, &root, &["--album", "2"], false)["conflicts"], 1);
+ assert_eq!(
+ run(&home, &root, &["--album", "2"], false)["failures"]["conflicts"],
+ 1
+ );
assert_eq!(
fs::read(root.join("Travel/notes.txt")).unwrap(),
b"local addition"
@@ -584,7 +587,10 @@ fn export_discards_failed_downloads_and_services_other_albums() {
let file = revision(file, 30);
page(&mut server, 1, 0, json!([file]), false).create();
let staged = download(&mut server, 10, &bytes, 1);
- assert_eq!(run(&home, &root, &["-j", "1"], false)["conflicts"], 1);
+ assert_eq!(
+ run(&home, &root, &["-j", "1"], false)["failures"]["conflicts"],
+ 1
+ );
let db = export_database(&home);
assert_eq!(count(&db, "SELECT count(*) FROM temporaries"), 0);
run(&home, &root, &["--album", "Second", "-j", "1"], true);
@@ -1608,7 +1614,12 @@ fn export_first_publication_requires_ownership_and_recovers_renamed_bytes() {
} else {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, b"unrelated").unwrap();
- assert!(run(&home, &root, &[], false)["conflicts"].as_i64().unwrap() > 0);
+ assert!(
+ run(&home, &root, &[], false)["failures"]["conflicts"]
+ .as_i64()
+ .unwrap()
+ > 0
+ );
assert_eq!(fs::read(&path).unwrap(), b"unrelated");
fs::remove_file(&path).unwrap();
}
@@ -1936,7 +1947,7 @@ fn export_restores_missing_cross_album_publications_and_preserves_edits() {
page(&mut fixture.server, 2, 50, json!([]), false).create();
if !missing {
let result = run(&fixture.home, root, &["--album", "Renamed"], false);
- assert!(result["conflicts"].as_i64().unwrap() > 0);
+ assert!(result["failures"]["conflicts"].as_i64().unwrap() > 0);
assert_eq!(fs::read(root.join("Renamed/Photo.jpg")).unwrap(), b"wrong");
fs::remove_file(root.join("Renamed/Photo.jpg")).unwrap();
}
@@ -2135,7 +2146,10 @@ fn export_reports_selected_cleanup_failures_without_changing_completed_counts()
result["copies"]["completed"],
if selected_owner { 2 } else { 1 }
);
- assert_eq!(result["failures"].as_i64().unwrap() > 0, selected_owner);
+ assert_eq!(
+ result["failures"]["total"].as_i64().unwrap() > 0,
+ selected_owner
+ );
assert_eq!(count(&db, "SELECT count(*) FROM temporaries"), 1);
assert_eq!(
fs::read(root.join("First/.ente-cleanup.part")).unwrap(),
@@ -2201,7 +2215,7 @@ fn export_leaves_unselected_pending_and_temporary_rows_untouched() {
page(&mut server, 2, 0, json!([revision(other, 50)]), false).create();
let other_get = download(&mut server, 20, &other_bytes, 1);
let result = run(&home, &root, &["--album", "Renamed", "-j", "1"], true);
- assert_eq!(result["failures"], 0);
+ assert_eq!(result["failures"]["total"], 0);
assert_eq!(count(&db, "SELECT count(*) FROM temporaries"), 4);
assert_eq!(
db.query_row("SELECT action FROM pending WHERE file=10", [], |r| r
@@ -2406,7 +2420,7 @@ fn export_recovers_empty_initial_directories_without_claiming_unrelated_contents
let rerun = run(&home, &root, &[], true);
assert_eq!(
rerun["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
assert_eq!(fs::read(&history).unwrap(), bytes);
fetched.assert();
@@ -2415,7 +2429,7 @@ fn export_recovers_empty_initial_directories_without_claiming_unrelated_contents
let notes = folder.join("notes.txt");
fs::write(&notes, b"unrelated").unwrap();
let result = run(&home, &root, &[], false);
- assert!(result["conflicts"].as_i64().unwrap() > 0);
+ assert!(result["failures"]["conflicts"].as_i64().unwrap() > 0);
assert_eq!(fs::read(&notes).unwrap(), b"unrelated");
assert!(!folder.join("metadata.json").exists());
assert_eq!(
diff --git a/rust/apps/cli-next/tests/cli/export_media.rs b/rust/apps/cli-next/tests/cli/export_media.rs
index 2f04dd1c41..e859983f5d 100644
--- a/rust/apps/cli-next/tests/cli/export_media.rs
+++ b/rust/apps/cli-next/tests/cli/export_media.rs
@@ -79,7 +79,7 @@ fn engine_category_filters_preserve_history_and_reuse_excluded_originals() {
let export = engine.prepare(options).unwrap();
let result = engine.execute(export).unwrap();
assert!(result.complete);
- assert_eq!(result.json["changes"]["retained"], 2);
+ assert_eq!(result.json["changes"]["movedToTrash"], 2);
for album in ["First", "Incoming", "Trash/Second", "Trash/Owned"] {
assert_eq!(
fs::read(root.join(album).join("Photo.jpg")).unwrap(),
@@ -90,7 +90,7 @@ fn engine_category_filters_preserve_history_and_reuse_excluded_originals() {
fs::read(root.join("First/.ente-excluded.part")).unwrap(),
b"pending"
);
- assert_eq!(run(&mut engine, true)["changes"]["retained"], 2);
+ assert_eq!(run(&mut engine, true)["changes"]["movedToTrash"], 2);
assert!(!root.join("First/.ente-excluded.part").exists());
fetched.assert();
}
@@ -155,7 +155,7 @@ fn engine_category_recovery_preserves_unknown_albums_after_database_loss() {
let export = engine.prepare(options).unwrap();
let result = engine.execute(export).unwrap();
assert!(!result.complete);
- assert_eq!(result.json["failures"], 1);
+ assert_eq!(result.json["failures"]["total"], 1);
assert_eq!(result.completed, 1);
for album in ["First", "Second", "Current"] {
assert_eq!(
@@ -169,7 +169,7 @@ fn engine_category_recovery_preserves_unknown_albums_after_database_loss() {
options.exclude_albums.push("Second".into());
let export = engine.prepare(options).unwrap();
assert!(engine.execute(export).unwrap().complete);
- assert_eq!(run(&mut engine, true)["changes"]["retained"], 2);
+ assert_eq!(run(&mut engine, true)["changes"]["movedToTrash"], 2);
engine.database = "history-only.db".into();
let mut options = engine.options(true, &[]);
options.exclude_shared = true;
@@ -213,7 +213,7 @@ fn engine_category_filters_recheck_recovered_metadata() {
let export = engine.prepare(options).unwrap();
let result = engine.execute(export).unwrap();
assert!(!result.complete);
- assert_eq!(result.json["failures"], 1);
+ assert_eq!(result.json["failures"]["total"], 1);
assert_eq!(
fs::read(engine.root().join("Second/Photo.jpg")).unwrap(),
b"original"
@@ -332,7 +332,7 @@ fn engine_preserves_local_media_and_restores_missing_copies() {
engine.catalog.files = BTreeMap::from([((1, 10), changed.clone()), ((2, 10), changed)]);
for _ in 0..2 {
let result = run(&mut engine, false);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(
result["copies"],
json!({"expected":2,"completed":1,"pending":1})
@@ -421,7 +421,7 @@ fn engine_checks_previous_bytes_before_source_and_layout_replacement() {
engine.catalog.files = BTreeMap::from([((1, 10), new.clone()), ((2, 10), new)]);
let fetched = download(&mut server, 10, &bytes, 1);
let result = run(&mut engine, false);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(result["copies"]["completed"], 1);
assert_eq!(fs::read(&photo).unwrap(), b"bad");
assert_eq!(fs::metadata(&photo).unwrap().modified().unwrap(), modified);
@@ -496,7 +496,7 @@ fn engine_restores_a_new_layout_after_missing_interrupted_retention() {
db.execute_batch("DROP TRIGGER stop_retention;").unwrap();
if old_live {
fs::write(root.join("First/Motion.mov"), b"local edit").unwrap();
- assert_eq!(run(&mut engine, false)["conflicts"], 1);
+ assert_eq!(run(&mut engine, false)["failures"]["conflicts"], 1);
assert_eq!(
fs::read(root.join("First/Motion.mov")).unwrap(),
b"local edit"
@@ -524,7 +524,7 @@ fn engine_restores_a_new_layout_after_missing_interrupted_retention() {
)["ente"]["components"][0]["hash"],
b64::encode(&hash::hash(b"old", Some(64), None).unwrap())
);
- assert_eq!(run(&mut engine, true)["changes"]["retained"], 0);
+ assert_eq!(run(&mut engine, true)["changes"]["movedToTrash"], 0);
assert_eq!(
count(
&db,
@@ -575,7 +575,7 @@ fn engine_checks_both_live_components_when_only_one_source_component_changes() {
let new = revision(new, 30);
engine.catalog.files = BTreeMap::from([((1, 10), new.clone()), ((2, 10), new)]);
let fetched = download(&mut server, 10, &bytes, 1);
- assert_eq!(run(&mut engine, false)["conflicts"], 1);
+ assert_eq!(run(&mut engine, false)["failures"]["conflicts"], 1);
assert_eq!(fs::read(&photo).unwrap(), b"bad");
assert_component(&root, "First", "Motion.mov", b"old");
assert_component(&root, "Second", "Motion.heic", b"old");
@@ -615,7 +615,7 @@ fn engine_recovery_checks_live_siblings_before_acknowledging_publication() {
.unwrap();
db.execute_batch("DROP TRIGGER stop_ack;").unwrap();
let result = run(&mut engine, false);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(
fs::read(root.join("First/Motion.mov")).unwrap(),
b"edited video"
@@ -683,7 +683,7 @@ fn engine_recovery_preserves_edits_at_either_move_endpoint() {
continue;
}
let result = run(&mut engine, false);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(fs::read(changed).unwrap(), b"local edit");
assert_component(&root, "Second", "Renamed.jpg", b"original");
assert_eq!(
@@ -830,13 +830,13 @@ fn engine_links_live_components_and_preserves_edits() {
engine.catalog.files.insert((2, 11), other);
let independent = download(&mut server, 11, &bytes, 1);
let result = run(&mut engine, false);
- assert_eq!(result["conflicts"], 2);
+ assert_eq!(result["failures"]["conflicts"], 2);
assert_eq!(result["copies"]["completed"], 1);
assert_component(&root, "Second", "Other.jpg", b"independent");
assert_eq!(fs::read(&second).unwrap(), b"edited in place");
fs::remove_file(&first).unwrap();
fs::write(&first, b"independent local edit").unwrap();
- assert_eq!(run(&mut engine, false)["conflicts"], 2);
+ assert_eq!(run(&mut engine, false)["failures"]["conflicts"], 2);
assert_eq!(fs::read(&first).unwrap(), b"independent local edit");
independent.assert();
fetched.assert();
@@ -879,7 +879,7 @@ fn engine_recovers_interrupted_link_publication() {
for _ in 0..2 {
let result = engine.run(false, &["Second"]).unwrap();
assert!(!result.complete);
- assert_eq!(result.json["conflicts"], 1);
+ assert_eq!(result.json["failures"]["conflicts"], 1);
}
assert_eq!(fs::read(&photo).unwrap(), b"modified");
fs::write(&photo, b"original").unwrap();
@@ -940,7 +940,7 @@ fn engine_rechecks_link_source_before_completion() {
});
let result = result.unwrap();
assert!(!result.complete);
- assert_eq!(result.json["conflicts"], 2);
+ assert_eq!(result.json["failures"]["conflicts"], 2);
assert_eq!(result.json["copies"]["completed"], 2);
assert_eq!(fs::read(&first).unwrap(), b"modified");
assert_eq!(
@@ -949,7 +949,7 @@ fn engine_rechecks_link_source_before_completion() {
);
let result = engine.run(false, &["First", "Second", "Fourth"]).unwrap();
assert!(!result.complete);
- assert_eq!(result.json["conflicts"], 3);
+ assert_eq!(result.json["failures"]["conflicts"], 3);
assert_eq!(result.json["copies"]["completed"], 0);
fetched.assert();
}
diff --git a/rust/apps/cli-next/tests/cli/export_resources.rs b/rust/apps/cli-next/tests/cli/export_resources.rs
index ab9a158b05..158f7298ac 100644
--- a/rust/apps/cli-next/tests/cli/export_resources.rs
+++ b/rust/apps/cli-next/tests/cli/export_resources.rs
@@ -147,7 +147,7 @@ fn export_large_original_and_live_photo_with_bounded_memory() -> TestResult {
assert_eq!(reads, 2);
assert_eq!(
measure(&home, &root, "large media unchanged")?["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
assert_eq!(museum.object_store().reads(), reads);
Ok(())
@@ -203,7 +203,7 @@ fn export_many_records_unchanged_resource_check() -> TestResult {
assert_eq!(result["copies"]["completed"], 2000);
assert_eq!(
result["changes"],
- json!({"exported":0,"metadataUpdated":0,"renamed":0,"retained":0})
+ json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
assert_eq!(museum.object_store().reads(), reads);
for (path, modified) in observed {
diff --git a/rust/apps/cli-next/tests/cli/export_sources.rs b/rust/apps/cli-next/tests/cli/export_sources.rs
index 5c02d75ca3..59621e0f10 100644
--- a/rust/apps/cli-next/tests/cli/export_sources.rs
+++ b/rust/apps/cli-next/tests/cli/export_sources.rs
@@ -114,7 +114,7 @@ fn export_preserves_failed_records_and_advances_the_page_atomically() {
initial["copies"],
json!({"expected":4,"completed":2,"pending":2})
);
- assert_eq!(initial["failures"], 2);
+ assert_eq!(initial["failures"]["total"], 2);
assert_eq!(fs::read(root.join("First/Good.jpg")).unwrap(), b"good");
assert_eq!(fs::read(root.join("First/Later.jpg")).unwrap(), b"later");
let db = database(&home);
@@ -174,7 +174,7 @@ fn export_preserves_failed_records_and_advances_the_page_atomically() {
page(&mut server, 2, 10, json!([removed]), false).create();
let result = run(&home, &root, &["--album", "Second"], true);
assert_eq!(result["copies"]["expected"], 0);
- assert_eq!(result["failures"], 0);
+ assert_eq!(result["failures"]["total"], 0);
assert_eq!(
db.query_row(
"SELECT count(*) FROM photos_files WHERE collection_id=2 AND id=11",
@@ -186,7 +186,7 @@ fn export_preserves_failed_records_and_advances_the_page_atomically() {
);
assert!(!root.join("Second/Broken.jpg").exists());
assert_eq!(
- run(&home, &root, &["--album", "Second"], true)["failures"],
+ run(&home, &root, &["--album", "Second"], true)["failures"]["total"],
0
);
}
@@ -449,7 +449,10 @@ fn export_releases_a_deleted_album_reservation_before_its_first_association() {
.with_body(json!({"collections":[album]}).to_string())
.create();
page(&mut server, 1, 0, json!([]), false).create();
- assert_eq!(run(&home, &root, &["--album", "1"], false)["conflicts"], 1);
+ assert_eq!(
+ run(&home, &root, &["--album", "1"], false)["failures"]["conflicts"],
+ 1
+ );
let db = export_database(&home);
let reservation = || {
db.query_row(
@@ -462,7 +465,7 @@ fn export_releases_a_deleted_album_reservation_before_its_first_association() {
let pending = reservation();
assert_eq!(pending, "Family");
assert_eq!(
- run(&home, &root, &["--album", "Family"], false)["conflicts"],
+ run(&home, &root, &["--album", "Family"], false)["failures"]["conflicts"],
1
);
run(&home, &root, &["--exclude-album", "Family"], true);
@@ -556,7 +559,7 @@ fn export_clears_deleted_adopted_album_rename_reservations() {
.match_query(mockito::Matcher::Any)
.with_body(json!({"collections":[renamed]}).to_string())
.create();
- assert_eq!(run(&fresh, &root, &[], false)["conflicts"], 2);
+ assert_eq!(run(&fresh, &root, &[], false)["failures"]["conflicts"], 2);
let reservation = || {
db.query_row("SELECT name1 FROM pending WHERE owner=?1", [&owner], |r| {
r.get::<_, String>(0)
@@ -672,7 +675,7 @@ fn export_rejects_offline_early_and_reports_path_conflicts() {
fs::write(&target, b"outside export").unwrap();
fs::remove_file(root.join("First/Good.jpg")).unwrap();
std::os::unix::fs::symlink(&target, root.join("First/Good.jpg")).unwrap();
- assert_eq!(run(&home, &root, &[], false)["conflicts"], 1);
+ assert_eq!(run(&home, &root, &[], false)["failures"]["conflicts"], 1);
assert_eq!(fs::read(&target).unwrap(), b"outside export");
assert!(
fs::symlink_metadata(root.join("First/Good.jpg"))
@@ -682,13 +685,13 @@ fn export_rejects_offline_early_and_reports_path_conflicts() {
fs::remove_file(root.join("First/Good.jpg")).unwrap();
let external_metadata = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(external_metadata.path(), root.join("First/metadata")).unwrap();
- assert_eq!(run(&home, &root, &[], false)["conflicts"], 1);
+ assert_eq!(run(&home, &root, &[], false)["failures"]["conflicts"], 1);
assert_eq!(fs::read_dir(external_metadata.path()).unwrap().count(), 0);
fs::remove_file(root.join("First/metadata")).unwrap();
fs::write(root.join("First/Good.jpg"), b"unrelated").unwrap();
}
let result = run(&home, &root, &[], false);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(result["copies"]["pending"], 1);
assert_eq!(fs::read(root.join("First/Good.jpg")).unwrap(), b"unrelated");
assert!(!root.join("First/Good-1.jpg").exists());
@@ -714,7 +717,7 @@ fn export_rejects_offline_early_and_reports_path_conflicts() {
let allocated = reservation();
assert_eq!(allocated, "Good.jpg");
let unchanged = page(&mut server, 1, 10, json!([]), false).create();
- assert_eq!(run(&home, &root, &[], false)["conflicts"], 1);
+ assert_eq!(run(&home, &root, &[], false)["failures"]["conflicts"], 1);
assert_eq!(reservation(), allocated);
assert_eq!(fs::read(root.join("First/Good.jpg")).unwrap(), b"unrelated");
unchanged.remove();
@@ -736,7 +739,7 @@ fn export_rejects_offline_early_and_reports_path_conflicts() {
result["copies"],
json!({"expected":2,"completed":1,"pending":1})
);
- assert_eq!(result["conflicts"], 1);
+ assert_eq!(result["failures"]["conflicts"], 1);
assert_eq!(reservation(), allocated);
assert_eq!(fs::read(root.join("First/Good.jpg")).unwrap(), b"unrelated");
assert_eq!(
@@ -1062,7 +1065,7 @@ fn export_page_and_recognized_failures_roll_back_together_on_storage_failure() {
broken["metadata"]["encryptedData"] = json!("broken");
page(&mut server, 1, 0, json!([good, broken]), false).create();
let result = run_failure(&home, &root, &[], "fixture storage failure");
- assert_eq!(result["failures"], 2);
+ assert_eq!(result["failures"]["total"], 2);
assert!(result["files"].is_null());
assert_eq!(
db.query_row("SELECT count(*) FROM photos_files", [], |r| r
diff --git a/rust/apps/cli-next/tests/cli/main.rs b/rust/apps/cli-next/tests/cli/main.rs
index 31572f3a9e..1366c20c1b 100644
--- a/rust/apps/cli-next/tests/cli/main.rs
+++ b/rust/apps/cli-next/tests/cli/main.rs
@@ -29,7 +29,7 @@ fn completion_prints_scripts_without_storage() {
let script = String::from_utf8(output.stdout).unwrap();
assert!(serde_json::from_str::<Value>(&script).is_err(), "{shell}");
for item in [
- "help-all",
+ "migration",
"account",
"paste",
"hardlinks",
@@ -45,6 +45,60 @@ fn completion_prints_scripts_without_storage() {
}
}
+#[test]
+fn migration_hints_respect_command_and_argument_boundaries() {
+ let binary = format!("ente-cli-next{}", std::env::consts::EXE_SUFFIX);
+ let home = TestHome::new();
+ let path = home.dir.path().join("unused");
+ for (args, suggestion) in [
+ ("export", "photos export DIR"),
+ ("--offline account --json add", "account login --app"),
+ ("accounts --no-input get-token", "account token --app"),
+ (
+ "auth decrypt in.json out.txt",
+ "auth decrypt INPUT --output OUTPUT",
+ ),
+ (
+ "admin disable-2fa --user [email protected]",
+ "admin user disable-totp",
+ ),
+ ] {
+ let output = home
+ .command(&args.split_whitespace().collect::<Vec<_>>())
+ .env("ENTE_CLI_HOME", &path)
+ .env("ENTE_CLI_VAULT_KEY", "invalid")
+ .output()
+ .unwrap();
+ let error = failure(&output);
+ assert!(error.contains(suggestion), "{args}: {error}");
+ assert!(
+ error.contains(&format!("\n {binary} help migration\n")),
+ "{args}: {error}"
+ );
+ assert!(
+ error.lines().all(|line| line == line.trim_end()),
+ "{args}: {error}"
+ );
+ assert_eq!(output.status.code(), Some(2));
+ assert!(output.stdout.is_empty());
+ }
+ for args in [
+ "paste create export --unknown",
+ "photos --account export album view version --unknown",
+ "auth decrypt --output version in.json --unknown",
+ "paste create -- version export",
+ ] {
+ let output = home
+ .command(&args.split_whitespace().collect::<Vec<_>>())
+ .env("ENTE_CLI_HOME", &path)
+ .output()
+ .unwrap();
+ let error = failure(&output);
+ assert!(!error.contains("help migration"), "{args}: {error}");
+ }
+ assert!(!path.exists());
+}
+
#[test]
fn reads_do_not_initialize_storage() {
let binary = format!("ente-cli-next{}", std::env::consts::EXE_SUFFIX);
@@ -55,7 +109,7 @@ fn reads_do_not_initialize_storage() {
fs::create_dir(&path).unwrap();
}
let help = success(
- home.command(&["--help-all"])
+ home.command(&["help", "--all"])
.env("ENTE_CLI_HOME", &path)
.env("ENTE_CLI_VAULT_KEY", "invalid")
.output()
@@ -64,7 +118,7 @@ fn reads_do_not_initialize_storage() {
assert!(help.stderr.is_empty());
let help = String::from_utf8(help.stdout).unwrap();
assert!(help.contains(&format!("=== {binary} ===")));
- assert!(help.contains("Usage: ente-cli-next [OPTIONS] <COMMAND>"));
+ assert!(help.contains(&format!("Usage: {binary} [OPTIONS] <COMMAND>")));
assert!(help.contains(&format!("=== {binary} photos file download ===")));
assert!(help.contains(&format!("=== {binary} vault key generate ===")));
assert!(help.contains("--hardlinks"));
@@ -74,6 +128,64 @@ fn reads_do_not_initialize_storage() {
assert!(help.contains(&format!("=== {binary} paste create ===")));
assert!(help.contains(&format!("=== {binary} paste consume ===")));
assert!(help.contains(&format!("=== {binary} account token ===")));
+ let migration = success(
+ home.command(&["help", "migration", "--json", "--offline", "--no-input"])
+ .env("ENTE_CLI_HOME", &path)
+ .env("ENTE_CLI_VAULT_KEY", "invalid")
+ .output()
+ .unwrap(),
+ );
+ assert!(migration.stderr.is_empty());
+ let migration = String::from_utf8(migration.stdout).unwrap();
+ assert!(migration.contains("account login --app"));
+ assert!(migration.lines().all(|line| line == line.trim_end()));
+ for commands in [
+ vec![],
+ vec!["help"],
+ vec!["photos", "file", "view"],
+ vec!["accounts", "login"],
+ ] {
+ let mut topic = vec!["help"];
+ topic.extend(&commands);
+ let mut flag = commands;
+ flag.push("--help");
+ let read_help = |args: &[&str]| {
+ let output = success(
+ home.command(args)
+ .env("ENTE_CLI_HOME", &path)
+ .env("ENTE_CLI_VAULT_KEY", "invalid")
+ .output()
+ .unwrap(),
+ );
+ assert!(output.stderr.is_empty());
+ String::from_utf8(output.stdout).unwrap()
+ };
+ let expected = read_help(&flag);
+ assert_eq!(
+ read_help(&topic).split_whitespace().collect::<Vec<_>>(),
+ expected.split_whitespace().collect::<Vec<_>>()
+ );
+ if topic.len() > 2 {
+ topic.swap(0, 1);
+ assert_eq!(
+ read_help(&topic).split_whitespace().collect::<Vec<_>>(),
+ expected.split_whitespace().collect::<Vec<_>>()
+ );
+ }
+ }
+ for args in [
+ vec!["help", "photos", "unknown"],
+ vec!["help", "--all", "migration"],
+ ] {
+ let output = home
+ .command(&args)
+ .env("ENTE_CLI_HOME", &path)
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(2));
+ assert!(output.stdout.is_empty());
+ }
+ assert_eq!(path.exists(), existing_home);
for command in ["login", "token"] {
let missing_app = home
.command(&["account", command])
@@ -325,7 +437,7 @@ fn vault_schema_version_is_checked_after_decryption() {
home.write_vault_document(&json!({"schema_version": 2, "state": Value::Null}));
let original = fs::read(home.dir.path().join("vault.json")).unwrap();
let error = failure(&home.run(&["account", "list"]));
- assert!(error.contains("unsupported CLI vault schema 2; this build supports 1."));
+ assert!(error.contains("cannot read CLI vault format 2; this CLI supports 1."));
assert!(error.contains(&format!(
"To start fresh, move {} aside, then log in again.",
home.dir.path().canonicalize().unwrap().join("vault.json").display(),
diff --git a/rust/apps/cli-next/tests/cli/museum.rs b/rust/apps/cli-next/tests/cli/museum.rs
index dab8004289..29b1bc5007 100644
--- a/rust/apps/cli-next/tests/cli/museum.rs
+++ b/rust/apps/cli-next/tests/cli/museum.rs
@@ -566,7 +566,7 @@ async fn exercise(origin: String) -> TestResult {
.unwrap();
for flag in ["--exclude-shared", "--exclude-hidden"] {
let result = adopted.json(&["photos", "export", shared_export.to_str().unwrap(), flag]);
- assert_eq!(result["changes"]["retained"], 0);
+ assert_eq!(result["changes"]["movedToTrash"], 0);
assert_eq!(
fs::read(shared_export.join("Monsoon 🌧/original.jpg")).unwrap(),
original
@@ -591,7 +591,7 @@ async fn exercise(origin: String) -> TestResult {
&album.to_string(),
]);
assert_eq!(revoked["copies"]["expected"], 0);
- assert_eq!(revoked["changes"]["retained"], 1);
+ assert_eq!(revoked["changes"]["movedToTrash"], 1);
assert!(!shared_export.join("Monsoon 🌧/original.jpg").exists());
assert_eq!(
fs::read(shared_export.join("Trash/Monsoon 🌧/original.jpg")).unwrap(),
@@ -609,7 +609,7 @@ async fn exercise(origin: String) -> TestResult {
shared_export.to_str().unwrap(),
"--album",
&album.to_string()
- ])["changes"]["retained"],
+ ])["changes"]["movedToTrash"],
0
);
diff --git a/rust/crates/photos-export/src/legacy/mod.rs b/rust/crates/photos-export/src/legacy/mod.rs
index 3c5ea2164b..c40a81290c 100644
--- a/rust/crates/photos-export/src/legacy/mod.rs
+++ b/rust/crates/photos-export/src/legacy/mod.rs
@@ -28,7 +28,7 @@ impl Failures {
pub fn record(&mut self, result: Result<()>, context: &str) -> Result<()> {
if let Err(error) = result {
if crate::fatal(&error) {
- return Err(error.context(format!("adoption preflight incomplete: {context}")));
+ return Err(error.context(format!("cannot take over this export: {context}")));
}
self.count += 1;
if self.examples.len() < 10 {
@@ -55,7 +55,7 @@ impl Failures {
pub fn finish(&self) -> Result<()> {
ensure!(
self.count == 0,
- "adoption preflight failed: {}",
+ "cannot take over this export: {}",
self.message()
);
Ok(())
@@ -171,7 +171,7 @@ impl Preflight<'_> {
if result.is_err() {
store.db.execute("UPDATE desired_albums SET failure='adoption album preflight failed' WHERE id=?1",[id])?;
}
- failures.record(result, &format!("album:{id}"))?;
+ failures.record(result, &format!("album {:?} (ID {id})", record.album.name))?;
}
let mut after = (0, String::new());
let mut expected = None;
@@ -239,7 +239,10 @@ impl Preflight<'_> {
.await;
failures.record(
result,
- &format!("file:{}:{}", item.placement.album, item.placement.file),
+ &format!(
+ "file {:?} (ID {}, album {})",
+ item.placement.name, item.placement.file, item.placement.album
+ ),
)?;
}
failures.record((|| {
@@ -252,9 +255,9 @@ impl Preflight<'_> {
if !self.matching_root && verified == 0 && failures.count == 0 {
failures.record(
Err(anyhow::anyhow!(
- "at least one existing active original must verify"
+ "no existing original could be matched to this account"
)),
- "source association",
+ "account verification",
)?;
}
failures.finish()
diff --git a/rust/crates/photos-export/src/lib.rs b/rust/crates/photos-export/src/lib.rs
index 316bfe8143..08d85d97f0 100644
--- a/rust/crates/photos-export/src/lib.rs
+++ b/rust/crates/photos-export/src/lib.rs
@@ -169,7 +169,7 @@ impl Export {
if self.root_lock.is_some() {
failures.record(
adopt::scan(&self.destination, index, desktop.as_ref()),
- "native records",
+ "this CLI's export records",
)?;
}
if self.adopting {
@@ -281,7 +281,7 @@ impl Export {
refreshed?;
legacy::scope(&store, &self.options, index.as_ref(), report)?;
if let Some(index) = &index {
- report("Verifying every existing active legacy original before adoption.");
+ report("Checking the existing files before taking over this export.");
legacy::Preflight {
root: &self.destination,
store: &store,
@@ -518,7 +518,7 @@ fn select(
!= 0
{
report(&format!(
- "{unit}: last known category is unavailable; use --exclude-album {id} or remove {flags}"
+ "{unit}: cannot determine whether this album is excluded by {flags}; use --exclude-album {id} or remove {flags}"
));
}
}
@@ -898,7 +898,7 @@ fn summary(store: &Store, destination: &Path, prepared: bool) -> Result<Summary>
.db
.query_row("SELECT bound FROM export WHERE id=1", [], |r| r.get(0))?;
let complete = bound && work_complete(store, prepared)?;
- let result = json!({"output":destination.to_string_lossy(),"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"retained":retained},"failures":failures,"conflicts":conflicts});
+ let result = json!({"output":destination.to_string_lossy(),"complete":complete,"files":if unknown {None}else{Some(files)},"copies":if unknown {None}else{Some(json!({"expected":expected,"completed":completed,"pending":expected-completed}))},"changes":{"exported":exported,"metadataUpdated":metadata_updated,"renamed":renamed,"movedToTrash":retained},"failures":{"total":failures,"conflicts":conflicts}});
Ok(Summary {
json: result,
complete,
diff --git a/rust/crates/photos-export/src/reconcile.rs b/rust/crates/photos-export/src/reconcile.rs
index a48780a3eb..16d2c52877 100644
--- a/rust/crates/photos-export/src/reconcile.rs
+++ b/rust/crates/photos-export/src/reconcile.rs
@@ -419,7 +419,10 @@ impl Run<'_> {
}
ensure!(
Properties::optional(&path)?.is_none() || owned,
- super::Conflict(format!("at {}: unrelated occupant", path.display()))
+ super::Conflict(format!(
+ "{} exists and is not part of this export",
+ path.display()
+ ))
);
disk::create_dir_all(path.parent().context("publication has no parent")?)?;
disk::rename(&source, &path)?;
@@ -430,7 +433,10 @@ impl Run<'_> {
if !matches {
ensure!(
!path.try_exists()? || owned,
- super::Conflict(format!("at {}: unrelated occupant", path.display()))
+ super::Conflict(format!(
+ "{} exists and is not part of this export",
+ path.display()
+ ))
);
self.clear_action(target)?;
self.discard(&temporary)?;
@@ -1194,7 +1200,10 @@ impl Run<'_> {
.unwrap_or(false);
ensure!(
Properties::optional(&path)?.is_none() || owned || renamed,
- super::Conflict(format!("at {}: unrelated occupant", path.display()))
+ super::Conflict(format!(
+ "{} exists and is not part of this export",
+ path.display()
+ ))
);
}
let location = Location {