fix(cli): offer repository-wide git dependency approvals (#18378)
`pnpm approve` accepts a package name and Git repository URL as an explicit selector for future updates. It uses the same repository identity as the install policy to find pending commits, records the requested capabilities under the repository selector, and uses the resolved keys to rebuild packages and clear pending entries. The picker shows one row per Git package and repository. Leave it unchecked to deny the pending commits, press Space to approve only those commits, or press R to include future commits. Enter submits the choice once. `--all` stays commit-scoped. An exact positional selector can still approve a single revision. Verified all three choices in a terminal using two pending commits and a second repository. Checked the resulting policy keys after each choice. The focused permission, checkbox, and agent-skills suites passed all 66 tests. Closes pnpm/pnpm#18375.
This commit is contained in:
parent
78a8a1a282
commit
dcb26c99fa
11 changed files with 469 additions and 93 deletions
5
.changeset/approve-git-repository.md
Normal file
5
.changeset/approve-git-repository.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
"pnpm": patch
|
||||
---
|
||||
|
||||
`pnpm approve` now lets you approve a Git dependency across updates. Press R on the package in the interactive prompt or pass its package name and repository URL without a commit [#18375](https://github.com/pnpm/pnpm/issues/18375).
|
||||
|
|
@ -19,7 +19,11 @@ use owo_colors::{
|
|||
OwoColorize,
|
||||
Stream,
|
||||
};
|
||||
use std::io;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io,
|
||||
mem,
|
||||
};
|
||||
|
||||
/// One line of a [`CheckboxPrompt`].
|
||||
pub(crate) enum CheckboxItem<Value> {
|
||||
|
|
@ -69,7 +73,7 @@ pub(crate) enum CheckboxAnswer<Value> {
|
|||
pub(crate) struct CheckboxPrompt<Value> {
|
||||
message: String,
|
||||
items: Vec<CheckboxItem<Value>>,
|
||||
checked: Vec<bool>,
|
||||
selection: CheckboxSelection<Value>,
|
||||
required: bool,
|
||||
theme: CheckboxTheme,
|
||||
error: Option<&'static str>,
|
||||
|
|
@ -78,6 +82,11 @@ pub(crate) struct CheckboxPrompt<Value> {
|
|||
mode: wasm::Mode,
|
||||
}
|
||||
|
||||
struct CheckboxSelection<Value> {
|
||||
checked: Vec<bool>,
|
||||
alternatives: BTreeMap<usize, CheckboxChoice<Value>>,
|
||||
}
|
||||
|
||||
struct PromptViewport {
|
||||
active: usize,
|
||||
/// The first item on screen.
|
||||
|
|
@ -116,7 +125,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
Self {
|
||||
message: message.into(),
|
||||
items,
|
||||
checked,
|
||||
selection: CheckboxSelection { checked, alternatives: BTreeMap::new() },
|
||||
required: false,
|
||||
theme: CheckboxTheme::default(),
|
||||
error: None,
|
||||
|
|
@ -131,6 +140,15 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Pressing `r` swaps the highlighted choice with its alternative and selects it.
|
||||
pub(crate) fn with_alternatives(
|
||||
mut self,
|
||||
alternatives: BTreeMap<usize, CheckboxChoice<Value>>,
|
||||
) -> Self {
|
||||
self.selection.alternatives = alternatives;
|
||||
self
|
||||
}
|
||||
|
||||
/// Refuse to confirm an empty selection.
|
||||
pub(crate) fn required(mut self, required: bool) -> Self {
|
||||
self.required = required;
|
||||
|
|
@ -212,22 +230,25 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
}
|
||||
match key {
|
||||
Key::Enter => {
|
||||
if self.required && !self.checked.iter().any(|&checked| checked) {
|
||||
if self.required && !self.selection.checked.iter().any(|&checked| checked) {
|
||||
self.error = Some("At least one choice must be selected");
|
||||
return KeyOutcome::Redraw;
|
||||
}
|
||||
return KeyOutcome::Submit;
|
||||
}
|
||||
Key::Escape if !self.selection.alternatives.is_empty() => return KeyOutcome::Cancel,
|
||||
Key::CtrlC => return KeyOutcome::Cancel,
|
||||
Key::Char('r' | 'R') => self.toggle_alternative(),
|
||||
Key::ArrowUp | Key::Char('k') => self.move_active(-1),
|
||||
Key::ArrowDown | Key::Char('j') => self.move_active(1),
|
||||
Key::Char(' ') => {
|
||||
self.checked[self.viewport.active] = !self.checked[self.viewport.active];
|
||||
self.selection.checked[self.viewport.active] =
|
||||
!self.selection.checked[self.viewport.active];
|
||||
}
|
||||
Key::Char('a') => {
|
||||
let select_all = self.items
|
||||
.iter()
|
||||
.zip(&self.checked)
|
||||
.zip(&self.selection.checked)
|
||||
.any(|(item, &checked)| is_choice(item) && !checked);
|
||||
self.check_every_choice(|_| select_all);
|
||||
}
|
||||
|
|
@ -241,6 +262,16 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
KeyOutcome::Redraw
|
||||
}
|
||||
|
||||
fn toggle_alternative(&mut self) {
|
||||
let active = self.viewport.active;
|
||||
if let CheckboxItem::Choice(choice) = &mut self.items[active]
|
||||
&& let Some(alternative) = self.selection.alternatives.get_mut(&active)
|
||||
{
|
||||
mem::swap(choice, alternative);
|
||||
self.selection.checked[active] = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_numbered_choice(&mut self, digit: char) {
|
||||
let nth = usize::from(digit as u8 - b'1');
|
||||
if let Some(index) = self.items
|
||||
|
|
@ -251,7 +282,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
.map(|(index, _)| index)
|
||||
{
|
||||
self.viewport.active = index;
|
||||
self.checked[index] = !self.checked[index];
|
||||
self.selection.checked[index] = !self.selection.checked[index];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -270,7 +301,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
}
|
||||
|
||||
fn check_every_choice(&mut self, checked: impl Fn(bool) -> bool) {
|
||||
for (item, slot) in self.items.iter().zip(&mut self.checked) {
|
||||
for (item, slot) in self.items.iter().zip(&mut self.selection.checked) {
|
||||
if is_choice(item) {
|
||||
*slot = checked(*slot);
|
||||
}
|
||||
|
|
@ -366,7 +397,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
let active = index == self.viewport.active;
|
||||
let cursor = if active { "❯" } else { " " };
|
||||
let checkbox =
|
||||
if self.checked[index] { &self.theme.checked } else { &self.theme.unchecked };
|
||||
if self.selection.checked[index] { &self.theme.checked } else { &self.theme.unchecked };
|
||||
let line = format!("{cursor}{checkbox} {}", choice.name);
|
||||
if active { stdout_styled(&line, in_active_cyan) } else { line }
|
||||
}
|
||||
|
|
@ -387,7 +418,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
pub(crate) fn selected_choices(&self) -> impl Iterator<Item = &CheckboxChoice<Value>> {
|
||||
self.items
|
||||
.iter()
|
||||
.zip(&self.checked)
|
||||
.zip(&self.selection.checked)
|
||||
.filter_map(|(item, &checked)| match item {
|
||||
CheckboxItem::Choice(choice) if checked => Some(choice),
|
||||
_ => None,
|
||||
|
|
@ -395,7 +426,7 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
}
|
||||
|
||||
fn take_selected(&mut self) -> Vec<Value> {
|
||||
let checked = std::mem::take(&mut self.checked);
|
||||
let checked = std::mem::take(&mut self.selection.checked);
|
||||
std::mem::take(&mut self.items)
|
||||
.into_iter()
|
||||
.zip(checked)
|
||||
|
|
|
|||
|
|
@ -56,6 +56,23 @@ fn selected(prompt: &CheckboxPrompt<&'static str>) -> Vec<&'static str> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_shortcut_selects_only_the_highlighted_alternative() {
|
||||
let alternate = CheckboxChoice {
|
||||
value: "repo",
|
||||
name: "all commits".to_string(),
|
||||
short: "repo".to_string(),
|
||||
description: None,
|
||||
};
|
||||
let mut prompt = grouped_prompt().with_alternatives([(2, alternate)].into());
|
||||
press(&mut prompt, &[Key::Char('a')]);
|
||||
assert_eq!(selected(&prompt), vec!["foo", "bar", "baz"]);
|
||||
press(&mut prompt, &[Key::Char('a'), Key::Char('r')]);
|
||||
assert_eq!(selected(&prompt), vec!["repo"]);
|
||||
press(&mut prompt, &[Key::Char('R'), Key::Enter]);
|
||||
assert_eq!(selected(&prompt), vec!["foo"]);
|
||||
}
|
||||
|
||||
fn frame_lines(prompt: &CheckboxPrompt<&'static str>) -> Vec<String> {
|
||||
strip_ansi_codes(&prompt.render_frame())
|
||||
.lines()
|
||||
|
|
|
|||
|
|
@ -14,16 +14,16 @@ pub(super) enum Mode {
|
|||
|
||||
impl<Value> CheckboxPrompt<Value> {
|
||||
pub(crate) fn dialoguer_defaults(mut self, defaults: Vec<bool>) -> Self {
|
||||
assert_eq!(self.checked.len(), defaults.len());
|
||||
self.checked = defaults;
|
||||
assert_eq!(self.selection.checked.len(), defaults.len());
|
||||
self.selection.checked = defaults;
|
||||
self.mode = Mode::MultiSelect;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn single_selection(mut self, active: usize) -> Self {
|
||||
self.viewport.active = active;
|
||||
self.checked.fill(false);
|
||||
self.checked[active] = true;
|
||||
self.selection.checked.fill(false);
|
||||
self.selection.checked[active] = true;
|
||||
self.mode = Mode::Select;
|
||||
self.theme = CheckboxTheme { checked: String::new(), unchecked: String::new() };
|
||||
self
|
||||
|
|
@ -49,8 +49,8 @@ impl<Value> CheckboxPrompt<Value> {
|
|||
}
|
||||
if self.move_for_dialoguer_key(key) {
|
||||
if self.mode == Mode::Select {
|
||||
self.checked.fill(false);
|
||||
self.checked[self.viewport.active] = true;
|
||||
self.selection.checked.fill(false);
|
||||
self.selection.checked[self.viewport.active] = true;
|
||||
}
|
||||
self.scroll_into_view();
|
||||
return Some(KeyOutcome::Redraw);
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ pub(crate) mod render;
|
|||
pub(crate) use decisions::Approval;
|
||||
pub(crate) use render::render_permissions;
|
||||
|
||||
mod repository_scope;
|
||||
|
||||
use crate::{
|
||||
State,
|
||||
cli_args::{
|
||||
approve_builds::{
|
||||
ApprovalStore,
|
||||
ApproveBuildsArgs,
|
||||
confirm,
|
||||
disambiguated_labels,
|
||||
partition_params,
|
||||
prompt_for_choices,
|
||||
|
|
@ -84,7 +85,9 @@ pub struct ApproveArgs {
|
|||
/// Packages to approve (`<pkg>`) or deny (`!<pkg>`). A package is
|
||||
/// approved or denied for everything it requests. With no packages, the
|
||||
/// packages awaiting approval are chosen interactively, and for a
|
||||
/// package whose skills are approved, which of its skills.
|
||||
/// package whose skills are approved, which of its skills. To approve
|
||||
/// a Git package across updates, select its repository in the prompt or
|
||||
/// pass `<name>@<git-url>` without a commit.
|
||||
pub packages: Vec<String>,
|
||||
|
||||
/// Approve everything awaiting approval without interactive prompts.
|
||||
|
|
@ -150,7 +153,6 @@ pub(crate) fn pending_permissions(config: &Config) -> miette::Result<PendingPerm
|
|||
use decisions::{
|
||||
capability_list,
|
||||
clear_decided,
|
||||
confirmation,
|
||||
decisions_by_approval,
|
||||
decisions_for_all,
|
||||
named_decisions,
|
||||
|
|
@ -250,24 +252,15 @@ impl ApproveArgs {
|
|||
if !prompt.is_available() {
|
||||
return Err(ApproveNonInteractive.into());
|
||||
}
|
||||
let Some(selected) = prompt_for_packages(pending)? else {
|
||||
let Some(approved) = repository_scope::prompt_for_packages(pending)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let approved: BTreeSet<String> = pending
|
||||
.keys()
|
||||
.filter(|pkg| selected.contains(pkg))
|
||||
.cloned()
|
||||
.collect();
|
||||
let Some(review) = review_skills(config, manifest_dir, &approved, pending)? else {
|
||||
let pending = repository_scope::group_requests(pending.clone(), &approved);
|
||||
let Some(review) = review_skills(config, manifest_dir, &approved, &pending)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !approved.is_empty() && !confirm(&confirmation(&approved, pending))? {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(Approval {
|
||||
decisions: decisions_by_approval(&approved, pending, &review.skills_by_package),
|
||||
skills_dirs: review.dirs,
|
||||
}))
|
||||
let decisions = decisions_by_approval(&approved, &pending, &review.skills_by_package);
|
||||
Ok(Some(Approval { decisions, skills_dirs: review.dirs }))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -281,12 +274,6 @@ pub(crate) fn package_choices(pending: &BTreeMap<String, Capabilities>) -> Vec<(
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn prompt_for_packages(
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> miette::Result<Option<Vec<String>>> {
|
||||
prompt_for_choices("Choose which packages to approve", &package_choices(pending))
|
||||
}
|
||||
|
||||
/// The interactive skills review of an approval: the first-run
|
||||
/// `skills.dirs` prompt, and one skill checkbox per approved package.
|
||||
#[derive(Default)]
|
||||
|
|
@ -322,8 +309,9 @@ fn review_skills(
|
|||
.wrap_err("find the skills of the packages awaiting approval")?;
|
||||
|
||||
let labels = disambiguated_labels(pending.keys().map(String::as_str));
|
||||
let skills_by_key = repository_scope::group_requests(options.skills_by_key, approved);
|
||||
let Some(skills_by_package) =
|
||||
collect_package_skill_decisions(&skills_pending, &labels, &options.skills_by_key)?
|
||||
collect_package_skill_decisions(&skills_pending, &labels, &skills_by_key)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
|
@ -339,14 +327,16 @@ fn review_skills(
|
|||
fn collect_package_skill_decisions(
|
||||
skills_pending: &[&String],
|
||||
labels: &BTreeMap<&str, String>,
|
||||
skills_by_key: &BTreeMap<String, Vec<String>>,
|
||||
skills_by_key: &BTreeMap<String, BTreeSet<String>>,
|
||||
) -> miette::Result<Option<BTreeMap<String, SkillsPermission>>> {
|
||||
let mut skills_by_package = BTreeMap::new();
|
||||
for &pkg in skills_pending {
|
||||
let skills = skills_by_key
|
||||
.get(pkg.as_str())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
.collect::<Vec<_>>();
|
||||
match prompt_for_package_skills(&labels[pkg.as_str()], &skills)? {
|
||||
SkillPromptOutcome::Cancelled => return Ok(None),
|
||||
SkillPromptOutcome::Undiscovered => {}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ use super::{
|
|||
Capabilities,
|
||||
IgnoredBuildsScan,
|
||||
PermissionCapability,
|
||||
disambiguated_labels,
|
||||
emit_global_warning,
|
||||
partition_params,
|
||||
};
|
||||
|
|
@ -18,6 +17,7 @@ use pnpm_package_manager::{
|
|||
allow_build_key_from_ignored_build,
|
||||
skill_approval_key,
|
||||
};
|
||||
use pnpm_package_name::git_repo_allow_build_key_from_dep_path;
|
||||
use pnpm_reporter::Reporter;
|
||||
use pnpm_workspace_manifest_writer::{
|
||||
PermissionValue,
|
||||
|
|
@ -74,34 +74,29 @@ pub(super) fn pending_builds_approved(
|
|||
decisions: &Decisions,
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> Vec<String> {
|
||||
decisions
|
||||
pending
|
||||
.iter()
|
||||
.filter_map(|(pkg, decided)| {
|
||||
decided.build
|
||||
.filter(|&allowed| {
|
||||
allowed
|
||||
&& pending
|
||||
.get(pkg)
|
||||
.is_some_and(|requested| {
|
||||
requested.contains(&PermissionCapability::Build)
|
||||
})
|
||||
})
|
||||
.map(|_| pkg.clone())
|
||||
.filter(|(_, requested)| requested.contains(&PermissionCapability::Build))
|
||||
.filter(|(pkg, _)| {
|
||||
matching_decisions(decisions, pkg)
|
||||
.filter_map(|decision| decision.build)
|
||||
.min()
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|(pkg, _)| pkg.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn confirmation(
|
||||
approved: &BTreeSet<String>,
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> String {
|
||||
let labels = disambiguated_labels(pending.keys().map(String::as_str));
|
||||
let packages = approved
|
||||
.iter()
|
||||
.map(|pkg| format!("{} ({})", labels[pkg.as_str()], capability_list(&pending[pkg])))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("Approve {packages}?")
|
||||
fn matching_decisions<'a>(
|
||||
decisions: &'a Decisions,
|
||||
key: &str,
|
||||
) -> impl Iterator<Item = &'a PackageDecisions> {
|
||||
let repository =
|
||||
git_repo_allow_build_key_from_dep_path(key).and_then(|repo| decisions.get(repo.as_ref()));
|
||||
decisions
|
||||
.get(key)
|
||||
.into_iter()
|
||||
.chain(repository)
|
||||
}
|
||||
|
||||
/// The decisions of `<pkg>` / `!<pkg>` arguments. A package that is not
|
||||
|
|
@ -110,7 +105,8 @@ pub(super) fn named_decisions<Reporter: self::Reporter>(
|
|||
params: &[String],
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> miette::Result<Decisions> {
|
||||
let pending_names: Vec<String> = pending.keys().cloned().collect();
|
||||
let requests = requests_by_selector(pending);
|
||||
let pending_names: Vec<String> = requests.keys().cloned().collect();
|
||||
let partition = partition_params(params, &pending_names);
|
||||
if !partition.unknown.is_empty() {
|
||||
emit_global_warning::<Reporter>(&format!(
|
||||
|
|
@ -123,7 +119,7 @@ pub(super) fn named_decisions<Reporter: self::Reporter>(
|
|||
names
|
||||
.iter()
|
||||
.map(|pkg| {
|
||||
let capabilities: Capabilities = pending
|
||||
let capabilities: Capabilities = requests
|
||||
.get(pkg)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| ALL_CAPABILITIES.into_iter().collect());
|
||||
|
|
@ -143,6 +139,21 @@ pub(super) fn named_decisions<Reporter: self::Reporter>(
|
|||
.collect())
|
||||
}
|
||||
|
||||
fn requests_by_selector(
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> BTreeMap<String, Capabilities> {
|
||||
let mut requests = pending.clone();
|
||||
for (key, capabilities) in pending {
|
||||
if let Some(repo) = git_repo_allow_build_key_from_dep_path(key) {
|
||||
requests
|
||||
.entry(repo.into_owned())
|
||||
.or_default()
|
||||
.extend(capabilities);
|
||||
}
|
||||
}
|
||||
requests
|
||||
}
|
||||
|
||||
/// The decisions for `--all`: every capability of every pending package is
|
||||
/// approved.
|
||||
pub(super) fn decisions_for_all(pending: &BTreeMap<String, Capabilities>) -> Decisions {
|
||||
|
|
@ -196,13 +207,13 @@ pub(super) fn decisions_by_approval(
|
|||
|
||||
fn is_decided(decisions: &Decisions, dep_path: &str, capability: PermissionCapability) -> bool {
|
||||
match capability {
|
||||
PermissionCapability::Build => decisions
|
||||
.get(&allow_build_key_from_ignored_build(dep_path))
|
||||
.is_some_and(|decided| decided.build.is_some()),
|
||||
PermissionCapability::Build => {
|
||||
matching_decisions(decisions, &allow_build_key_from_ignored_build(dep_path))
|
||||
.any(|decided| decided.build.is_some())
|
||||
}
|
||||
PermissionCapability::Skills => {
|
||||
decisions
|
||||
.get(&skill_approval_key(dep_path))
|
||||
.is_some_and(|decided| decided.skills.is_some())
|
||||
matching_decisions(decisions, &skill_approval_key(dep_path))
|
||||
.any(|decided| decided.skills.is_some())
|
||||
|| decisions
|
||||
.get(&allow_build_key_from_ignored_build(dep_path))
|
||||
.is_some_and(|decided| decided.skills.is_some())
|
||||
|
|
|
|||
119
pnpm/crates/cli/src/cli_args/permissions/repository_scope.rs
Normal file
119
pnpm/crates/cli/src/cli_args/permissions/repository_scope.rs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
use super::{
|
||||
Capabilities,
|
||||
capability_list,
|
||||
disambiguated_labels,
|
||||
package_choices,
|
||||
prompt_for_choices,
|
||||
};
|
||||
use crate::checkbox_prompt::{
|
||||
CheckboxAnswer,
|
||||
CheckboxChoice,
|
||||
CheckboxItem,
|
||||
CheckboxPrompt,
|
||||
};
|
||||
use miette::IntoDiagnostic;
|
||||
use pnpm_package_name::git_repo_allow_build_key_from_dep_path;
|
||||
use std::collections::{
|
||||
BTreeMap,
|
||||
BTreeSet,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
struct PackageGroup {
|
||||
keys: Vec<String>,
|
||||
requests: Capabilities,
|
||||
git: bool,
|
||||
}
|
||||
|
||||
pub(super) fn prompt_for_packages(
|
||||
pending: &BTreeMap<String, Capabilities>,
|
||||
) -> miette::Result<Option<BTreeSet<String>>> {
|
||||
let message = "Choose which packages to approve";
|
||||
let groups = package_groups(pending);
|
||||
if !groups.values().any(|group| group.git) {
|
||||
return Ok(prompt_for_choices(message, &package_choices(pending))?.map(BTreeSet::from_iter));
|
||||
}
|
||||
let prompt = grouped_prompt(message, &groups);
|
||||
Ok(match prompt.interact().into_diagnostic()? {
|
||||
CheckboxAnswer::Selected(selected) => Some(selected.into_iter().flatten().collect()),
|
||||
CheckboxAnswer::Cancelled => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn package_groups(pending: &BTreeMap<String, Capabilities>) -> BTreeMap<String, PackageGroup> {
|
||||
let mut groups = BTreeMap::<String, PackageGroup>::new();
|
||||
for (key, requests) in pending {
|
||||
let repo = git_repo_allow_build_key_from_dep_path(key);
|
||||
let git = repo.is_some();
|
||||
let identity = repo.map(std::borrow::Cow::into_owned).unwrap_or_else(|| key.clone());
|
||||
let group = groups
|
||||
.entry(identity)
|
||||
.or_insert_with(|| PackageGroup { git, ..Default::default() });
|
||||
group.keys.push(key.clone());
|
||||
group.requests.extend(requests);
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
fn grouped_prompt(
|
||||
message: &str,
|
||||
groups: &BTreeMap<String, PackageGroup>,
|
||||
) -> CheckboxPrompt<Vec<String>> {
|
||||
let labels = disambiguated_labels(groups.keys().map(String::as_str));
|
||||
let mut items = Vec::new();
|
||||
let mut alternatives = BTreeMap::new();
|
||||
for (key, group) in groups {
|
||||
let display_key = pnpm_network::redact_and_sanitize(key.split('?').next().unwrap_or(key));
|
||||
let display_label = labels[key.as_str()].replace(key, &display_key);
|
||||
let label = format!("{display_label} {}", capability_list(&group.requests));
|
||||
let mut choice = CheckboxChoice {
|
||||
short: label.clone(),
|
||||
name: label.clone(),
|
||||
description: None,
|
||||
value: group.keys.clone(),
|
||||
};
|
||||
if group.git {
|
||||
let count = group.keys.len();
|
||||
let scope = if count == 1 {
|
||||
"this commit".to_string()
|
||||
} else {
|
||||
format!("{count} pending commits")
|
||||
};
|
||||
choice.name = format!("{label} [{scope}]");
|
||||
choice.description = Some("r: include future commits".to_string());
|
||||
alternatives.insert(
|
||||
items.len(),
|
||||
CheckboxChoice {
|
||||
name: format!("{label} [all commits of {display_key}]"),
|
||||
short: format!("{label} (all commits)"),
|
||||
description: Some("r: pending commits only".to_string()),
|
||||
value: vec![key.clone()],
|
||||
},
|
||||
);
|
||||
}
|
||||
items.push(CheckboxItem::Choice(choice));
|
||||
}
|
||||
CheckboxPrompt::new(message, items).with_alternatives(alternatives)
|
||||
}
|
||||
|
||||
/// Combine the requests covered by each selected repository. Every other key
|
||||
/// keeps its commit-specific requests.
|
||||
pub(super) fn group_requests<Request: Ord>(
|
||||
requests: BTreeMap<String, impl IntoIterator<Item = Request>>,
|
||||
selected: &BTreeSet<String>,
|
||||
) -> BTreeMap<String, BTreeSet<Request>> {
|
||||
let mut grouped = BTreeMap::<String, BTreeSet<Request>>::new();
|
||||
for (key, values) in requests {
|
||||
let repo = git_repo_allow_build_key_from_dep_path(&key)
|
||||
.filter(|repo| selected.contains(repo.as_ref()))
|
||||
.map(std::borrow::Cow::into_owned);
|
||||
grouped
|
||||
.entry(repo.unwrap_or(key))
|
||||
.or_default()
|
||||
.extend(values);
|
||||
}
|
||||
grouped
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
use super::{
|
||||
grouped_prompt,
|
||||
package_groups,
|
||||
};
|
||||
use console::Key;
|
||||
use pnpm_config::PermissionCapability::{
|
||||
Build,
|
||||
Skills,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn one_git_row_selects_none_pending_commits_or_the_repository() {
|
||||
let repo = "alpha@git+https://example.org/alpha.git";
|
||||
let first = format!("{repo}#1111111");
|
||||
let second = format!("{repo}#2222222");
|
||||
let pending = BTreeMap::from([
|
||||
(first.clone(), [Build].into()),
|
||||
(second.clone(), [Skills].into()),
|
||||
("beta@git+https://example.org/beta.git#3333333".to_string(), [Skills].into()),
|
||||
]);
|
||||
let mut prompt = grouped_prompt("Approve", &package_groups(&pending));
|
||||
let frame = prompt.render_frame();
|
||||
assert_eq!(frame.matches("alpha (git)").count(), 1);
|
||||
assert!(frame.contains("2 pending commits"));
|
||||
assert_eq!(prompt.selected_choices().count(), 0);
|
||||
prompt.handle_key(&Key::Char(' '));
|
||||
let selected = |choice: &crate::checkbox_prompt::CheckboxChoice<Vec<String>>| {
|
||||
choice.value.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
prompt
|
||||
.selected_choices()
|
||||
.map(selected)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![vec![first.clone(), second.clone()]],
|
||||
);
|
||||
prompt.handle_key(&Key::Char('r'));
|
||||
assert_eq!(
|
||||
prompt
|
||||
.selected_choices()
|
||||
.map(selected)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![vec![repo.to_string()]],
|
||||
);
|
||||
prompt.handle_key(&Key::Char('r'));
|
||||
assert_eq!(
|
||||
prompt
|
||||
.selected_choices()
|
||||
.map(selected)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![vec![first, second]],
|
||||
);
|
||||
prompt.handle_key(&Key::Char(' '));
|
||||
assert_eq!(prompt.selected_choices().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_labels_redact_credentials_and_keep_the_policy_key() {
|
||||
let key =
|
||||
"demo@git+https://example-user:example-password@example.org/demo.git?token=example-query";
|
||||
let pending = BTreeMap::from([
|
||||
(format!("{key}#1234567"), [Build].into()),
|
||||
("demo@git+https://example.org/other.git#7654321".to_string(), [Build].into()),
|
||||
]);
|
||||
let mut prompt = grouped_prompt("Approve", &package_groups(&pending));
|
||||
for frame in [
|
||||
prompt.render_frame(),
|
||||
{
|
||||
prompt.handle_key(&Key::Char('r'));
|
||||
prompt.render_frame()
|
||||
},
|
||||
prompt.render_answer(),
|
||||
] {
|
||||
assert!(!frame.contains("example-password"));
|
||||
assert!(!frame.contains("example-query"));
|
||||
}
|
||||
assert_eq!(
|
||||
prompt
|
||||
.selected_choices()
|
||||
.next()
|
||||
.unwrap()
|
||||
.value,
|
||||
vec![key.to_string()],
|
||||
);
|
||||
}
|
||||
|
|
@ -2,10 +2,7 @@ use super::{
|
|||
ApproveArgs,
|
||||
Capabilities,
|
||||
PromptAvailability,
|
||||
decisions::{
|
||||
PackageDecisions,
|
||||
confirmation,
|
||||
},
|
||||
decisions::PackageDecisions,
|
||||
render_permissions,
|
||||
};
|
||||
use pnpm_config::{
|
||||
|
|
@ -106,6 +103,80 @@ fn all_approves_every_pending_capability() {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_git_repository_selector_decides_pending_commits() {
|
||||
let repo = "example@git+https://example.org/project.git";
|
||||
let first = format!("{repo}#1111111");
|
||||
let second = format!("{repo}#2222222");
|
||||
let other = "example@git+https://example.org/other.git#1111111";
|
||||
let pending = pending(&[(&first, &[Build]), (&second, &[Build]), (other, &[Build, Skills])]);
|
||||
let approval = args(&[repo], false)
|
||||
.decide::<SilentReporter>(&pending, decide_config(), Path::new("/workspace"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(approval.decisions, BTreeMap::from([(repo.to_string(), decided(Some(true), None))]));
|
||||
assert_eq!(
|
||||
super::decisions::pending_builds_approved(&approval.decisions, &pending),
|
||||
vec![first, second],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_git_repository_decision_clears_only_its_pending_skills() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let other = "example@git+https://example.org/other.git#1111111";
|
||||
let repo = "example@git+https://example.org/project.git";
|
||||
let config = config_awaiting(&dir, &[&format!("{repo}#1111111"), other]);
|
||||
let pending = super::pending_permissions(&config).unwrap();
|
||||
let approval = args(&[repo], false)
|
||||
.decide::<SilentReporter>(&pending.by_package, decide_config(), dir.path())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
approval.decisions,
|
||||
BTreeMap::from([(repo.to_string(), decided(None, Some(SkillsPermission::All(true))))]),
|
||||
);
|
||||
super::decisions::clear_decided(pending.scan, &approval.decisions).unwrap();
|
||||
assert_eq!(
|
||||
super::pending_permissions(&config).unwrap().by_package,
|
||||
self::pending(&[(other, &[Skills])]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_scope_combines_all_pending_commits_before_review() {
|
||||
let repo = "demo@git+https://example.org/demo.git";
|
||||
let first = format!("{repo}#abcdef1");
|
||||
let second = format!("{repo}#abcdef2");
|
||||
let other = "demo@git+https://example.org/other.git#abcdef1";
|
||||
let requests = pending(&[(&first, &[Build]), (&second, &[Skills]), (other, &[Skills])]);
|
||||
let selected = [repo.to_string()].into();
|
||||
let grouped = super::repository_scope::group_requests(requests, &selected);
|
||||
assert_eq!(grouped, pending(&[(repo, &[Build, Skills]), (other, &[Skills])]));
|
||||
let skills = BTreeMap::from([(first, vec!["one"]), (second, vec!["two", "one"])]);
|
||||
assert_eq!(
|
||||
super::repository_scope::group_requests(skills, &selected),
|
||||
BTreeMap::from([(repo.to_string(), ["one", "two"].into())]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approving_all_git_packages_keeps_the_resolved_commit() {
|
||||
let commit = "example@git+https://example.org/project.git#1111111";
|
||||
let approval = args(&[], true)
|
||||
.decide::<SilentReporter>(
|
||||
&pending(&[(commit, &[Skills])]),
|
||||
decide_config(),
|
||||
Path::new("/workspace"),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
approval.decisions,
|
||||
BTreeMap::from([(commit.to_string(), decided(None, Some(SkillsPermission::All(true))))]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_contradictory_arguments() {
|
||||
let error = args(&["foo", "!foo"], false)
|
||||
|
|
@ -186,17 +257,6 @@ fn lists_chosen_skills_next_to_the_package() {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_confirmation_names_packages_without_their_dep_path() {
|
||||
let pending =
|
||||
pending(&[("@pnpm/marked-skills", &[Skills]), ("@pnpm/git-skills", &[Build, Skills])]);
|
||||
|
||||
assert_eq!(
|
||||
confirmation(&pending.keys().cloned().collect(), &pending),
|
||||
"Approve @pnpm/git-skills (build, skills), @pnpm/marked-skills (skills)?",
|
||||
);
|
||||
}
|
||||
|
||||
/// A config whose `.modules.yaml` awaits the approval of `pending_skills`.
|
||||
fn config_awaiting(dir: &TempDir, pending_skills: &[&str]) -> Config {
|
||||
let modules_dir = dir.path().join("node_modules");
|
||||
|
|
|
|||
|
|
@ -6,9 +6,12 @@ mod local_deps;
|
|||
|
||||
use assert_cmd::prelude::*;
|
||||
use command_extra::CommandExtra;
|
||||
use pnpm_testing_utils::bin::{
|
||||
AddMockedRegistry,
|
||||
CommandTempCwd,
|
||||
use pnpm_testing_utils::{
|
||||
bin::{
|
||||
AddMockedRegistry,
|
||||
CommandTempCwd,
|
||||
},
|
||||
git_repo::GitRepoFixture,
|
||||
};
|
||||
use std::{
|
||||
fs,
|
||||
|
|
@ -486,3 +489,47 @@ fn approve_builds_reports_skills_still_awaiting_approval_in_append_only_output()
|
|||
assert_eq!(output.matches("Packages awaiting approval:").count(), 1, "{output}");
|
||||
drop(harness);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_approval_links_a_pending_git_skill_across_updates() {
|
||||
let harness = CommandTempCwd::init();
|
||||
let workspace = &harness.workspace;
|
||||
let repo = GitRepoFixture::init(harness.root.path(), "sample");
|
||||
repo.write_file("package.json", r#"{"name":"sample","version":"1.0.0"}"#);
|
||||
let skill = "skills/sample-guide/SKILL.md";
|
||||
repo.write_file(skill, "---\nname: sample-guide\n---\nFirst revision");
|
||||
let _ = repo.commit("first revision");
|
||||
fs::write(
|
||||
workspace.join("package.json"),
|
||||
serde_json::json!({
|
||||
"dependencies": { "sample": repo.git_url_at("main") },
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
let settings = workspace.join("pnpm-workspace.yaml");
|
||||
fs::write(&settings, "skills:\n dirs:\n - .agents/skills\n").unwrap();
|
||||
pnpm(workspace)
|
||||
.with_arg("install")
|
||||
.assert()
|
||||
.success();
|
||||
assert!(pending_skills(workspace).is_some());
|
||||
let selector = format!("sample@git+{}", repo.file_url());
|
||||
let output = output_of(pnpm(workspace).with_args(["approve", &selector]));
|
||||
assert!(!output.contains("not awaiting approval"), "{output}");
|
||||
let yaml: serde_json::Value =
|
||||
serde_saphyr::from_str(&fs::read_to_string(settings).unwrap()).unwrap();
|
||||
assert_eq!(yaml["permissions"][&selector]["skills"], true);
|
||||
assert!(pending_skills(workspace).is_none());
|
||||
let updated = "---\nname: sample-guide\n---\nUpdated revision";
|
||||
repo.write_file(skill, updated);
|
||||
let _ = repo.commit("update skill");
|
||||
pnpm(workspace)
|
||||
.with_args(["update", "sample"])
|
||||
.assert()
|
||||
.success();
|
||||
assert!(pending_skills(workspace).is_none());
|
||||
let linked =
|
||||
fs::read_to_string(workspace.join(".agents/skills/sample-guide/SKILL.md")).unwrap();
|
||||
assert!(linked.lines().eq(updated.lines()));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,6 +32,16 @@ pnpm approve drizzle-kit !esbuild
|
|||
|
||||
A named package is approved or denied for everything it requests, including every skill it ships. A package that is not awaiting approval yet is decided for every capability.
|
||||
|
||||
Each Git package appears once per repository. Press **Space** to approve its pending commits, or **R** to include future commits. Press **Enter** to save. To approve a single revision, pass its full commit selector to `pnpm approve`. `--all` approves only pending commits.
|
||||
|
||||
To approve a Git package across updates without a prompt, pass its package name and exact `git+` repository URL without a commit or branch suffix. For a `github:` dependency, the URL ends in `.git`. See the [repository matching rules](../settings/build.md#allowbuilds).
|
||||
|
||||
```sh
|
||||
pnpm approve 'example@git+https://github.com/example/project.git'
|
||||
```
|
||||
|
||||
This approves the requested capabilities for any commit from that repository.
|
||||
|
||||
After the decision is written, pnpm rebuilds the packages approved to build and links the approved agent skills.
|
||||
|
||||
A `build` decision is written to `permissions` only when `pnpm-workspace.yaml` already has a `permissions` setting. Otherwise it is written to [`allowBuilds`](../settings/build.md#allowbuilds), which older pnpm versions read too.
|
||||
|
|
|
|||
Loading…
Reference in a new issue