Skip to content

Fix critical bug in CLI update command and stabilize it#3007

Closed
ChanTsune wants to merge 2 commits into
mainfrom
fix-cli-update-bug-and-stabilize-14259518636105600921
Closed

Fix critical bug in CLI update command and stabilize it#3007
ChanTsune wants to merge 2 commits into
mainfrom
fix-cli-update-bug-and-stabilize-14259518636105600921

Conversation

@ChanTsune
Copy link
Copy Markdown
Owner

@ChanTsune ChanTsune commented Apr 30, 2026

This PR fixes a critical bug in the PNA CLI where the update command was not accessible from the top-level interface and, when invoked via experimental update, failed to correctly match filesystem paths against archive entries when path transformations (like --strip-components) were used. This led to duplicate entries instead of updates.

Changes:

  • Added Update to the main Commands enum.
  • Modified run_update_archive to use pathname_editor for path normalization during entry matching.
  • Stabilized the update command and added a deprecation warning to experimental update.
  • Updated all integration tests to use the new top-level update command.
  • Cleaned up development artifacts and improved test code formatting.

PR created automatically by Jules for task 14259518636105600921 started by @ChanTsune

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Enhanced archive entry processing during updates to properly handle name conversions; entries that cannot be successfully converted are now correctly excluded from update and add operations.
  • Documentation

    • Updated command documentation and usage examples to reflect the current CLI structure and interface standards.

- Register `update` subcommand as a top-level command.
- Fix path matching in `update` to respect path transformations like `--strip-components`.
- Deprecate `experimental update` with a warning.
- Update integration tests to use the stabilized `update` command.
- Clean up test code formatting.

Co-authored-by: ChanTsune <41658782+ChanTsune@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cbe3f3a9-e6f2-4f0b-9830-400935310179

📥 Commits

Reviewing files that changed from the base of the PR and between bc923a8 and f7f0b48.

📒 Files selected for processing (2)
  • cli/tests/cli/update/no_timestamp_archive.rs
  • cli/tests/cli/update/option_archive_missing_mtime.rs
✅ Files skipped from review due to trivial changes (2)
  • cli/tests/cli/update/no_timestamp_archive.rs
  • cli/tests/cli/update/option_archive_missing_mtime.rs

📝 Walkthrough

Walkthrough

The run_update_archive function now derives entry lookup keys from pathname editor transformations instead of unconditionally converting filesystem paths. Entries failing name editing are omitted from the target files mapping, affecting which archive entries are matched during updates and additions. Test documentation reflects CLI command syntax updates from experimental to standard forms.

Changes

Cohort / File(s) Summary
Entry Name Derivation
cli/src/command/update.rs
Modified run_update_archive to use pathname_editor.edit_entry_name for generating lookup keys instead of EntryName::from_lossy. Entries producing None are now skipped from target_files_mapping, affecting entry matching and addition logic.
Test Documentation
cli/tests/cli/update/no_timestamp_archive.rs, cli/tests/cli/update/option_archive_missing_mtime.rs
Updated test documentation strings to reflect current CLI syntax, replacing pna experimental update references with pna update and correcting example command flags.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Codex/bsdtar gap b partial #2710: Directly implements entry-skipping behavior when pathname_editor.edit_entry_name returns None, including tests and logging for skipped entries.
  • ✨ Serial creation #2635: Modifies target_files_mapping structure and entry-matching logic within the same run_update_archive function.
  • @ support #2523: Alters entry processing types and signatures within the run_update_archive control flow.

Poem

🐰 Through pathways edited with care,
Names transform in the air,
Entries filtered with grace,
Each one finds its place,
The archive now pristine and fair! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main objectives: fixing a bug in path normalization during entry matching and stabilizing the update command from experimental to top-level.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-cli-update-bug-and-stabilize-14259518636105600921

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request stabilizes the update command, moving it from the experimental subcommand to a top-level command with a visible alias "u". The experimental update command now issues a deprecation warning. Functional changes include integrating the pathname_editor into the update process to allow entry name transformations. Feedback focuses on maintaining consistency in the experimental command descriptions, addressing an unused archive_missing_ctime flag, and optimizing the performance of the update operation by reconsidering the use of IndexMap and shift_remove to avoid $O(N \times M)$ complexity.

