Skip to content

Commit

Permalink
#862 - evaluate the node command
Browse files Browse the repository at this point in the history
  • Loading branch information
estruyf committed Oct 28, 2024
1 parent fc96c89 commit f8f539b
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 116 deletions.
99 changes: 21 additions & 78 deletions src/helpers/CustomScript.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Settings } from './SettingsHelper';
import { CommandType } from './../models/PanelSettings';
import { CustomScript as ICustomScript, ScriptType } from '../models/PanelSettings';
import { window, env as vscodeEnv, ProgressLocation, Uri, commands, workspace } from 'vscode';
import { window, env as vscodeEnv, ProgressLocation, Uri, commands } from 'vscode';
import { ArticleHelper, Logger, MediaHelpers } from '.';
import { Folders, WORKSPACE_PLACEHOLDER } from '../commands/Folders';
import { exec, execSync } from 'child_process';
Expand All @@ -13,10 +13,8 @@ import { Dashboard } from '../commands/Dashboard';
import { DashboardCommand } from '../dashboardWebView/DashboardCommand';
import { ParsedFrontMatter } from '../parsers';
import { SETTING_CUSTOM_SCRIPTS } from '../constants';
import { existsAsync, getPlatform } from '../utils';
import * as l10n from '@vscode/l10n';
import { LocalizationKey } from '../localization';
import { ShellSetting } from '../models';
import { evaluateCommand, existsAsync, getPlatform } from '../utils';
import { LocalizationKey, localize } from '../localization';

