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
8 changes: 6 additions & 2 deletions crates/dg/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1273,8 +1273,12 @@ async fn balance(ctx: &Ctx) -> Result<()> {
// name register
// ---------------------------------------------------------------------------------------

/// DPNS registration cost for a non-contested name (preorder + domain), credits; an estimate.
const DPNS_ESTIMATE_CREDITS: u64 = 2_000_000_000;
/// DPNS registration cost for a non-contested name (preorder + domain), credits: an upper
/// bound. A 9-character name was charged 71,000,000 credits (0.00071 DASH) on devnet bonsia
/// (QW2-080); the old 0.02 DASH quote was 28 times that. A 63-character label stores about
/// 110 more bytes (the label and its normalized form, each indexed): a few million credits at
/// Platform's ~27,700 credits per byte, well inside the margin.
const DPNS_ESTIMATE_CREDITS: u64 = 100_000_000;

async fn name_register(ctx: &Ctx, label: &str, master: Option<&std::path::Path>) -> Result<()> {
let label = label.trim().trim_end_matches(".dash");
Expand Down
70 changes: 61 additions & 9 deletions crates/dg/src/ci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ async fn runner_list(ctx: &Ctx, repo: &str) -> Result<()> {
let r = Reader::open(ctx, repo).await?;
let runners = RunnerReader::new(&r.client).list(&r.repo).await?;
ctx.emit(
json!({ "count": runners.len(), "runners": runners }),
json!({ "count": runners.len(), "runners": crate::fmt::with_ids(&runners) }),
|| {
if runners.is_empty() {
println!("no runners");
Expand Down Expand Up @@ -602,8 +602,9 @@ fn gives_log_url(profile: &Profile) -> bool {
}
}

/// Refuse, before anything is uploaded, storage none of whose profiles records an https or
/// IPFS address (a plain-http or private bucket): the check run could not name the log.
/// Refuse, before anything is uploaded: no storage of your own at all (a Platform-only
/// repository and no `--storage`), or storage none of whose profiles records an https or IPFS
/// address (a plain-http or private bucket), where the check run could not name the log.
fn check_log_storage(storage: Option<&str>) -> Result<()> {
let (list, replicas) = match storage {
Some(s) => (Some(s.to_string()), None),
Expand All @@ -614,8 +615,10 @@ fn check_log_storage(storage: Option<&str>) -> Result<()> {
};
let policy = StoragePolicy::from_git_values(list.as_deref(), replicas.as_deref(), None)?
.resolve(&StorageProfiles::load()?)?;
if policy.external.is_empty() || policy.external.iter().any(|(_, p)| gives_log_url(p)) {
// No external storage at all: `asset_targets` explains that.
if policy.external.is_empty() {
return Err(no_log_storage(storage.is_some()));
}
if policy.external.iter().any(|(_, p)| gives_log_url(p)) {
return Ok(());
}
Err(UserError::new(
Expand All @@ -637,9 +640,31 @@ fn check_log_storage(storage: Option<&str>) -> Result<()> {
.into())
}

/// E501 for `--log` / `--artifact` with no storage of your own: they are uploaded there, never
/// to Platform. Before, this was the release command's "release not created: no storage for
/// the assets" (QW2-077).
fn no_log_storage(storage_given: bool) -> anyhow::Error {
let why = if storage_given {
"the --storage given names no storage of your own (only Platform)"
} else {
"dash.storage names none (it is unset, or platform), and no --storage was given"
};
UserError::new(
codes::STORAGE_CONFIG,
"check run not reported: --log and --artifact need your own storage",
)
.cause(format!(
"a check run's log and artifacts are uploaded to your own storage (an S3 bucket with an https public_url, or IPFS) and the run records their URL; {why}"
))
.fix("pass --storage <profile> (`dg storage list` shows yours; `dg storage add <name> …` adds one)")
.fix("or report the run without --log / --artifact")
.note("nothing was uploaded or written")
.into()
}

/// The log's https (else `ipfs://`) URL and its SHA-256, after uploading it to `storage`.
async fn upload_log(path: &Path, storage: Option<&str>) -> Result<(String, [u8; 32])> {
let (targets, required) = crate::release::asset_targets(storage)?;
let (targets, required) = crate::release::asset_targets(storage, "check run not reported")?;
let (asset, _) = crate::release::upload_asset(path, &targets, required).await?;
let url = log_url(&asset.uris)
.cloned()
Expand Down Expand Up @@ -703,7 +728,9 @@ async fn report(ctx: &Ctx, a: &ReportArgs) -> Result<()> {
// text once the repository's visibility says whether it is kept (a private repository's
// run drops it with a warning instead).
let usage = |e: forge_core::error::Error| match e {
forge_core::error::Error::Config(m) => crate::errors::usage(m),
forge_core::error::Error::Config(m) | forge_core::error::Error::InvalidInput(m) => {
crate::errors::usage(m)
}
other => other.into(),
};
r.for_visibility(Visibility::Private)
Expand Down Expand Up @@ -909,7 +936,7 @@ async fn upload_artifacts(
paths: &[PathBuf],
storage: Option<&str>,
) -> Result<(Option<String>, Vec<String>)> {
let (targets, required) = crate::release::asset_targets(storage)?;
let (targets, required) = crate::release::asset_targets(storage, "check run not reported")?;
let mut uploaded = Vec::new();
for p in paths {
let (mut asset, _) = crate::release::upload_asset(p, &targets, required).await?;
Expand Down Expand Up @@ -984,7 +1011,7 @@ async fn status(ctx: &Ctx, repo: &str, sha: &str) -> Result<()> {
})
.collect();
ctx.emit(
json!({ "headOid": sha, "checks": rows, "url": url }),
json!({ "headOid": sha, "checks": crate::fmt::with_ids(&rows), "url": url }),
|| {
if runs.is_empty() {
println!("no checks reported for {}", &sha[..7.min(sha.len())]);
Expand Down Expand Up @@ -1022,6 +1049,31 @@ async fn status(ctx: &Ctx, repo: &str, sha: &str) -> Result<()> {
mod tests {
use super::*;

/// QW2-077: `--log` on a Platform-only repository names the flag and the fix, not the
/// release command's "release not created".
#[test]
fn a_log_without_storage_says_it_needs_storage() {
let e = no_log_storage(false);
let u = e.downcast_ref::<UserError>().unwrap();
assert_eq!((u.code, u.exit_code()), ("E501", 5));
assert!(u.message.starts_with("check run not reported"), "{u:?}");
assert!(!u.message.contains("release"), "{u:?}");
assert!(
u.cause
.as_deref()
.unwrap()
.contains("no --storage was given"),
"{u:?}"
);
assert!(u.fix[0].contains("--storage <profile>"), "{u:?}");
let given = no_log_storage(true);
let u = given.downcast_ref::<UserError>().unwrap();
assert!(
u.cause.as_deref().unwrap().contains("the --storage given"),
"{u:?}"
);
}

/// QW2-086: a report of a check the policy pins to another source says it will not count.
#[test]
fn a_check_pinned_to_another_source_is_noted() {
Expand Down
38 changes: 37 additions & 1 deletion crates/dg/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,25 @@ fn invalid_ref(input: &str, why: &str) -> anyhow::Error {
.into()
}

/// Refuse a `what` argument (a comment, review or thread id) that cannot be a document id,
/// before any read: E201 naming the argument and where the ids are listed (`listed_by`).
/// Before, `dg issue delete-comment <repo> 2` was E204 "invalid configuration" with a raw
/// "Identifier must be 32 bytes long" (QW2-076).
pub fn document_id_arg(value: &str, what: &str, listed_by: &str) -> Result<()> {
if looks_like_identity_id(value) {
return Ok(());
}
Err(UserError::new(
codes::USAGE,
format!("{:?} is not a {what}", crate::fmt::safe(value)),
)
.cause(format!(
"a {what} is a document id (about 44 base58 characters), not a number"
))
.fix(format!("{listed_by} lists the ids"))
.into())
}

/// Whether `s` is plausibly a base58 identity id (32-byte id ≈ 42-44 base58 chars, no
/// `0OIl` and no `/`). Used to distinguish an identity owner from a DPNS label.
fn looks_like_identity_id(s: &str) -> bool {
Expand Down Expand Up @@ -314,11 +333,28 @@ pub async fn resolve_identity(client: &PlatformClient, who: &str, what: &str) ->

#[cfg(test)]
mod tests {
use super::{looks_like_identity_id, RepoRef};
use super::{document_id_arg, looks_like_identity_id, RepoRef};

// A real testnet identity id shape (DEPLOYER).
const ID: &str = "8hJmcHWTsdvkHyCrk4UgjbyugDAmE7QfuCTQXpXAc7nB";

/// QW2-076: a number where a comment id goes is E201 naming the argument, not E204.
#[test]
fn a_document_id_argument_is_checked_before_any_read() {
assert!(document_id_arg(ID, "comment id", "`dg issue view`").is_ok());
let e =
document_id_arg("2", "comment id", "`dg issue view <repo> <n> --json`").unwrap_err();
let u = e
.downcast_ref::<forge_core::user_error::UserError>()
.unwrap();
assert_eq!((u.code, u.exit_code()), ("E201", 2));
assert_eq!(u.message, "\"2\" is not a comment id");
assert!(
u.fix[0].contains("dg issue view <repo> <n> --json"),
"{u:?}"
);
}

#[test]
fn parses_owner_slash_name() {
let r = RepoRef::parse(&format!("{ID}/my-repo")).unwrap();
Expand Down
34 changes: 33 additions & 1 deletion crates/dg/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ fn prompt_blocker(yes: bool, json: bool, stdin_tty: bool) -> Option<&'static str
}
}

/// The E802 fix for `prompt`: "check the estimate" only when one was shown (in the prompt, or
/// a price line printed before it, [`crate::fmt::ESTIMATE_SHOWN`]); a prompt that names the
/// write without a price (`dg collab accept`, `dg issue close`) is reviewed instead (QW2-079).
fn confirm_fix(prompt: &str, estimate_shown: bool) -> &'static str {
if estimate_shown || prompt.contains(" DASH") {
"check the estimate, then run the same command with --yes"
} else {
"check what it will do, then run the same command with --yes"
}
}

/// The E802 for a prompt that cannot be asked, with `cause`; callers add the fixes.
fn confirmation_required(cause: String) -> UserError {
UserError::new(codes::CONFIRMATION_REQUIRED, "confirmation required")
Expand Down Expand Up @@ -487,7 +498,10 @@ impl Ctx {
}
if let Some(why) = prompt_blocker(self.yes, self.json, self.stdin_tty) {
return Err(confirmation_required(format!("{prompt} — and {why}"))
.fix("check the estimate, then run the same command with --yes")
.fix(confirm_fix(
prompt,
crate::fmt::ESTIMATE_SHOWN.load(std::sync::atomic::Ordering::Relaxed),
))
.into());
}
eprint!("{prompt} {} ", if default_yes { "[Y/n]" } else { "[y/N]" });
Expand Down Expand Up @@ -563,6 +577,24 @@ impl Ctx {
mod tests {
use super::*;

/// QW2-079: "check the estimate" only when the prompt quotes one.
#[test]
fn the_e802_fix_mentions_an_estimate_only_when_there_is_one() {
assert!(confirm_fix(
"Report build = queued? (create a check run, ~0.0013 DASH)",
false
)
.contains("estimate"));
// The price on a line before a plain question (`dg auth login`, `dg auth name register`).
assert!(confirm_fix("Register the key?", true).contains("estimate"));
let fix = confirm_fix(
"Accept membership of a/b? Its owner can then add you (one small document)",
false,
);
assert!(!fix.contains("estimate"), "{fix}");
assert!(fix.contains("--yes"), "{fix}");
}

fn config(network: &str) -> Config {
Config {
network: Some(network.into()),
Expand Down
28 changes: 27 additions & 1 deletion crates/dg/src/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,7 @@ fn check_git_config(ctx: &Ctx) -> Vec<Check> {
);
out.push(match policy {
Err(e) => Check::fail("dash.storage", e.to_string(), "`dg storage use <profiles>` rewrites it"),
Ok(p) if p.is_platform_only() => Check::ok("dash.storage", "unset: pushes store packs on Platform"),
Ok(p) if p.is_platform_only() => Check::ok("dash.storage", platform_only_detail(storage.as_deref())),
Ok(p) => match StorageProfiles::load().and_then(|profiles| p.resolve(&profiles)) {
Ok(r) => Check::ok(
"dash.storage",
Expand All @@ -1215,6 +1215,15 @@ fn check_git_config(ctx: &Ctx) -> Vec<Check> {
out
}

/// The `dash.storage` row's detail for a Platform-only policy: the value as set (`platform`),
/// or `unset` when there is none (QW2-081: a repo set to `platform` read "unset").
fn platform_only_detail(value: Option<&str>) -> String {
match value.map(str::trim).filter(|v| !v.is_empty()) {
Some(v) => format!("{v}: pushes store packs on Platform"),
None => "unset: pushes store packs on Platform".to_string(),
}
}

/// The `dash.network` row when git's network does not resolve: a `config.toml` that does
/// not parse (E204, reported on its own row) is a pointer to that row; anything else is a
/// bad `dash.*` value in git config.
Expand Down Expand Up @@ -1355,6 +1364,23 @@ fn in_git_repo() -> bool {
mod tests {
use super::*;

/// QW2-081: a repository set to `platform` says so; only a missing value is "unset".
#[test]
fn a_platform_storage_value_is_named_not_called_unset() {
assert_eq!(
platform_only_detail(Some("platform")),
"platform: pushes store packs on Platform"
);
assert_eq!(
platform_only_detail(None),
"unset: pushes store packs on Platform"
);
assert_eq!(
platform_only_detail(Some(" ")),
"unset: pushes store packs on Platform"
);
}

/// The guard `dg doctor --fix` sets lets a small push through without asking, packs on
/// Platform included (its quote is an upper bound), and still asks before a megabyte.
#[test]
Expand Down
Loading
Loading