Merge branch 'main' into feature/extension-settings

This commit is contained in:
Sanjula Ganepola
2024-11-27 20:03:43 -05:00
17 changed files with 358 additions and 130 deletions

View File

@@ -1,7 +1,10 @@
import * as childProcess from "child_process";
import * as fs from "fs/promises";
import * as path from "path";
import sanitize from "sanitize-filename";
import { ExtensionContext, ShellExecution, TaskGroup, TaskPanelKind, TaskRevealKind, tasks, TaskScope, Uri, window, workspace, WorkspaceFolder } from "vscode";
import { commands, CustomExecution, env, EventEmitter, ExtensionContext, Pseudoterminal, ShellExecution, TaskDefinition, TaskGroup, TaskPanelKind, TaskRevealKind, tasks, TaskScope, TerminalDimensions, Uri, window, workspace, WorkspaceFolder } from "vscode";
import { ComponentsManager } from "./componentsManager";
import { ConfigurationManager, Platform, Section } from "./configurationManager";
import { componentsTreeDataProvider, historyTreeDataProvider } from './extension';
import { HistoryManager, HistoryStatus } from './historyManager';
import { SecretManager } from "./secretManager";
@@ -70,7 +73,8 @@ export interface CommandArgs {
}
export class Act {
private static base: string = 'act';
static defaultActCommand: string = 'act';
static githubCliActCommand: string = 'gh act';
context: ExtensionContext;
storageManager: StorageManager;
secretManager: SecretManager;
@@ -80,6 +84,8 @@ export class Act {
settingsManager: SettingsManager;
installationCommands: { [packageManager: string]: string };
prebuiltExecutables: { [architecture: string]: string };
refreshInterval: NodeJS.Timeout | undefined;
runningTaskCount: number;
constructor(context: ExtensionContext) {
this.context = context;
@@ -89,6 +95,7 @@ export class Act {
this.workflowsManager = new WorkflowsManager();
this.historyManager = new HistoryManager(this.storageManager);
this.settingsManager = new SettingsManager(this.storageManager, this.secretManager);
this.runningTaskCount = 0;
switch (process.platform) {
case 'win32':
@@ -96,7 +103,7 @@ export class Act {
'Chocolatey': 'choco install act-cli',
'Winget': 'winget install nektos.act',
'Scoop': 'scoop install act',
'GitHub CLI': 'gh extension install https://github.com/nektos/gh-act'
'GitHub CLI': '(gh auth status || gh auth login) && gh extension install https://github.com/nektos/gh-act'
};
this.prebuiltExecutables = {
@@ -111,7 +118,7 @@ export class Act {
'Homebrew': 'brew install act',
'Nix': 'nix run nixpkgs#act',
'MacPorts': 'sudo port install act',
'GitHub CLI': 'gh extension install https://github.com/nektos/gh-act'
'GitHub CLI': '(gh auth status || gh auth login) && gh extension install https://github.com/nektos/gh-act'
};
this.prebuiltExecutables = {
@@ -123,9 +130,10 @@ export class Act {
this.installationCommands = {
'Homebrew': 'brew install act',
'Nix': 'nix run nixpkgs#act',
'Arch': 'pacman -Syu act',
'AUR': 'yay -Syu act',
'COPR': 'dnf copr enable goncalossilva/act && dnf install act-cli',
'GitHub CLI': 'gh extension install https://github.com/nektos/gh-act'
'GitHub CLI': '(gh auth status || gh auth login) && gh extension install https://github.com/nektos/gh-act'
};
this.prebuiltExecutables = {
@@ -142,80 +150,57 @@ export class Act {
}
// Setup automatic history view refreshing
let refreshInterval: NodeJS.Timeout | undefined;
tasks.onDidStartTask(e => {
const taskDefinition = e.execution.task.definition;
if (taskDefinition.type === 'GitHub Local Actions' && !refreshInterval) {
refreshInterval = setInterval(() => {
historyTreeDataProvider.refresh();
}, 1000);
if (taskDefinition.type === 'GitHub Local Actions') {
this.runningTaskCount++;
if (!this.refreshInterval && this.runningTaskCount >= 0) {
this.refreshInterval = setInterval(() => {
historyTreeDataProvider.refresh();
}, 1000);
}
}
});
tasks.onDidEndTask(e => {
const taskDefinition = e.execution.task.definition;
if (taskDefinition.type === 'GitHub Local Actions') {
if (refreshInterval) {
clearInterval(refreshInterval);
refreshInterval = undefined;
this.runningTaskCount--;
if (this.refreshInterval && this.runningTaskCount == 0) {
clearInterval(this.refreshInterval);
this.refreshInterval = undefined;
}
}
});
// Refresh components view after installation
tasks.onDidEndTask(e => {
tasks.onDidEndTaskProcess(async e => {
const taskDefinition = e.execution.task.definition;
if (taskDefinition.type === 'nektos/act installation') {
if (taskDefinition.type === 'nektos/act installation' && e.exitCode === 0) {
this.updateActCommand(taskDefinition.ghCliInstall ? Act.githubCliActCommand : Act.defaultActCommand);
componentsTreeDataProvider.refresh();
}
});
}
tasks.onDidStartTaskProcess(e => {
const taskDefinition = e.execution.task.definition;
if (taskDefinition.type === 'GitHub Local Actions') {
const commandArgs: CommandArgs = taskDefinition.commandArgs;
const historyIndex = taskDefinition.historyIndex;
static getActCommand() {
return ConfigurationManager.get<string>(Section.actCommand) || Act.defaultActCommand;
}
// Add new entry to workspace history
this.historyManager.workspaceHistory[commandArgs.path].push({
index: historyIndex,
count: taskDefinition.count,
name: `${commandArgs.name}`,
status: HistoryStatus.Running,
date: {
start: taskDefinition.start.toString()
},
taskExecution: e.execution,
commandArgs: commandArgs,
logPath: taskDefinition.logPath
});
historyTreeDataProvider.refresh();
this.storageManager.update(StorageKey.WorkspaceHistory, this.historyManager.workspaceHistory);
}
});
tasks.onDidEndTaskProcess(e => {
const taskDefinition = e.execution.task.definition;
if (taskDefinition.type === 'GitHub Local Actions') {
const commandArgs: CommandArgs = taskDefinition.commandArgs;
const historyIndex = taskDefinition.historyIndex;
updateActCommand(newActCommand: string) {
const actCommand = ConfigurationManager.get(Section.actCommand);
// Set end status
if (this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status === HistoryStatus.Running) {
if (e.exitCode === 0) {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Success;
} else if (!e.exitCode) {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Cancelled;
} else {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Failed;
}
if (newActCommand !== actCommand) {
window.showInformationMessage(`The act command is currently set to "${actCommand}". Once the installation is complete, it is recommended to update this to "${newActCommand}" for this selected installation method.`, 'Proceed', 'Manually Edit').then(async value => {
if (value === 'Proceed') {
await ConfigurationManager.set(Section.actCommand, newActCommand);
componentsTreeDataProvider.refresh();
} else if (value === 'Manually Edit') {
await commands.executeCommand('workbench.action.openSettings', ConfigurationManager.getSearchTerm(Section.actCommand));
}
// Set end time
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].date.end = new Date().toString();
historyTreeDataProvider.refresh();
this.storageManager.update(StorageKey.WorkspaceHistory, this.historyManager.workspaceHistory);
}
});
});
}
}
async runAllWorkflows(workspaceFolder: WorkspaceFolder) {
@@ -309,22 +294,21 @@ export class Act {
} catch (error: any) { }
// Build command with settings
const actCommand = Act.getActCommand();
const settings = await this.settingsManager.getSettings(workspaceFolder, true);
const command =
`set -o pipefail; ` +
`${Act.base} ${commandArgs.options}` +
`${actCommand} ${commandArgs.options}` +
(settings.secrets.length > 0 ? ` ${Option.Secret} ${settings.secrets.map(secret => secret.key).join(` ${Option.Secret} `)}` : ``) +
(settings.secretFiles.length > 0 ? ` ${Option.SecretFile} "${settings.secretFiles[0].path}"` : ` ${Option.SecretFile} ""`) +
(settings.variables.length > 0 ? ` ${Option.Variable} ${settings.variables.map(variable => (variable.value ? `${variable.key}=${variable.value}` : variable.key)).join(` ${Option.Variable} `)}` : ``) +
(settings.variables.length > 0 ? ` ${Option.Variable} ${settings.variables.map(variable => `${variable.key}=${variable.value}`).join(` ${Option.Variable} `)}` : ``) +
(settings.variableFiles.length > 0 ? ` ${Option.VariableFile} "${settings.variableFiles[0].path}"` : ` ${Option.VariableFile} ""`) +
(settings.inputs.length > 0 ? ` ${Option.Input} ${settings.inputs.map(input => `${input.key}=${input.value}`).join(` ${Option.Input} `)}` : ``) +
(settings.inputFiles.length > 0 ? ` ${Option.InputFile} "${settings.inputFiles[0].path}"` : ` ${Option.InputFile} ""`) +
(settings.runners.length > 0 ? ` ${Option.Platform} ${settings.runners.map(runner => `${runner.key}=${runner.value}`).join(` ${Option.Platform} `)}` : ``) +
(settings.payloadFiles.length > 0 ? ` ${Option.PayloadFile} "${settings.payloadFiles[0].path}"` : ` ${Option.PayloadFile} ""`) +
` 2>&1 | tee "${logPath}"`;
(settings.payloadFiles.length > 0 ? ` ${Option.PayloadFile} "${settings.payloadFiles[0].path}"` : ` ${Option.PayloadFile} ""`);
// Execute task
await tasks.executeTask({
const taskExecution = await tasks.executeTask({
name: `${commandArgs.name} #${count}`,
detail: `${commandArgs.name} #${count}`,
definition: {
@@ -350,18 +334,129 @@ export class Act {
problemMatchers: [],
runOptions: {},
group: TaskGroup.Build,
execution: new ShellExecution(
command,
{
cwd: commandArgs.path,
env: settings.secrets
.filter(secret => secret.value)
.reduce((previousValue, currentValue) => {
previousValue[currentValue.key] = currentValue.value;
return previousValue;
}, {} as Record<string, string>)
execution: new CustomExecution(async (resolvedDefinition: TaskDefinition): Promise<Pseudoterminal> => {
// Add new entry to workspace history
this.historyManager.workspaceHistory[commandArgs.path].push({
index: historyIndex,
count: count,
name: `${commandArgs.name}`,
status: HistoryStatus.Running,
date: {
start: start.toString()
},
taskExecution: taskExecution,
commandArgs: commandArgs,
logPath: logPath
});
historyTreeDataProvider.refresh();
this.storageManager.update(StorageKey.WorkspaceHistory, this.historyManager.workspaceHistory);
const writeEmitter = new EventEmitter<string>();
const closeEmitter = new EventEmitter<number>();
writeEmitter.event(async data => {
try {
// Create log file if it does not exist
try {
await fs.access(logPath);
} catch (error: any) {
await fs.writeFile(logPath, '');
}
// Append data to log file
await fs.appendFile(logPath, data);
} catch (error) { }
});
const handleIO = (data: any) => {
const lines: string[] = data.toString().split('\n').filter((line: string) => line != '');
for (const line of lines) {
writeEmitter.fire(`${line.trimEnd()}\r\n`);
}
}
)
let shell = env.shell;
switch (process.platform) {
case Platform.windows:
shell = 'cmd';
break;
case Platform.mac:
shell = 'zsh';
break;
case Platform.linux:
shell = 'bash';
break;
}
const exec = childProcess.spawn(
command,
{
cwd: commandArgs.path,
shell: shell,
env: {
...process.env,
...settings.secrets
.filter(secret => secret.value)
.reduce((previousValue, currentValue) => {
previousValue[currentValue.key] = currentValue.value;
return previousValue;
}, {} as Record<string, string>)
}
}
);
exec.stdout.on('data', handleIO);
exec.stderr.on('data', handleIO);
exec.on('exit', (code, signal) => {
// Set execution status and end time in workspace history
if (this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status === HistoryStatus.Running) {
if (code === 0) {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Success;
} else if (!code) {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Cancelled;
} else {
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].status = HistoryStatus.Failed;
}
}
this.historyManager.workspaceHistory[commandArgs.path][historyIndex].date.end = new Date().toString();
historyTreeDataProvider.refresh();
this.storageManager.update(StorageKey.WorkspaceHistory, this.historyManager.workspaceHistory);
if (signal === 'SIGINT') {
writeEmitter.fire(`\r\nTask interrupted.\r\n`);
closeEmitter.fire(code || 1);
} else {
writeEmitter.fire(`\r\nTask exited with exit code ${code}.\r\n`);
closeEmitter.fire(code || 0);
}
});
exec.on('close', (code) => {
closeEmitter.fire(code || 0);
});
return {
onDidWrite: writeEmitter.event,
onDidClose: closeEmitter.event,
open: async (initialDimensions: TerminalDimensions | undefined): Promise<void> => {
writeEmitter.fire(`${command}\r\n\r\n`);
},
handleInput: (data: string) => {
if (data === '\x03') {
exec.kill('SIGINT');
exec.stdout.destroy();
exec.stdin.destroy();
exec.stderr.destroy();
} else {
exec.stdin.write(data === '\r' ? '\r\n' : data)
}
},
close: () => {
exec.kill('SIGINT');
exec.stdout.destroy();
exec.stdin.destroy();
exec.stderr.destroy();
},
};
})
});
this.storageManager.update(StorageKey.WorkspaceHistory, this.historyManager.workspaceHistory);
}
@@ -372,7 +467,10 @@ export class Act {
await tasks.executeTask({
name: 'nektos/act',
detail: 'Install nektos/act',
definition: { type: 'nektos/act installation' },
definition: {
type: 'nektos/act installation',
ghCliInstall: command.includes('gh-act')
},
source: 'GitHub Local Actions',
scope: TaskScope.Workspace,
isBackground: true,