export class CustomScript {
/**
Expand Down Expand Up @@ -102,7 +100,7 @@ export class CustomScript {
);
} else {
Notifications.warning(
l10n.t(LocalizationKey.helpersCustomScriptSingleRunArticleWarning, script.title)
localize(LocalizationKey.helpersCustomScriptSingleRunArticleWarning, script.title)
);
}
}
Expand All @@ -118,7 +116,7 @@ export class CustomScript {

if (!folders || folders.length === 0) {
Notifications.warning(
l10n.t(LocalizationKey.helpersCustomScriptBulkRunNoFilesWarning, script.title)
localize(LocalizationKey.helpersCustomScriptBulkRunNoFilesWarning, script.title)
);
return;
}
Expand All @@ -128,7 +126,7 @@ export class CustomScript {
window.withProgress(
{
location: ProgressLocation.Notification,
title: l10n.t(LocalizationKey.helpersCustomScriptExecuting, script.title),
title: localize(LocalizationKey.helpersCustomScriptExecuting, script.title),
cancellable: false
},
async (_, __) => {
Expand Down Expand Up @@ -174,7 +172,7 @@ export class CustomScript {
): Promise<void> {
if (!path) {
Notifications.error(
l10n.t(LocalizationKey.helpersCustomScriptRunMediaScriptNoFolderWarning, script.title)
localize(LocalizationKey.helpersCustomScriptRunMediaScriptNoFolderWarning, script.title)
);
return;
}
Expand All @@ -183,7 +181,7 @@ export class CustomScript {
window.withProgress(
{
location: ProgressLocation.Notification,
title: l10n.t(LocalizationKey.helpersCustomScriptExecuting, script.title),
title: localize(LocalizationKey.helpersCustomScriptExecuting, script.title),
cancellable: false
},
async () => {
Expand Down Expand Up @@ -310,7 +308,10 @@ export class CustomScript {
throw new Error(`Couldn't update article.`);
}
Notifications.info(
l10n.t(LocalizationKey.helpersCustomScriptShowOutputFrontMatterSuccess, script.title)
localize(
LocalizationKey.helpersCustomScriptShowOutputFrontMatterSuccess,
script.title
)
);
}
} else if (data.fmAction) {
Expand Down Expand Up @@ -346,18 +347,20 @@ export class CustomScript {
window
.showInformationMessage(
`${script.title}: ${output}`,
l10n.t(LocalizationKey.helpersCustomScriptShowOutputCopyOutputAction)
localize(LocalizationKey.helpersCustomScriptShowOutputCopyOutputAction)
)
.then((value) => {
if (value === l10n.t(LocalizationKey.helpersCustomScriptShowOutputCopyOutputAction)) {
if (
value === localize(LocalizationKey.helpersCustomScriptShowOutputCopyOutputAction)
) {
vscodeEnv.clipboard.writeText(output);
}
});
}
}
} else {
Notifications.info(
l10n.t(LocalizationKey.helpersCustomScriptShowOutputSuccess, script.title)
localize(LocalizationKey.helpersCustomScriptShowOutputSuccess, script.title)
);
}
}
Expand All @@ -383,7 +386,7 @@ export class CustomScript {
}

if (script.command === CommandType.Node && platform !== 'windows') {
command = await CustomScript.evaluateCommand(CommandType.Node);
command = await evaluateCommand(CommandType.Node);
}

let scriptPath = join(wsPath, script.script);
Expand All @@ -399,7 +402,7 @@ export class CustomScript {
command = environment.command;

if (command === CommandType.Node && platform !== 'windows') {
command = await CustomScript.evaluateCommand(CommandType.Node);
command = await evaluateCommand(CommandType.Node);
}

scriptPath = join(wsPath, environment.script);
Expand All @@ -420,7 +423,7 @@ export class CustomScript {
}

const fullScript = `${command} "${scriptPath}" ${args}`;
Logger.info(l10n.t(LocalizationKey.helpersCustomScriptExecuting, fullScript));
Logger.info(localize(LocalizationKey.helpersCustomScriptExecuting, fullScript));

const output: string = await CustomScript.executeScriptAsync(fullScript, wsPath);

Expand Down Expand Up @@ -503,68 +506,8 @@ export class CustomScript {

return true;
} catch (e) {
Logger.error(l10n.t(LocalizationKey.helpersCustomScriptValidateCommandError, command));
Logger.error(localize(LocalizationKey.helpersCustomScriptValidateCommandError, command));
return false;
}
}

/**
* Evaluate the command dynamically using `which` command
* @param command
* @returns
*/
private static async evaluateCommand(command: string): Promise<string> {
const shell = CustomScript.getShellPath();
let shellPath: string | undefined = undefined;
if (typeof shell !== 'string' && !!shell) {
shellPath = shell.path;
} else {
shellPath = shell || undefined;
}

return new Promise((resolve, reject) => {
exec(`which ${command}`, { shell: shellPath }, (error, stdout) => {
if (error) {
Logger.error(`Error evaluating command: ${command}`);
reject(error);
return;
}

resolve(stdout.trim());
});
});
}

/**
* Retrieves the shell path configuration based on the current platform and terminal settings.
*
* This method checks for the following configurations in order:
* 1. `integrated.automationProfile.<platform>`: Returns the automation profile if it exists.
* 2. `integrated.defaultProfile.<platform>` and `integrated.profiles.<platform>`: Returns the shell setting from the default profile if it exists.
* 3. `integrated.shell.<platform>`: Returns the shell setting if the above configurations are not found.
*
* @returns {string | ShellSetting | undefined} The shell path configuration or undefined if not found.
*/
private static getShellPath(): string | ShellSetting | undefined {
const platform = getPlatform();
const terminalSettings = workspace.getConfiguration('terminal');

const automationProfile = terminalSettings.get<string | ShellSetting>(
`integrated.automationProfile.${platform}`
);
if (!!automationProfile) {
return automationProfile;
}

const defaultProfile = terminalSettings.get<string>(`integrated.defaultProfile.${platform}`);
const profiles = terminalSettings.get<{ [prop: string]: ShellSetting }>(
`integrated.profiles.${platform}`
);

if (defaultProfile && profiles && profiles[defaultProfile]) {
return profiles[defaultProfile];
}

return terminalSettings.get(`integrated.shell.${platform}`);
}
}
9 changes: 7 additions & 2 deletions src/listeners/dashboard/SsgListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from '../../constants';
import { SettingsListener } from './SettingsListener';
import { Terminal } from '../../services';
import { existsAsync, readFileAsync } from '../../utils';
import { evaluateCommand, existsAsync, getPlatform, readFileAsync } from '../../utils';
import { join } from 'path';

export class SsgListener extends BaseListener {
Expand Down Expand Up @@ -170,7 +170,12 @@ export class SsgListener extends BaseListener {
workspace.fs.copy(scriptPath, tempScriptPath, { overwrite: true });
}

const fullScript = `node "${tempScriptPath.fsPath}" "${contentConfigFile.fsPath}"`;
let nodeExecPath = 'node';
const platform = getPlatform();
if (platform !== 'windows') {
nodeExecPath = await evaluateCommand('node');
}
const fullScript = `${nodeExecPath} "${tempScriptPath.fsPath}" "${contentConfigFile.fsPath}"`;

try {
const result: string = await SsgListener.executeScript(fullScript, wsFolder?.fsPath || '');
Expand Down
40 changes: 4 additions & 36 deletions src/services/Terminal.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import { workspace, window, ThemeIcon, TerminalOptions } from 'vscode';
import { Folders } from '../commands';
import * as l10n from '@vscode/l10n';
import { LocalizationKey } from '../localization';
import { getPlatform } from '../utils';

interface ShellSetting {
path: string;
}
import { LocalizationKey, localize } from '../localization';
import { getShellPath } from '../utils';

export class Terminal {
public static readonly terminalName: string = 'Local server';
Expand All @@ -15,7 +10,7 @@ export class Terminal {
* Return the shell path for the current platform
*/
public static get shell() {
const shell: string | { path: string } | undefined = Terminal.getShellPath();
const shell: string | { path: string } | undefined = getShellPath();
let shellPath: string | undefined = undefined;

if (typeof shell !== 'string' && !!shell) {
Expand Down Expand Up @@ -47,7 +42,7 @@ export class Terminal {
const terminalOptions: TerminalOptions = {
name: Terminal.terminalName,
iconPath: new ThemeIcon('server-environment'),
message: l10n.t(
message: localize(
LocalizationKey.servicesTerminalOpenLocalServerTerminalTerminalOptionMessage
)
};
Expand Down Expand Up @@ -90,31 +85,4 @@ export class Terminal {
return localServerTerminal;
}
}

/**
* Retrieve the automation profile for the current platform
* @returns
*/
private static getShellPath(): string | ShellSetting | undefined {
const platform = getPlatform();
const terminalSettings = workspace.getConfiguration('terminal');

const automationProfile = terminalSettings.get<string | ShellSetting>(
`integrated.automationProfile.${platform}`
);
if (!!automationProfile) {
return automationProfile;
}

const defaultProfile = terminalSettings.get<string>(`integrated.defaultProfile.${platform}`);
const profiles = terminalSettings.get<{ [prop: string]: ShellSetting }>(
`integrated.profiles.${platform}`
);

if (defaultProfile && profiles && profiles[defaultProfile]) {
return profiles[defaultProfile];
}

return terminalSettings.get(`integrated.shell.${platform}`);
}
}
30 changes: 30 additions & 0 deletions src/utils/evaluateCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { exec } from 'child_process';
import { getShellPath } from '../utils';
import { Logger } from '../helpers';

/**
* Evaluate the command dynamically using `which` command
* @param command
* @returns
*/
export const evaluateCommand = (command: string): Promise<string> => {
const shell = getShellPath();
let shellPath: string | undefined = undefined;
if (typeof shell !== 'string' && !!shell) {
shellPath = shell.path;
} else {
shellPath = shell || undefined;
}

return new Promise((resolve, reject) => {
exec(`which ${command}`, { shell: shellPath }, (error, stdout) => {
if (error) {
Logger.error(`Error evaluating command: ${command}`);
reject(error);
return;
}

resolve(stdout.trim());
});
});
};
36 changes: 36 additions & 0 deletions src/utils/getShellPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { workspace } from 'vscode';
import { ShellSetting } from '../models';
import { getPlatform } from './getPlatform';

/**
* Retrieves the shell path configuration based on the current platform and terminal settings.
*
* This method checks for the following configurations in order:
* 1. `integrated.automationProfile.<platform>`: Returns the automation profile if it exists.
* 2. `integrated.defaultProfile.<platform>` and `integrated.profiles.<platform>`: Returns the shell setting from the default profile if it exists.
* 3. `integrated.shell.<platform>`: Returns the shell setting if the above configurations are not found.
*
* @returns {string | ShellSetting | undefined} The shell path configuration or undefined if not found.
*/
export const getShellPath = (): string | ShellSetting | undefined => {
const platform = getPlatform();
const terminalSettings = workspace.getConfiguration('terminal');

const automationProfile = terminalSettings.get<string | ShellSetting>(
`integrated.automationProfile.${platform}`
);
if (!!automationProfile) {
return automationProfile;
}

const defaultProfile = terminalSettings.get<string>(`integrated.defaultProfile.${platform}`);
const profiles = terminalSettings.get<{ [prop: string]: ShellSetting }>(
`integrated.profiles.${platform}`
);

if (defaultProfile && profiles && profiles[defaultProfile]) {
return profiles[defaultProfile];
}

return terminalSettings.get(`integrated.shell.${platform}`);
};
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './cn';
export * from './copyFileAsync';
export * from './encodeEmoji';
export * from './evaluateCommand';
export * from './existsAsync';
export * from './fetchWithTimeout';
export * from './fieldWhenClause';
Expand All @@ -9,6 +10,7 @@ export * from './getDescriptionField';
export * from './getExtensibilityScripts';
export * from './getLocalizationFile';
export * from './getPlatform';
export * from './getShellPath';
export * from './getTitleField';
export * from './getWebviewJsFiles';
export * from './ignoreMsgCommand';
Expand Down

0 comments on commit f8f539b

Please sign in to comment.