Comment thread cli/src/command/experimental.rs Outdated
cmd.execute(ctx)
}
ExperimentalCommands::Update(cmd) => cmd.execute(ctx),
ExperimentalCommands::Update(cmd) => {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While stabilizing the update command, the about text for the Update variant in the ExperimentalCommands enum (line 80) should be updated to reflect its stabilized status and future removal, maintaining consistency with the Delete and Sort variants.

Comment thread cli/src/command/update.rs
use clap::{ArgGroup, Parser, ValueHint};
use indexmap::IndexMap;
use pna::{Archive, EntryName, Metadata, prelude::*};
use pna::{Archive, Metadata, prelude::*};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While updating the imports and stabilizing the update command, note that the archive_missing_ctime field (defined at line 280) is currently unused in the update_archive and run_update_archive functions. Since the staleness check in is_newer_than_archive only utilizes modification time (mtime), this flag should either be integrated into the logic or removed to avoid providing a non-functional CLI option.

Comment thread cli/src/command/update.rs
.edit_entry_name(&item.path)
.map(|name| (name, (idx, item)))
})
.collect::<IndexMap<_, _>>();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of IndexMap here, combined with shift_remove at line 600, results in $O(M)$ complexity for each archive entry lookup (where $M$ is the number of target files), leading to $O(N \times M)$ total complexity for the update operation. Since ReorderByIndex (line 647) ensures the final archive entries are correctly ordered, the insertion order within this map is not critical for the output. Consider using a HashMap for $O(1)$ lookups or using swap_remove at line 600 to significantly improve performance for large updates.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cli/src/command/update.rs`:
- Around line 583-592: The current collection into target_files_mapping uses
collect::<IndexMap<_, _>>() which will silently overwrite earlier entries when
create_options.pathname_editor.edit_entry_name(&item.path) returns the same name
for multiple target_items; change the logic that builds target_files_mapping
(the block using target_items.into_iter().enumerate().filter_map(...) and
collected into target_files_mapping) to explicitly detect duplicates: iterate
and attempt to insert each (name, (idx, item)) into the map, check
target_files_mapping.contains_key(&name) (or use entry API) and on collision
return an Err or accumulate a clear diagnostic mentioning the duplicate
transformed name and the conflicting source paths (using edit_entry_name and the
original item.path) so callers can fail fast instead of silently overwriting.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 32e129de-5bb2-4b93-8d26-2370188fbf74

📥 Commits

Reviewing files that changed from the base of the PR and between 50855d7 and bc923a8.

📒 Files selected for processing (25)
  • cli/src/cli.rs
  • cli/src/command.rs
  • cli/src/command/experimental.rs
  • cli/src/command/update.rs
  • cli/tests/cli/update/encryption.rs
  • cli/tests/cli/update/entry_order.rs
  • cli/tests/cli/update/error.rs
  • cli/tests/cli/update/no_timestamp_archive.rs
  • cli/tests/cli/update/option_archive_missing_mtime.rs
  • cli/tests/cli/update/option_atime.rs
  • cli/tests/cli/update/option_ctime.rs
  • cli/tests/cli/update/option_exclude.rs
  • cli/tests/cli/update/option_exclude_vcs.rs
  • cli/tests/cli/update/option_files_from_stdin.rs
  • cli/tests/cli/update/option_mtime.rs
  • cli/tests/cli/update/option_newer_ctime.rs
  • cli/tests/cli/update/option_newer_ctime_than.rs
  • cli/tests/cli/update/option_newer_mtime.rs
  • cli/tests/cli/update/option_newer_mtime_than.rs
  • cli/tests/cli/update/option_older_ctime.rs
  • cli/tests/cli/update/option_older_ctime_than.rs
  • cli/tests/cli/update/option_older_mtime.rs
  • cli/tests/cli/update/option_older_mtime_than.rs
  • cli/tests/cli/update/option_recursive.rs
  • cli/tests/cli/update/option_sync.rs

Comment thread cli/src/command/update.rs
Comment on lines 583 to 592
let mut target_files_mapping = target_items
.into_iter()
.enumerate()
.map(|(idx, item)| (EntryName::from_lossy(&item.path), (idx, item)))
.filter_map(|(idx, item)| {
create_options
.pathname_editor
.edit_entry_name(&item.path)
.map(|name| (name, (idx, item)))
})
.collect::<IndexMap<_, _>>();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Detect transformed-name collisions instead of silently overwriting.

This direct collect::<IndexMap<_, _>>() can silently replace earlier items when multiple source paths normalize to the same entry name. That can skip intended updates/additions with no warning.

Suggested fix
-    let mut target_files_mapping = target_items
-        .into_iter()
-        .enumerate()
-        .filter_map(|(idx, item)| {
-            create_options
-                .pathname_editor
-                .edit_entry_name(&item.path)
-                .map(|name| (name, (idx, item)))
-        })
-        .collect::<IndexMap<_, _>>();
+    let mut target_files_mapping = IndexMap::new();
+    for (idx, item) in target_items.into_iter().enumerate() {
+        let Some(name) = create_options.pathname_editor.edit_entry_name(&item.path) else {
+            continue;
+        };
+        if let Some((_, prev_item)) = target_files_mapping.get(&name) {
+            anyhow::bail!(
+                "multiple input paths map to the same archive entry '{}': '{}' and '{}'",
+                name,
+                prev_item.path.display(),
+                item.path.display()
+            );
+        }
+        target_files_mapping.insert(name, (idx, item));
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let mut target_files_mapping = target_items
.into_iter()
.enumerate()
.map(|(idx, item)| (EntryName::from_lossy(&item.path), (idx, item)))
.filter_map(|(idx, item)| {
create_options
.pathname_editor
.edit_entry_name(&item.path)
.map(|name| (name, (idx, item)))
})
.collect::<IndexMap<_, _>>();
let mut target_files_mapping = IndexMap::new();
for (idx, item) in target_items.into_iter().enumerate() {
let Some(name) = create_options.pathname_editor.edit_entry_name(&item.path) else {
continue;
};
if let Some((_, prev_item)) = target_files_mapping.get(&name) {
anyhow::bail!(
"multiple input paths map to the same archive entry '{}': '{}' and '{}'",
name,
prev_item.path.display(),
item.path.display()
);
}
target_files_mapping.insert(name, (idx, item));
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cli/src/command/update.rs` around lines 583 - 592, The current collection
into target_files_mapping uses collect::<IndexMap<_, _>>() which will silently
overwrite earlier entries when
create_options.pathname_editor.edit_entry_name(&item.path) returns the same name
for multiple target_items; change the logic that builds target_files_mapping
(the block using target_items.into_iter().enumerate().filter_map(...) and
collected into target_files_mapping) to explicitly detect duplicates: iterate
and attempt to insert each (name, (idx, item)) into the map, check
target_files_mapping.contains_key(&name) (or use entry API) and on collision
return an Err or accumulate a clear diagnostic mentioning the duplicate
transformed name and the conflicting source paths (using edit_entry_name and the
original item.path) so callers can fail fast instead of silently overwriting.

@github-actions github-actions Bot added the cli This issue is about cli application label Apr 30, 2026
The `update` command failed to correctly match filesystem paths against
existing archive entries when path transformations (like
`--strip-components`) were used. This led to duplicate entries instead
of updates.

This fix ensures that filesystem paths are normalized using the same
logic as archive entry names before being used as keys in the matching
logic.

The `update` command remains an experimental feature.

Co-authored-by: ChanTsune <41658782+ChanTsune@users.noreply.github.com>
@ChanTsune ChanTsune closed this May 3, 2026
@ChanTsune ChanTsune deleted the fix-cli-update-bug-and-stabilize-14259518636105600921 branch May 3, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli This issue is about cli application

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant