Skip to content

Commit

Permalink
326 add aliases (#734)
Browse files Browse the repository at this point in the history
  • Loading branch information
katherinejensen00 authored Jan 30, 2024
2 parents 2f77330 + ad99875 commit dd0539c
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 73 deletions.
13 changes: 6 additions & 7 deletions src/extension-host/global-this.model.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
/** Module to set up globalThis and polyfills in the extension host */
/** Module to set up globalThis and polyfills in the extension host */

import { LogLevel } from 'electron-log';
import polyfillLocalStorage from '@node/polyfills/local-storage.polyfill';
import {
ARG_LOG_LEVEL,
ARG_PACKAGED,
ARG_RESOURCES_PATH,
COMMAND_LINE_ARGS,
getCommandLineArgument,
getCommandLineSwitch,
} from '@node/utils/command-line.util';
import { ProcessType } from '@shared/global-this.model';

// #region command-line arguments

const isPackaged = getCommandLineSwitch(ARG_PACKAGED);
const resourcesPath = getCommandLineArgument(ARG_RESOURCES_PATH) ?? 'resources://';
const isPackaged = getCommandLineSwitch(COMMAND_LINE_ARGS.Packaged);
const resourcesPath = getCommandLineArgument(COMMAND_LINE_ARGS.ResourcesPath) ?? 'resources://';
const logLevel =
// Assert the extracted type.
// eslint-disable-next-line no-type-assertion/no-type-assertion
(getCommandLineArgument(ARG_LOG_LEVEL) as LogLevel) ?? (isPackaged ? 'error' : 'info');
(getCommandLineArgument(COMMAND_LINE_ARGS.LogLevel) as LogLevel) ??
(isPackaged ? 'error' : 'info');

// #endregion

Expand Down
14 changes: 5 additions & 9 deletions src/extension-host/services/extension.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ import { getModuleSimilarApiMessage } from '@shared/utils/util';
import Module from 'module';
import * as SillsdevScripture from '@sillsdev/scripture';
import logger from '@shared/services/logger.service';
import {
ARG_EXTENSION_DIRS,
ARG_EXTENSIONS,
getCommandLineArgumentsGroup,
} from '@node/utils/command-line.util';
import { getCommandLineArgumentsGroup, COMMAND_LINE_ARGS } from '@node/utils/command-line.util';
import { setExtensionUris } from '@extension-host/services/extension-storage.service';
import papi, { fetch as papiFetch } from '@extension-host/services/papi-backend.service';
import executionTokenService from '@node/services/execution-token.service';
Expand Down Expand Up @@ -142,17 +138,17 @@ function parseManifest(extensionManifestJson: string): ExtensionManifest {
* - In production: `resources/extensions`
*/
const extensionRootDirectories: Uri[] = [
...getCommandLineArgumentsGroup(ARG_EXTENSION_DIRS).map(
...getCommandLineArgumentsGroup(COMMAND_LINE_ARGS.ExtensionsDir).map(
(extensionDirPath) => `${FILE_PROTOCOL}${path.resolve(extensionDirPath)}`,
),
installedExtensionsUri,
`resources://extensions${globalThis.isPackaged ? '' : '/dist'}`,
];

/** Individual extension folders and/or zips to load as provided by command-line `--extensions` */
const commandLineExtensionDirectories: string[] = getCommandLineArgumentsGroup(ARG_EXTENSIONS).map(
(extensionPath) => `${FILE_PROTOCOL}${path.resolve(extensionPath)}`,
);
const commandLineExtensionDirectories: string[] = getCommandLineArgumentsGroup(
COMMAND_LINE_ARGS.Extensions,
).map((extensionPath) => `${FILE_PROTOCOL}${path.resolve(extensionPath)}`);

/**
* Contents of `nodeFS.readDir()` for all parent folders of extensions. This is expected to be a
Expand Down
5 changes: 3 additions & 2 deletions src/main/global-this.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import path from 'path';
import polyfillLocalStorage from '@node/polyfills/local-storage.polyfill';
import { ProcessType } from '@shared/global-this.model';
import { app } from 'electron';
import { ARG_LOG_LEVEL, getCommandLineArgument } from '@node/utils/command-line.util';
import { getCommandLineArgument, COMMAND_LINE_ARGS } from '@node/utils/command-line.util';
import { LogLevel } from 'electron-log';

// #region globalThis setup
Expand All @@ -22,7 +22,8 @@ globalThis.resourcesPath = app.isPackaged ? process.resourcesPath : path.join(__
globalThis.logLevel =
// Assert the extracted type.
// eslint-disable-next-line no-type-assertion/no-type-assertion
(getCommandLineArgument(ARG_LOG_LEVEL) as LogLevel) ?? (globalThis.isPackaged ? 'info' : 'debug');
(getCommandLineArgument(COMMAND_LINE_ARGS.LogLevel) as LogLevel) ??
(globalThis.isPackaged ? 'info' : 'debug');

// #endregion

Expand Down
19 changes: 8 additions & 11 deletions src/main/services/extension-host.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
/** Service that runs the extension-host process from the main file */
/** Service that runs the extension-host process from the main file */

import {
ARG_EXTENSION_DIRS,
ARG_EXTENSIONS,
ARG_LOG_LEVEL,
ARG_PACKAGED,
ARG_RESOURCES_PATH,
getCommandLineArgumentsGroup,
COMMAND_LINE_ARGS,
commandLineArgumentsAliases,
} from '@node/utils/command-line.util';
import logger, { formatLog, WARN_TAG } from '@shared/services/logger.service';
import { waitForDuration } from 'platform-bible-utils';
Expand Down Expand Up @@ -66,8 +63,8 @@ function killExtensionHost() {
function getCommandLineArgumentsToForward() {
// Pass through the relevant command-line arguments to the extension host
return [
...getCommandLineArgumentsGroup(ARG_EXTENSIONS, true),
...getCommandLineArgumentsGroup(ARG_EXTENSION_DIRS, true),
...getCommandLineArgumentsGroup(COMMAND_LINE_ARGS.Extensions, true),
...getCommandLineArgumentsGroup(COMMAND_LINE_ARGS.ExtensionsDir, true),
];
}

Expand All @@ -79,17 +76,17 @@ async function startExtensionHost() {
// In development, spawn nodemon to watch the extension-host
/** Arguments that will be passed to the extension host no matter how we start the process */
const sharedArgs = [
ARG_RESOURCES_PATH,
commandLineArgumentsAliases[COMMAND_LINE_ARGS.ResourcesPath][0],
globalThis.resourcesPath,
ARG_LOG_LEVEL,
commandLineArgumentsAliases[COMMAND_LINE_ARGS.LogLevel][0],
globalThis.logLevel,
...getCommandLineArgumentsToForward(),
];

if (app.isPackaged) {
extensionHost = fork(
path.join(__dirname, '../extension-host/extension-host.js'),
[ARG_PACKAGED, ...sharedArgs],
[commandLineArgumentsAliases[COMMAND_LINE_ARGS.Packaged][0], ...sharedArgs],
{
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
},
Expand Down
115 changes: 71 additions & 44 deletions src/node/utils/command-line.util.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
/** Command-line argument that specifies extra individual extension folders */
export const ARG_EXTENSIONS = '--extensions';
/** All command line arguments mapped from argument type to array of aliases for the argument */
type CommandLineArgumentAliases = {
[argument in COMMAND_LINE_ARGS]: string[];
};

/**
* Command-line argument that specifies extra extension directories in which to check all contained
* folders for extensions
* Command Line Arguments
*
* - Extensions - Command-line argument that specifies extra individual extension folders
* - ExtensionsDir - Command-line argument that specifies extra extension directories in which to
* check all contained folders for extensions
* - LogLevel - Command-line argument that specifies log level to use Options: 'error' | 'warn' |
* 'info' | 'verbose' | 'debug'
* - ResourcesPath - Command-line argument that specifies the path to the resources folder
* - Packaged - Command-line switch that specifies if the application is packaged. Only on
* extension-host
*/
export const ARG_EXTENSION_DIRS = '--extensionDirs';
export enum COMMAND_LINE_ARGS {
Extensions = 'extensions',
ExtensionsDir = 'extensions_dir',
LogLevel = 'log_level',
ResourcesPath = 'resources_path',
Packaged = 'packaged',
}

/**
* Command-line argument that specifies log level to use
*
* Options: 'error' | 'warn' | 'info' | 'verbose' | 'debug' | 'silly'
*
* @see module:electron-log#LogLevel for up-to-date options
* Aliases for each command line argument mapped from argument type to an array of aliases for that
* argument type
*/
export const ARG_LOG_LEVEL = '--logLevel';

/** Command-line argument that specifies the path to the resources folder */
export const ARG_RESOURCES_PATH = '--resourcesPath';

/** Command-line switch that specifies if the application is packaged. Only on extension-host */
export const ARG_PACKAGED = '--packaged';
export const commandLineArgumentsAliases: CommandLineArgumentAliases = {
[COMMAND_LINE_ARGS.Extensions]: ['--extensions', '--extension', '-e'],
[COMMAND_LINE_ARGS.ExtensionsDir]: ['--extensionDirs', '--extensionDir', '-d'],
[COMMAND_LINE_ARGS.LogLevel]: ['--logLevels', '--logLevel', '-l'],
[COMMAND_LINE_ARGS.ResourcesPath]: ['--resourcesPath', '--resourcePath', '-r'],
[COMMAND_LINE_ARGS.Packaged]: ['--packaged', '--isPackaged', '-p'],
};

/** Get the index of the next command-line argument after the startIndex */
export function findNextCommandLineArgumentIndex(currentArgIndex: number) {
Expand All @@ -36,7 +50,7 @@ export function findNextCommandLineArgumentIndex(currentArgIndex: number) {
* Get a command-line argument's group of arguments. If no arguments are in its group, return
* nothing
*
* @param argName Name of the command-line argument to search for
* @param argName Name(s) of the command-line argument to search for
* @param shouldIncludeArgName Whether to include `argName` at the start of the returned array
* @returns Array of strings of the command-line args in this command-line argument group
*
Expand All @@ -55,47 +69,59 @@ export function findNextCommandLineArgumentIndex(currentArgIndex: number) {
* - `getCommandLineArgumentsGroup('--things')` returns `[]`
* - `getCommandLineArgumentsGroup('--things', true)` returns `[]`
*/
export function getCommandLineArgumentsGroup(argName: string, shouldIncludeArgName = false) {
// TODO: If argName has two hyphens, check for single hyphen and first char + capitals if
// two-hyphen version does not exist. eg --extensionDirs -> -ed
const argIndex = process.argv.indexOf(argName);
export function getCommandLineArgumentsGroup(
argName: COMMAND_LINE_ARGS,
shouldIncludeArgName = false,
): string[] {
const argNames: string[] = commandLineArgumentsAliases[argName];

if (argIndex < 0) return [];
const argumentsGroup: string[] = [];
argNames
.filter((n) => process.argv.indexOf(n) > 0)
.forEach((arg) => {
const argIndex = process.argv.indexOf(arg);
const baseArray = shouldIncludeArgName ? [arg] : [];

const baseArray = shouldIncludeArgName ? [argName] : [];
argumentsGroup.concat(
process.argv.length > argIndex + 1
? [
...baseArray,
...process.argv.slice(argIndex + 1, findNextCommandLineArgumentIndex(argIndex)),
]
: baseArray,
);
});

return process.argv.length > argIndex + 1
? [
...baseArray,
...process.argv.slice(argIndex + 1, findNextCommandLineArgumentIndex(argIndex)),
]
: baseArray;
return argumentsGroup;
}

/**
* Get a command-line argument's argument. If the argument is not present, return `undefined`
*
* @param argName Name of the command-line argument to search for
* @param argName Name and aliases of the command-line argument to search for
* @returns String of the command-line arg provided
*
* Ex: '--thing ben'
*
* - `getCommandLineArgument('--thing')` returns `'ben'`
*/
export function getCommandLineArgument(argName: string) {
export function getCommandLineArgument(argName: COMMAND_LINE_ARGS) {
// TODO: If argName has two hyphens, check for single hyphen and first char + capitals if
// two-hyphen version does not exist. eg --extensionDirs -> -ed
const argIndex = process.argv.indexOf(argName);
const argNames: string[] = commandLineArgumentsAliases[argName];
const argIndices: number[] = argNames.map((name) => process.argv.indexOf(name));

const argIndex = argIndices.find(
(index) =>
// Will be negative if not found
index >= 0 &&
// Ensuring it is not the last argument (the arg name was found, but there is no actual argument provided)
index < process.argv.length - 1 &&
// If the next word is also an arg name, there was no actual argument provided
findNextCommandLineArgumentIndex(index) !== index + 1,
);

if (
// Not found
argIndex < 0 ||
// Last argument (the arg name was found, but there is no actual argument provided)
argIndex >= process.argv.length - 1 ||
// If the next word is also an arg name, there was no actual argument provided
findNextCommandLineArgumentIndex(argIndex) === argIndex + 1
)
return undefined;
if (argIndex === undefined) return undefined;

return process.argv[argIndex + 1];
}
Expand All @@ -112,6 +138,7 @@ export function getCommandLineArgument(argName: string) {
*
* - `getCommandLineSwitch('--thing')` returns `true`
*/
export function getCommandLineSwitch(argName: string) {
return process.argv.includes(argName);
export function getCommandLineSwitch(argName: COMMAND_LINE_ARGS) {
const argNames: string[] = commandLineArgumentsAliases[argName];
return argNames.some((alias) => process.argv.includes(alias));
}

0 comments on commit dd0539c

Please sign in to comment.