Skip to content

Commit

Permalink
feat: Add menu item for "Search in Git Changed Files" command
Browse files Browse the repository at this point in the history
  • Loading branch information
YuTengjing authored and YuTengjing committed Apr 21, 2024
1 parent f710a38 commit 68d31c9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@
"onStartupFinished"
],
"contributes": {
"menus": {
"view/title": [
{
"command": "power-edit.searchInGitChangedFiles",
"when": "view == workbench.view.search",
"group": "navigation"
}
]
},
"commands": [
{
"command": "power-edit.selectBracketContent",
Expand All @@ -75,7 +84,8 @@
},
{
"command": "power-edit.searchInGitChangedFiles",
"title": "Search in Git Changed Files"
"title": "Search in Git Changed Files",
"icon": "$(diff-added)"
}
]
},
Expand Down
18 changes: 13 additions & 5 deletions src/features/searchInGitChangedFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,36 @@ export async function searchInGitChangedFiles() {
return vscode.window.showErrorMessage('No workspace is opened');
}

// maybe the workspace is in a subdirectory of the git repo
let { stdout: gitRepoDir } = await exec('git rev-parse --show-toplevel', { cwd });
gitRepoDir = gitRepoDir.trim();
if (!gitRepoDir) {
return vscode.window.showErrorMessage('Not a Git repository');
}

cwd = gitRepoDir;
// Step 1: Detect Git changes
const [modifiedFilesOutput, addedFilesOutput] = await Promise.all([
const outputList = await Promise.all([
// staged
exec('git diff --name-only --cached', { cwd }),
// changed and not staged
exec('git diff --name-only', { cwd }),
// new added
exec('git ls-files --others --exclude-standard', { cwd }),
]);
if (modifiedFilesOutput.stderr || addedFilesOutput.stderr) {
if (outputList.some(({ stderr }) => stderr)) {
return vscode.window.showErrorMessage('Failed to detect Git changes');
}

const changedFiles = `${modifiedFilesOutput.stdout}\n${addedFilesOutput.stdout}`
let changedFiles = outputList
.map(({ stdout }) => stdout)
.join('\n')
.split(/\r?\n/)
.filter(Boolean);
.filter((line) => line.trim() !== '');
changedFiles = [...new Set(changedFiles)];

return vscode.commands.executeCommand('workbench.action.findInFiles', {
triggerSearch: true,
searchDetail: true,
filesToInclude: changedFiles.join(', '),
});
}

0 comments on commit 68d31c9

Please sign in to comment.