Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active March 13, 2022 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kekru/256d73c7819efc35e55cd88c5903ab46 to your computer and use it in GitHub Desktop.
Save kekru/256d73c7819efc35e55cd88c5903ab46 to your computer and use it in GitHub Desktop.
Command for each project in VS Code workspace

Run a command in every directory of a VSCode workspace

Deno must be installed.
On Windows GitBash is required.

Setup an alias and then run a command in every project of a VSCode workspace

# Store alias in $HOME/.bashrc
alias vsforeach="deno run --allow-run --allow-read https://gist.githubusercontent.com/kekru/256d73c7819efc35e55cd88c5903ab46/raw/25072c432cbadee38ca2d725fbe7f03f5f6eafcc/vsforeach.js"

# Run command, referencing the .code-workspace file and your command
# "#PROJECT" will be replaced by the folder name of the current project
vsforeach ../something.code-workspace "echo 'Hello #PROJECT'"
#!/usr/bin/env -S deno run --allow-run --allow-read
function showUsage() {
console.log("Example: deno run --allow-run --allow-read vsforeach.ts ../something.code-workspace \"echo 'Hello #PROJECT'\"")
Deno.exit(1)
}
if (Deno.args.length < 2) {
showUsage()
}
const workspaceFile = Deno.args[0]
const command = Deno.args[1]
console.log('workspaceFile', workspaceFile)
console.log('command', command)
if (!workspaceFile || !command) {
showUsage()
}
const indexOfLastSlash = workspaceFile.lastIndexOf('/')
const workspaceDir = indexOfLastSlash > -1
? workspaceFile.substring(0, indexOfLastSlash)
: '.'
const workspace = JSON.parse(await Deno.readTextFile(workspaceFile))
const decoder = new TextDecoder()
const preludeCommands = Deno.build.os === 'windows'
? [
"C:\\Program Files\\Git\\bin\\bash",
"--login",
"-i",
"-c"
]
: [
"/usr/local/bin/bash",
"-c"
];
let index = 0;
for (const project of workspace.folders) {
const projectName = project.path
const currentCommand = command.replace('#PROJECT', projectName)
console.log(`[${(index + 1).toString().padStart(2, '0')}] Run script for "${projectName}" with "${currentCommand}"`)
const allCommands = preludeCommands.concat([
`cd ${workspaceDir}/${projectName} && ${currentCommand}`
]);
const cmd = Deno.run(
{
cmd: allCommands,
stdout: "piped",
stderr: "piped"
}
);
const output = decoder.decode(await cmd.output())
const errOutput = decoder.decode(await cmd.stderrOutput())
if (output) {
console.log(output)
}
if (errOutput) {
console.log(errOutput)
}
cmd.close()
console.log("----")
index += 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment