Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { logger } from '../core/logger.js';

export function build(cwd: string) {
logger.success(`🔨 ${new Date().toLocaleTimeString()} Project building started`);
const configuration = getTSConfig(cwd, args.getArg('project'));
const configuration = getTSConfig(cwd, args['project']);

const result = buildTypescriptFiles(configuration);

Expand All @@ -18,4 +18,4 @@ export function build(cwd: string) {

logger.success(`✅ ${new Date().toLocaleTimeString()} Project building finished`);
process.exit(0);
}
}
2 changes: 1 addition & 1 deletion src/commands/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { watchNonTypescriptFiles, watchTypescriptFiles } from '../core/build.js'
import { getTSConfig } from '../core/config.js';

export function watch(cwd: string) {
const configuration = getTSConfig(cwd, args.getArg('project'));
const configuration = getTSConfig(cwd, args['project']);
watchTypescriptFiles(configuration);
watchNonTypescriptFiles(configuration);
}
64 changes: 18 additions & 46 deletions src/core/args.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,24 @@
export enum ArgsFlags {
INCLUDE_NON_TS_FILES = 'include-non-ts-files',
RETAIN_IMPORTS_AS_COMMENTS = 'retain-imports-as-comments',
RETAIN_NON_ASCII_CHARACTERS = 'retain-non-ascii-characters',
}
import { parseArgs } from "node:util";

export class ArgsParser {
#command: string = '';
#argv: string[] = [];
class ArgsParser {
command: string = '';
args: Record<string, any> = {} ;

constructor() {
this.#parse();
}

getArg(argName: string) {
const argumentsList = process.argv.slice(2);

for (let i = 0; i < argumentsList.length; i++) {
const argument = argumentsList[i];

if (!argument.startsWith(`--${argName}`)) {
continue;
}

if (argument === `--${argName}`) {
const nextArgument = argumentsList[i + 1];
return nextArgument?.startsWith('--') ? undefined : nextArgument;
}

if (argument.startsWith(`--${argName}=`)) {
return argument.slice(argName.length + 3);
}
}

return undefined;
}

getCommand() {
return this.#command;
}

has(argumentName: ArgsFlags) {
return this.#argv.includes(argumentName);
}

#parse() {
this.#command = process.argv.slice(2)[0];
this.#argv = process.argv.slice(3).filter((x: string) => x.startsWith('--')).map((x: string) => x.slice(2));
const { values: args, positionals: [command] } = parseArgs({
options: {
help: { type: 'boolean', short: 'h', default: false },
version: { type: 'boolean', short: 'v', default: false },
project: { type: 'string', short: 'p', default: 'tsconfig.json' },
'include-non-ts-files': { type: 'boolean', default: false },
'retain-imports-as-comments': { type: 'boolean', default: false },
'retain-non-ascii-characters': { type: 'boolean', default: false },
},
allowPositionals: true
});
this.command = command || '';
this.args = args;
}
}

export const args = new ArgsParser();
export const { args, command } = new ArgsParser();
31 changes: 23 additions & 8 deletions src/core/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { removeExports } from '../transformers/remove_exports.js';
import { convertTemplateStrings } from '../transformers/template_strings.js';
import { transformNamespaces } from '../transformers/transform_namespaces.js';
import { noDeclarationInLoop } from '../checks/no-declaration-in-loop.js';
import { args, ArgsFlags } from './args.js';
import { args } from './args.js';
import { logger } from './logger.js';

export function buildTypescriptFiles(configuration: ts.ParsedCommandLine) {
Expand Down Expand Up @@ -93,7 +93,7 @@ function decorateHostWriteFile(host: ts.CompilerHost) {
fileName = fileName.replace('.js', '.html');
}

if (!args.has(ArgsFlags.RETAIN_NON_ASCII_CHARACTERS)) {
if (!args['retain-non-ascii-characters']) {
// Decode non ASCII characters
data = data.replace(/\\u[\dA-Fa-f]{4}/g, (match) => {
return String.fromCharCode(parseInt(match.substr(2), 16));
Expand Down Expand Up @@ -148,15 +148,16 @@ export function watchTypescriptFiles(configuration: ts.ParsedCommandLine) {
}

export function watchNonTypescriptFiles(configuration: ts.ParsedCommandLine) {
if (!args.has(ArgsFlags.INCLUDE_NON_TS_FILES)) {
if (!args['include-non-ts-files']) {
return;
}

const { rootDir, outDir } = configuration.options;
const sourceRootPath = getSourceRootPath(configuration);
const { outDir } = configuration.options;
const entries = collectNonTypescriptFiles(configuration);

entries.forEach((x: string) => {
const filePath = rootDir ? relative(rootDir, x) : x;
const filePath = relative(sourceRootPath, x);
const outputFilePath = resolve(outDir!, filePath);

fs.watch(resolve(x), (event: fs.WatchEventType) => {
Expand All @@ -170,17 +171,31 @@ export function watchNonTypescriptFiles(configuration: ts.ParsedCommandLine) {
}

export function buildNonTypescriptFiles(configuration: ts.ParsedCommandLine) {
if (!args.has(ArgsFlags.INCLUDE_NON_TS_FILES)) {
if (!args['include-non-ts-files']) {
return;
}

const { rootDir, outDir } = configuration.options;
const sourceRootPath = getSourceRootPath(configuration);
const { outDir } = configuration.options;
const entries = collectNonTypescriptFiles(configuration);

entries.forEach((x: string) => {
const filePath = rootDir ? relative(rootDir, x) : x;
const filePath = relative(sourceRootPath, x);
const outputFilePath = resolve(outDir!, filePath);
fs.mkdirSync(dirname(outputFilePath), { recursive: true });
fs.writeFileSync(outputFilePath, fs.readFileSync(resolve(x), 'utf-8'));
});
}

function getSourceRootPath(configuration: ts.ParsedCommandLine) {
const configFilePath = typeof configuration.options.configFilePath === 'string'
? configuration.options.configFilePath
: resolve('tsconfig.json');
const configDirectoryPath = dirname(configFilePath);

if (typeof configuration.options.rootDir === 'string') {
return resolve(configDirectoryPath, configuration.options.rootDir);
}

return configDirectoryPath;
}
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#!/usr/bin/env node

import { args } from './core/args.js';
import * as args from './core/args.js';
import { commands } from './commands/index.js';
import { help } from './commands/help.js';

const cwd = process.cwd();

const command = commands.get(args.getCommand());
const command = commands.get(args.command);

if (command) {
command.callback(cwd);
Expand Down
4 changes: 2 additions & 2 deletions src/transformers/remove_exports.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ts from 'typescript';

import { args, ArgsFlags } from '../core/args.js';
import { args } from '../core/args.js';

export function removeExports(): ts.TransformerFactory<ts.SourceFile> {
return (context) => (sourceFile: ts.SourceFile) => {
Expand Down Expand Up @@ -30,7 +30,7 @@ export function removeExports(): ts.TransformerFactory<ts.SourceFile> {
}

if (ts.isImportDeclaration(node)) {
if (args.has(ArgsFlags.RETAIN_IMPORTS_AS_COMMENTS)) {
if (args['retain-imports-as-comments']) {
const commentedStatement = ts.factory.createNotEmittedStatement(node);
ts.addSyntheticLeadingComment(
commentedStatement,
Expand Down
94 changes: 94 additions & 0 deletions test/commands/build-args.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { match, ok, strictEqual } from 'node:assert';
import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
import { suite, test } from 'node:test';

const fixturePath = resolve(import.meta.dirname, 'build_args_fixture');
const cliEntryPath = resolve(import.meta.dirname, '..', '..', 'dist', 'index.js');

function createProject(t) {
const tempRootPath = mkdtempSync(join(tmpdir(), 'wshcmx-build-args-'));
const projectPath = join(tempRootPath, 'project');
cpSync(fixturePath, projectPath, { recursive: true });
t.after(() => rmSync(tempRootPath, { recursive: true, force: true }));
return projectPath;
}

function runBuild(projectPath, cliArgs = []) {
execFileSync(process.execPath, [cliEntryPath, 'build', ...cliArgs], {
cwd: projectPath,
stdio: 'pipe',
});
}

function getBuiltIndexPath(projectPath, outputDirectoryName) {
const candidatePaths = [
join(projectPath, outputDirectoryName, 'index.bs'),
join(projectPath, outputDirectoryName, 'index.js'),
join(projectPath, outputDirectoryName, 'src', 'index.bs'),
join(projectPath, outputDirectoryName, 'src', 'index.js'),
];

return candidatePaths.find((candidatePath) => existsSync(candidatePath)) ?? candidatePaths[0];
}

function hasBuiltIndex(projectPath, outputDirectoryName) {
return getBuiltIndexPath(projectPath, outputDirectoryName) !== join(projectPath, outputDirectoryName, 'index.bs')
|| existsSync(join(projectPath, outputDirectoryName, 'index.bs'));
}

suite('build command arguments', () => {
test('--project and -p select the tsconfig used for the build', (t) => {
const longOptionProjectPath = createProject(t);
const shortOptionProjectPath = createProject(t);

runBuild(longOptionProjectPath, ['--project', 'configs\\tsconfig.custom.json']);
runBuild(shortOptionProjectPath, ['-p', 'configs\\tsconfig.custom.json']);

ok(hasBuiltIndex(longOptionProjectPath, 'dist-custom'));
ok(hasBuiltIndex(shortOptionProjectPath, 'dist-custom'));
strictEqual(hasBuiltIndex(longOptionProjectPath, 'dist-default'), false);
strictEqual(hasBuiltIndex(shortOptionProjectPath, 'dist-default'), false);
});

test('--include-non-ts-files copies non-TypeScript assets into the output', (t) => {
const withoutFlagProjectPath = createProject(t);
const withFlagProjectPath = createProject(t);

runBuild(withoutFlagProjectPath);
runBuild(withFlagProjectPath, ['--include-non-ts-files']);

strictEqual(existsSync(join(withoutFlagProjectPath, 'dist-default', 'src', 'template.xml')), false);
ok(existsSync(join(withFlagProjectPath, 'dist-default', 'src', 'template.xml')));
});

test('--retain-imports-as-comments preserves imports as commented lines in the emitted file', (t) => {
const withoutFlagProjectPath = createProject(t);
const withFlagProjectPath = createProject(t);

runBuild(withoutFlagProjectPath);
runBuild(withFlagProjectPath, ['--retain-imports-as-comments']);

const withoutFlagOutput = readFileSync(getBuiltIndexPath(withoutFlagProjectPath, 'dist-default'), 'utf-8');
const withFlagOutput = readFileSync(getBuiltIndexPath(withFlagProjectPath, 'dist-default'), 'utf-8');

strictEqual(withoutFlagOutput.includes("import { value } from './submodule';"), false);
ok(withFlagOutput.includes("// import { value } from './submodule';"));
});

test('--retain-non-ascii-characters keeps unicode escapes in emitted output', (t) => {
const withoutFlagProjectPath = createProject(t);
const withFlagProjectPath = createProject(t);

runBuild(withoutFlagProjectPath);
runBuild(withFlagProjectPath, ['--retain-non-ascii-characters']);

const withoutFlagOutput = readFileSync(getBuiltIndexPath(withoutFlagProjectPath, 'dist-default'), 'utf-8');
const withFlagOutput = readFileSync(getBuiltIndexPath(withFlagProjectPath, 'dist-default'), 'utf-8');

ok(withoutFlagOutput.includes('Результат: '));
match(withFlagOutput, /\\u0420\\u0435\\u0437\\u0443\\u043b\\u044c\\u0442\\u0430\\u0442: /i);
});
});
11 changes: 11 additions & 0 deletions test/commands/build_args_fixture/configs/tsconfig.custom.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"rootDir": "../src",
"target": "esnext",
"module": "Preserve",
"outDir": "../dist-custom"
},
"include": [
"../src/**/*"
]
}
11 changes: 11 additions & 0 deletions test/commands/build_args_fixture/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { value } from './submodule';

export namespace Module {
export function method(a: number, b: number): string {
return `Результат: ${a + b}`;
}
}

export function readValue() {
return value;
}
1 change: 1 addition & 0 deletions test/commands/build_args_fixture/src/submodule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const value = 'submodule value';
3 changes: 3 additions & 0 deletions test/commands/build_args_fixture/src/template.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<name>builder-args</name>
</template>
10 changes: 10 additions & 0 deletions test/commands/build_args_fixture/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "esnext",
"module": "Preserve",
"outDir": "dist-default"
},
"include": [
"src/**/*"
]
}
Loading
Loading