Repository navigation
Renaming: v2.0 rewrite — fix batch failures, security vulnerability, add undo history - #25499
TurboCoder13 wants to merge 27 commits into
Conversation
Add vitest test framework, update TypeScript to ES2023 with noImplicitOverride, and add validate/typecheck/test scripts.
Define FileInfo, RenameOperation, NamingTemplate and other core types. Add enums for CaseStyle, SelectionMode, SortField, FileCategory, etc.
Structured logging with module-scoped loggers, custom error hierarchy (FileNotFoundError, PermissionError, ConflictError, etc.), centralized constants, filename validation, and regex safety checks.
Batch rename with conflict detection, file type categorization, case transformation (8 styles), clipboard parsing, OS capability detection, progress tracking, selection summary, and thumbnail generation via Quick Look.
Template parser with variable resolution ({original}, {counter},
{date}, {exif.*}, {file.*}, {spotlight.*}), format specifiers,
transliteration, sorting, and built-in template defaults.
Extract image EXIF data (camera, dimensions, GPS, exposure settings), Spotlight metadata (audio, video, document properties), and file stats (size, dates) for use in template variables.
Type-specific AI prompts for images, videos, audio, documents, and code files. Includes prompt builder, suggested name cleaning, and metadata-aware context generation for Raycast AI.
Undo/redo history with LocalStorage persistence (last 10 operations), and preset system for saving/loading rename configurations including template presets.
Hooks for file selection (Finder integration), rename form logic, AI suggestions, file metadata loading, and thumbnail caching. All hooks include structured logging for error diagnostics.
Reusable components for file metadata detail, file selection form, rename form view, results view, template builder/preview, history detail view, and undo action panel.
Replace monolithic index.tsx with focused command modules: rename, replace, clipboard-rename, ai-suggest, history, and presets. Remove legacy replace.tsx and utils.tsx.
26 test files covering core library modules: file operations, template system, metadata extraction, clipboard parsing, case transforms, validation, history, presets, and more. Includes Raycast API/utils mocks and test fixtures. 85% coverage thresholds configured.
Update README with v2.0 features, fix CHANGELOG to Keep a Changelog format, add LIMITATIONS.md, and update extension screenshots for the Raycast Store.
A note on the single-command hub patternThe original extension had 2 top-level commands. This rewrite adds significantly more functionality — the full set is now 8 sub-commands:
I chose to consolidate these into a single "Renaming" hub command rather than exposing all 8 as separate top-level commands, for two reasons:
The trade-off is that users lose the ability to search/hotkey individual sub-commands directly, and the original I'd appreciate your guidance on the right approach here. Some options:
Happy to adjust based on what you think works best for users and the Store! 🙇 |
|
Thank you for your contribution! 🎉 🔔 @theodaguier @ridemountainpig you might want to have a look. You can use this guide to learn how to check out the Pull Request locally in order to test it. 📋 Quick checkout commandsBRANCH="improve-renaming-extension"
FORK_URL="https://github.com/TurboCoder13/extensions.git"
EXTENSION_NAME="renaming"
REPO_NAME="extensions"
git clone -n --depth=1 --filter=tree:0 -b $BRANCH $FORK_URL
cd $REPO_NAME
git sparse-checkout set --no-cone "extensions/$EXTENSION_NAME"
git checkout
cd "extensions/$EXTENSION_NAME"
npm install && npm run devWe're currently experiencing a high volume of incoming requests. As a result, the initial review may take up to 10-15 business days. |
Greptile SummaryThis is a substantial v2.0 rewrite of the Renaming extension, replacing the AppleScript-based approach with native Node.js
Confidence Score: 4/5Safe to merge after fixing the case-insensitive undo guard in history.ts; all other previously flagged issues are resolved. One P1 defect remains: the undo system silently fails for every case-transformation rename on macOS due to the case-insensitive filesystem not being accounted for in the fileExists guard. Since case transformation is a headline feature of this rewrite, leaving it un-undoable is a present, reproducible bug. All prior review findings are addressed. extensions/renaming/src/lib/history.ts — both Important Files Changed
Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 88-91
Comment:
**Undo blocked for case-change renames on macOS**
`fileExists(op.oldPath)` uses `fs.access()`, which on macOS's case-insensitive APFS/HFS+ filesystem treats `photo.jpg` and `PHOTO.JPG` as the same path. After renaming `photo.jpg` → `PHOTO.JPG`, undoing hits this guard: `fileExists("photo.jpg")` returns `true` (because `PHOTO.JPG` is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.
Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.
The `files.ts` module already has the helper needed here. Skip the guard when `oldPath` and `newPath` are the same on the current filesystem:
```ts
// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
errors.push(`${basename(op.oldPath)} already exists`);
failedOps.push(op);
continue;
}
```
The same pattern applies in `undoToPoint()` at line 168.
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 168-171
Comment:
**Same case-insensitive undo bug in `undoToPoint`**
Same issue as line 88: `fileExists(op.oldPath)` incorrectly returns `true` for case-change renames on macOS, blocking `undoToPoint` from reverting any case-transformation operation. Apply the same `isCaseOnlyRename` guard here.
How can I resolve this? If you propose a fix, please make it concise.Reviews (4): Last reviewed commit: "fix: address CodeRabbit review findings ..." | Re-trigger Greptile |
…and wasteful EXIF reads
- Fix double-dot filenames in ai-suggest, clipboard, and template commands
where `.${file.extension}` produced `name..jpg` since extname() already
includes the leading dot
- Fix inline sample FileInfo using `extension: "jpg"` instead of `".jpg"`
- Replace shell `mv` command in thumbnails.ts with fs.rename() to eliminate
shell injection via filenames containing single quotes
- Gate EXIF metadata extraction to image files only, avoiding reading entire
non-image files into memory
Address division-by-zero in shutter speed, array bounds in EXIF, DateTimeOriginal regex validation, negative bytes guard, units overflow clamping, Promise.allSettled for resilient extraction, and artist/author space-preserving parsing in Spotlight metadata.
Normalize toTitleCase to lowercase remainder, fix duration :60 bug in audio/video prompts, reorder detectFormatType to check time before date, handle negative numbers in formatNumber, guard formatSize against negative/non-finite bytes, and accept 0 as valid random length.
Use UTF-8 byte length for filename validation, add backslash to invalid chars, fix RFC 4180 CSV parsing, sanitize thumbnail size parameter, re-sanitize after space replacement in transliterate, escape regex special chars in template parser, use path.dirname for directory extraction, add platform-aware path handling, and guard null extension.
Wrap undo/delete/save operations in try/catch across commands and components, add error state in useSelectedFiles, fix isLoading on null paths, correct fallback group size, remove unused historyDescription field, fix pluralization, add truncation indicator for directory groups, accept 0 as counter start, fix duplicate keyboard shortcuts, and preserve history on complete undo failure.
Update Preserve Name Mode terminology in README, clarify undo history and regex limitation descriptions, and remove vitest/globals from tsconfig types (already set in vitest.config.ts).
Use path.extname for hidden file extension extraction in template preview, make thumbnail test assertions explicit instead of conditional, and always use extname with fallback in isPreviewableImage.
|
@greptile can you do a fresh review please? |
kMDItemAuthors was read twice — once for artist (line 178) and again for author (line 206), making both fields always identical. Author now reads from kMDItemCreator first, falling back to kMDItemAuthors.
Re-validate the pattern inside the submit handler instead of relying on stale useEffect-based regexError state, preventing silent failures when the user types quickly and submits before state updates.
File Breakdown
Distribution |
- Return fallback string for empty input in buildAutoSummary - Use consistent "exif." prefix in getRequiredDateSource - Skip directories in groupFilesByExtension - Pad with "unnamed" instead of empty string in parseBatchAIResponse - Clear stale UI state after successful undo in useRenameOperations - Add error handling to handleClearHistory and loadHistory in history command - Always reload history after undoToPoint for partial undo handling - Use SortDirection.DESC enum instead of string literal in template builder - Remove inconsistent readonly from ExtensionGroupConfig.extension - Include file mtime in thumbnail cache key for staleness detection - Guard safeSize against NaN with Number.isFinite fallback - Update tests to match new behavior
dc13666 to
29a4d5e
Compare
|
@greptileai can you please do full review? |
|
Thanks for the update @TurboCoder13 @theodaguier do you want to check this? |
|
Giving @theodaguier a few days to review 🙂 |
|
This pull request has been automatically marked as stale because it did not have any recent activity. It will be closed if no further activity occurs in the next 7 days to keep our backlog clean 😊 |
|
This pull request has been automatically closed due to inactivity. Feel free to comment in the thread when you're ready to continue working on it 🙂 You can also catch us in Slack if you want to discuss this. |
|
Hey @pernielsentikaer 👋 I just got back from vacation, so I unfortunately didn't get to look at this before it went stale and got closed 😅 May I re-open the PR or perhaps do something else for these changes? 🤞 |
|
Hey @TurboCoder13, thanks for putting so much work into this — the security fix ( A few things we'd need before we can merge this:
The foundation is solid and the direction is good — just need to make it more incremental so we can land it safely. Happy to help if you have questions! |
|
@pernielsentikaer thanks so much! I appreciate the response and I will make work of your advice 🙂 |
| if (await fileExists(op.oldPath)) { | ||
| errors.push(`${basename(op.oldPath)} already exists`); | ||
| failedOps.push(op); | ||
| continue; |
There was a problem hiding this comment.
Undo blocked for case-change renames on macOS
fileExists(op.oldPath) uses fs.access(), which on macOS's case-insensitive APFS/HFS+ filesystem treats photo.jpg and PHOTO.JPG as the same path. After renaming photo.jpg → PHOTO.JPG, undoing hits this guard: fileExists("photo.jpg") returns true (because PHOTO.JPG is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.
Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.
The files.ts module already has the helper needed here. Skip the guard when oldPath and newPath are the same on the current filesystem:
// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
errors.push(`${basename(op.oldPath)} already exists`);
failedOps.push(op);
continue;
}The same pattern applies in undoToPoint() at line 168.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/renaming/src/lib/history.ts
Line: 88-91
Comment:
**Undo blocked for case-change renames on macOS**
`fileExists(op.oldPath)` uses `fs.access()`, which on macOS's case-insensitive APFS/HFS+ filesystem treats `photo.jpg` and `PHOTO.JPG` as the same path. After renaming `photo.jpg` → `PHOTO.JPG`, undoing hits this guard: `fileExists("photo.jpg")` returns `true` (because `PHOTO.JPG` is the same inode), so the undo aborts with "photo.jpg already exists" — even though the file you're trying to restore IS that file.
Since case transformation (lowercase → UPPERCASE, etc.) is a primary feature of this rewrite, every case-change batch will be un-undoable.
The `files.ts` module already has the helper needed here. Skip the guard when `oldPath` and `newPath` are the same on the current filesystem:
```ts
// Check if original path is free
// Skip when oldPath and newPath are the same file (case-only rename on case-insensitive FS)
const isCaseOnlyRename = op.oldPath.toLowerCase() === op.newPath.toLowerCase();
if (!isCaseOnlyRename && (await fileExists(op.oldPath))) {
errors.push(`${basename(op.oldPath)} already exists`);
failedOps.push(op);
continue;
}
```
The same pattern applies in `undoToPoint()` at line 168.
How can I resolve this? If you propose a fix, please make it concise.
🤖 Disclosure
This rewrite was developed with AI assistance (Claude Code, Codex and CodeRabbitAI), with my guidance on architecture, requirements, and testing. All code was reviewed and validated by me, including manual testing in Raycast.
Description
This PR is a complete rewrite of the Renaming extension, motivated by critical bugs and a security vulnerability in the original AppleScript-based approach.
Why the rewrite
1. Batch failures
The original implementation spawned a separate
osascriptprocess for each file rename viaspawnSync(). In practice, this became unreliable — I noticed timeouts and partial completion starting around ~90 files, where some files were renamed while others were silently skipped, with no indication of which succeeded or failed and no way to undo. Switching to nativefs.rename()eliminates the problem entirely.2. Shell injection vulnerability
Filenames were interpolated directly into
osascriptcommands with only"→\"escaping:This is insufficient — filenames containing other shell metacharacters could inject arbitrary AppleScript commands. A targeted security fix was merged upstream (ad9f7d6), but this rewrite eliminates the entire attack surface by using Node.js
fs.rename()directly.3. No error recovery
The original had a single
try/catcharound the entire rename loop. A failure mid-batch left files in an inconsistent state with no per-file error tracking, no conflict detection, and no undo capability.What changed
fs.rename()— eliminates process spawning overhead and shell injection entirelyNote on command structure
The original extension exposed 2 top-level commands (
Rename File(s)andReplace File(s) Characters). This rewrite consolidates into a single hub command with 8 sub-commands accessible via a menu. Both original commands are preserved and enhanced within the hub. See my follow-up comment for more context on this decision.Screencast
Screenshots in
metadata/folder.Checklist
npm run buildand tested the distribution build in Raycastassetsfolder are used by the extension