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
3 changes: 2 additions & 1 deletion crates/dg/src/ci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ async fn runner_add(ctx: &Ctx, repo: &str, runner: &str) -> Result<()> {
.await?;
let spent = s.spent_since(before).await;
ctx.emit(
json!({ "status": "enrolled", "runner": runner, "documentId": m.document_id, "cost": cost_json(spent, dash_usd_price()) }),
json!({ "status": "enrolled", "runner": runner, "documentId": m.document_id, "id": m.document_id, "cost": cost_json(spent, dash_usd_price()) }),
|| println!("✓ {runner} is a runner of {} ({})", s.repo.display(), cost_line(spent, dash_usd_price())),
);
Ok(())
Expand Down Expand Up @@ -724,6 +724,7 @@ fn emit_report(
json!({
"status": done.action,
"documentId": done.document_id,
"id": done.document_id,
"name": r.name,
"checkStatus": r.status,
"conclusion": r.conclusion,
Expand Down
17 changes: 16 additions & 1 deletion crates/dg/src/collab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ async fn accept(ctx: &Ctx, repo: &str, withdraw: bool) -> Result<()> {
"repo": handle.display(),
"identityId": me,
"documentId": document_id,
"id": document_id,
}),
|| {
println!(
Expand Down Expand Up @@ -232,6 +233,7 @@ async fn add(ctx: &Ctx, repo: &str, member: &str, role: RoleArg, wait: Option<u6
"member": member,
"role": role_name(role),
"documentId": granted.document_id,
"id": granted.document_id,
"repo": handle.display(),
}),
|| {
Expand Down Expand Up @@ -518,16 +520,29 @@ async fn list(ctx: &Ctx, repo: &str) -> Result<()> {
"identityId": m.identity_id,
"role": role_name(m.role),
"documentId": m.document_id,
"id": m.document_id,
"since": m.created_at,
})
})
.collect();
// DPNS names for the human list only, read together; a failed read shows the bare id.
let names = if ctx.json {
std::collections::BTreeMap::default()
} else {
client
.dpns_first_names(members.iter().map(|m| m.identity_id.as_str()))
.await
};
ctx.emit(
json!({ "count": rows.len(), "members": rows, "ownerId": handle.owner_id() }),
|| {
println!("{} member(s) of {}:", members.len(), handle.display());
for m in &members {
println!(" {} {}", m.identity_id, role_name(m.role));
println!(
" {} {}",
crate::fmt::with_name(&m.identity_id, &names),
role_name(m.role)
);
}
},
);
Expand Down
92 changes: 74 additions & 18 deletions crates/dg/src/doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ struct Section {
/// Run every check, apply the safe fixes when `fix` is set, and report.
pub async fn run(ctx: &Ctx, fix: bool) -> Result<()> {
let identity = check_identity(ctx).await;
let mut network = check_network(ctx).await;
let contracts = contract_rows(
&mut network,
check_contracts(&ctx.target, unchosen_undeployed(ctx)),
);
let mut sections = vec![
Section {
title: "toolchain",
Expand All @@ -187,11 +192,11 @@ pub async fn run(ctx: &Ctx, fix: bool) -> Result<()> {
},
Section {
title: "network",
checks: check_network(ctx).await,
checks: network,
},
Section {
title: "contracts",
checks: vec![check_contracts(&ctx.target, unchosen_undeployed(ctx))],
checks: contracts,
},
Section {
title: "storage",
Expand Down Expand Up @@ -725,23 +730,34 @@ async fn check_network(ctx: &Ctx) -> Vec<Check> {
"run it again in a minute (a different node is asked)",
),
});
out.push(check_forge_v2(&client, &ctx.target).await);
out.extend(check_forge_v2(&client, &ctx.target).await);
out
}

/// The contracts section: one `forge-v2` row (QW-083 printed it under network and again
/// here). The network section's proof-verified row, when it ran, moves here: it says all the
/// recorded row does and whether the contracts are really there. Otherwise (a fresh install,
/// no deployment, a DAPI that could not be reached) the recorded row is all there is.
fn contract_rows(network: &mut Vec<Check>, recorded: Check) -> Vec<Check> {
match network.iter().position(|c| c.name == "forge-v2") {
Some(i) => vec![network.remove(i)],
None => vec![recorded],
}
}

/// Where the forge-v2 contract ids for `target` come from.
fn deployment_source(target: &NetworkTarget) -> String {
format!("forge-contracts/deployments/{}.json", target.network.key())
}

/// The DPNS system contract: its id is fixed by rs-dpp and identical on every network.
const DPNS_CONTRACT_ID: &str = "GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec";

/// The forge-v2 contracts recorded for this network: each must fetch with a verified proof
/// and be enrolled, as whole contracts, in the recorded contract group. A network
/// with no forge-v2 deployment is reported by the contracts row, so this one only notes it.
async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Check {
let Some(ids) = &target.v2 else {
return Check::ok(
"forge-v2",
format!("not deployed on {} (see contracts)", target.network.key()),
);
};
/// and be enrolled, as whole contracts, in the recorded contract group. `None` for a network
/// with no forge-v2 deployment: [`check_contracts`]' row reports that.
async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Option<Check> {
let ids = target.v2.as_ref()?;
let mut problems = Vec::new();
// forge-community is forge-collab on a deployment that predates the split: checked once
let mut contracts = ids.all().to_vec();
Expand All @@ -765,12 +781,16 @@ async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Chec
Err(e) => problems.push(format!("{label} {id} group lookup failed: {e}")),
}
}
if problems.is_empty() {
Some(if problems.is_empty() {
Check::ok(
"forge-v2",
format!(
"core={} collab={} community={} proof-verified and enrolled in group {}",
ids.core, ids.collab, ids.community, ids.group
"core={} collab={} community={} proof-verified and enrolled in group {} (source: {})",
ids.core,
ids.collab,
ids.community,
ids.group,
deployment_source(target)
),
)
} else {
Expand All @@ -779,7 +799,7 @@ async fn check_forge_v2(client: &PlatformClient, target: &NetworkTarget) -> Chec
problems.join("; "),
"the network may not run protocol 14 yet, or the deployment record is stale",
)
}
})
}

/// A fresh install: no flag, `config.toml` or environment chose a network, and the default
Expand Down Expand Up @@ -814,12 +834,12 @@ fn check_contracts(target: &NetworkTarget, fresh_install: bool) -> Check {
Ok(ids) => Check::ok(
"forge-v2",
format!(
"core={} collab={} community={} group={} (source: forge-contracts/deployments/{}.json)",
"core={} collab={} community={} group={} (source: {})",
ids.core,
ids.collab,
ids.community,
ids.group,
target.network.key()
deployment_source(target)
),
),
Err(e) => Check::fail(
Expand Down Expand Up @@ -1449,6 +1469,42 @@ mod tests {
assert!(rows.iter().all(|c| c.status == Status::Ok));
}

/// QW-083: the forge-v2 row was printed under network and again under contracts.
#[test]
fn the_forge_v2_row_is_printed_once() {
let recorded = || Check::ok("forge-v2", "core=a (source: deployments/x.json)");
let proved = Check::ok("forge-v2", "core=a proof-verified and enrolled in group g");
let mut network = vec![
Check::ok("dapi", "reachable"),
Check::ok("protocol", "14"),
proved,
];
let contracts = contract_rows(&mut network, recorded());
assert_eq!(contracts.len(), 1);
assert!(
contracts[0].detail.contains("proof-verified"),
"the live row is kept"
);
let sections = [
Section {
title: "network",
checks: network,
},
Section {
title: "contracts",
checks: contracts,
},
];
let out = render_sections(&sections);
assert_eq!(out.matches("forge-v2").count(), 1, "{out}");

// No live row (fresh install, no deployment, DAPI down): the recorded one stands.
let mut network = vec![Check::fail("dapi", "could not connect", "retry")];
let contracts = contract_rows(&mut network, recorded());
assert!(contracts[0].detail.contains("source:"));
assert_eq!(network.len(), 1);
}

#[test]
fn contracts_check_reports_the_deployment_file_as_the_source() {
let target = NetworkSettings {
Expand Down
18 changes: 18 additions & 0 deletions crates/dg/src/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ pub fn safe(text: &str) -> std::borrow::Cow<'_, str> {
}
}

/// An identity id for display, with its DPNS name after it when `names` has one
/// (`Fi8b… (alice.dash)`), as [`forge_core::platform::PlatformClient::dpns_first_names`]
/// reads them.
pub fn with_name(id: &str, names: &std::collections::BTreeMap<String, String>) -> String {
match names.get(id) {
Some(name) => format!("{id} ({})", safe(name)),
None => id.to_string(),
}
}

/// A commit id shortened for display (12 hex digits).
pub fn short(oid: &str) -> &str {
// By character: the value may be untrusted document text, not hex.
Expand Down Expand Up @@ -193,6 +203,14 @@ mod tests {
assert_eq!(cost_json(0, 30.0)["usd"].as_f64(), Some(0.0));
}

/// QW-083: an id with a DPNS name shows it; one without (or whose read failed) is bare.
#[test]
fn an_identity_shows_its_dpns_name_when_it_has_one() {
let names = [("A1".to_string(), "alice.dash\u{1b}[2J".to_string())].into();
assert_eq!(with_name("A1", &names), "A1 (alice.dash[2J)");
assert_eq!(with_name("B2", &names), "B2");
}

/// The timeline's words for each transition kind (the web's), and how a state change was
/// written.
#[test]
Expand Down
55 changes: 45 additions & 10 deletions crates/dg/src/issue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use forge_core::rules::{Event, EventKind, IssueState};
use crate::common::{number_arg, Reader, Session};
use crate::context::Ctx;
use crate::fmt::{
cost_json, cost_line, dash_usd_price, safe, transition_phrase, transition_route_text,
cost_json, cost_line, dash_usd_price, safe, transition_phrase, transition_route_text, with_name,
};
use crate::{IssueCommand, IssueListArgs};

Expand Down Expand Up @@ -332,6 +332,7 @@ async fn list(ctx: &Ctx, args: &IssueListArgs) -> Result<()> {
"title": title,
"author": author,
"open": st.open,
"state": state_word(st.open),
"labels": st.labels,
"assignees": st.assignees,
"pinned": pinned,
Expand All @@ -353,7 +354,7 @@ async fn list(ctx: &Ctx, args: &IssueListArgs) -> Result<()> {
println!("no issues");
}
for (n, title, _, st, pinned) in &rows {
let mark = if st.open { "open" } else { "closed" };
let mark = state_word(st.open);
let mark = if *pinned {
format!("{mark}, pinned")
} else {
Expand Down Expand Up @@ -409,6 +410,18 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> {
let state = view.state;
let i = view.issue;
let (id, title, body, author) = (i.document_id, i.title, i.body, i.author);
// DPNS names for the human view only, read together; a failed read shows the bare id.
let names = if ctx.json {
std::collections::BTreeMap::default()
} else {
let actors = comments.iter().map(|c| c.author.as_str());
let actors = actors.chain(events.iter().map(|e| e.actor.as_str()));
let actors = actors.chain(transitions.iter().map(|t| t.actor.as_str()));
s.client
.dpns_first_names(std::iter::once(author.as_str()).chain(actors))
.await
};
let who = |id: &str| with_name(id, &names);

ctx.emit(
json!({
Expand All @@ -417,6 +430,7 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> {
"body": body,
"author": author,
"documentId": id,
"id": id,
"state": { "open": state.open, "labels": state.labels, "assignees": state.assignees },
"milestone": meta.milestone,
"pinned": meta.pinned,
Expand All @@ -441,9 +455,9 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> {
"plaintextEventValues": plaintext_values,
}),
|| {
let mark = if state.open { "open" } else { "closed" };
let mark = state_word(state.open);
println!("#{number} [{mark}] {}", safe(&title));
println!("author: {author}");
println!("author: {}", who(&author));
if !state.labels.is_empty() {
println!("labels: {}", safe(&labels_of(&state)));
}
Expand All @@ -453,11 +467,12 @@ async fn view(ctx: &Ctx, repo: &str, number: u64) -> Result<()> {
for item in &timeline {
match item {
Item::Comment(c) => {
println!("\n— {} ({}):\n{}", c.author, c.document_id, safe(&c.body));
let author = who(&c.author);
println!("\n— {author} ({}):\n{}", c.document_id, safe(&c.body));
}
Item::Event(e) => println!("\n· {} {}", e.actor, safe(&event_phrase(e))),
Item::Event(e) => println!("\n· {} {}", who(&e.actor), safe(&event_phrase(e))),
Item::Transition(t) => {
println!("\n· {} {}", t.actor, transition_phrase(t.kind));
println!("\n· {} {}", who(&t.actor), transition_phrase(t.kind));
}
}
}
Expand Down Expand Up @@ -738,6 +753,16 @@ async fn refuse_if_locked(s: &Session, number: u64, target_id: &str) -> Result<(
.into())
}

/// The `"state"` of an issue in JSON, `"open"` or `"closed"`, as `dg pr`'s: emitted beside
/// the older `"open": bool`, which stays for the consumers that read it (QW-081).
fn state_word(open: bool) -> &'static str {
if open {
"open"
} else {
"closed"
}
}

/// `(past tense, prompt verb)` of a close or a reopen ("reopend" was L-35).
fn open_words(close: bool) -> (&'static str, &'static str) {
if close {
Expand All @@ -758,9 +783,9 @@ async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()>
// way `set_state` reads it.
let open = status_of_code(collab.state_sum(&s.repo, &target.id).await?).open;
if open != close {
let state = if open { "open" } else { "closed" };
let state = state_word(open);
ctx.emit(
json!({ "status": "unchanged", "issue": number, "open": open, "written": false }),
json!({ "status": "unchanged", "issue": number, "open": open, "state": state, "written": false }),
|| println!("issue #{number} is already {state}; nothing written"),
);
return Ok(());
Expand All @@ -784,6 +809,7 @@ async fn set_open(ctx: &Ctx, repo: &str, number: u64, close: bool) -> Result<()>
"transitionId": change.transition_id,
"kind": change.kind,
"open": open_now,
"state": open_now.map(state_word),
}),
|| {
println!(
Expand Down Expand Up @@ -991,7 +1017,16 @@ async fn assign(ctx: &Ctx, repo: &str, number: u64, who: &[String], add: bool) -

#[cfg(test)]
mod tests {
use super::{changes, event_phrase, label_args, open_words, timeline, title_matches, Item};
use super::{
changes, event_phrase, label_args, open_words, state_word, timeline, title_matches, Item,
};

/// QW-081: an issue's JSON `"state"` uses the words `dg pr`'s does.
#[test]
fn an_issue_state_is_the_word_a_pr_state_uses() {
assert_eq!(state_word(true), "open");
assert_eq!(state_word(false), "closed");
}

/// QW-035: a label (or assignee) already on the issue is not written again, one already
/// off is not removed again, and a name given twice is written once. An unreadable state
Expand Down
3 changes: 2 additions & 1 deletion crates/dg/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,8 @@ pub enum PrCommand {
#[arg(long)]
comments: bool,
},
/// Check out a pull request as branch `pr/<n>`, fetching its head from the source repo.
/// Check out a pull request as branch `pr/<n>`, fetching its head from the source repo,
/// and switch to it (left for `git switch` when there are uncommitted changes).
Checkout {
/// The repository (`owner/name`).
repo: String,
Expand Down
Loading
Loading