Skip to content

Commit

Permalink
feature(cli): added rhtml cli
Browse files Browse the repository at this point in the history
  • Loading branch information
Stradivario committed Mar 5, 2024
1 parent 2c80ddd commit eed807d
Show file tree
Hide file tree
Showing 16 changed files with 944 additions and 17 deletions.
20 changes: 12 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,24 @@
"author": "Kristiyan Tachev",
"license": "MIT",
"devDependencies": {
"@types/jest": "^24.0.18",
"husky": "^3.0.9",
"@rhtml/di": "^0.0.128",
"@rxdi/bolt": "^0.24.3",
"typescript": "^5.3.3",
"@types/jest": "^24.0.18",
"@types/node": "^20.11.24",
"@typescript-eslint/eslint-plugin": "^7.1.1",
"@typescript-eslint/parser": "^7.1.1",
"eslint": "^8.47.0",
"eslint-config-prettier": "^6.7.0",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-simple-import-sort": "^5.0.0",
"@typescript-eslint/eslint-plugin": "^7.1.1",
"@typescript-eslint/parser": "^7.1.1",
"husky": "^3.0.9",
"jest": "^24.9.0",
"prettier": "^2.0.5",
"ts-jest": "25.2.1",
"@rhtml/di": "^0.0.128",
"jest": "^24.9.0"
"typescript": "^5.3.3",
"@rhtml/schematics": "^0.0.128",
"commander": "8.2.0",
"esbuild": "0.20.1"
},
"browserslist": [
"last 1 chrome versions"
Expand All @@ -57,4 +61,4 @@
"dependencies": {
"fastify": "^4.25.1"
}
}
}
1 change: 1 addition & 0 deletions packages/cli/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
28 changes: 28 additions & 0 deletions packages/cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
BSD 3-Clause License

Copyright (c) 2019, Reactive Solutions LTD 205455032. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 changes: 47 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# @rhtml/cli

#### Installation

```bash
npm i @rhtml/cli -g
```

#### Usage

##### Generate schematic can be 'module', 'controller', 'service'

```bash
rhtml generate --name test --type module
```

##### General Help

```bash
Usage: rhtml [options] [command]

Options:
-V, --version output the version number
-h, --help display help for command

Commands:
generate [options] Generate specific schematic
help [command] display help for command
```

##### Generate Help

```bash
Usage: rhtml generate [options]

Generate specific schematic

Options:
-n, --name <name> Name of the generated schematic
-t, --type <type> Specify type name can be one of the followings "controller", "module", "service"
-f, --force Force create schematics even with errors
--language <language> Language can be ts or js
--folder <folder> Choose folder where schematics will be generated default is src/app
--dry-run Dry run the command to see if the folder structure will be correct
--spec Whether or not to create .spec tests when creating schematics
-h, --help display help for command
```
15 changes: 15 additions & 0 deletions packages/cli/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

require('esbuild')
.build({
entryPoints: ['./src/main.ts'],
bundle: true,
minify: true,
platform: 'node',
target: 'node14.4',
outfile: './dist/index.js',
})
.then((data) => console.log('SUCCESS', data))
.catch((e) => {
console.error(e);
process.exit(1);
});
16 changes: 16 additions & 0 deletions packages/cli/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = {
testEnvironment: 'node',
testPathIgnorePatterns: ['/node_modules/'],
coverageReporters: ['lcov', 'html'],
rootDir: './',
moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'node'],
globals: {
__DEV__: true
},
transform: {
'\\.(ts|tsx)$': 'ts-jest'
},
testRegex: '/src/.*\\.spec.(ts|tsx|js)$',
verbose: true,
collectCoverage: true
};
46 changes: 46 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@rhtml/cli",
"version": "0.0.2",
"description": "Rhtml CLI tool",
"scripts": {
"start": "npx gapi start --local --path=./example/main.ts",
"patch": "npm run build && npm version patch && npm publish --update-readme --access public && npm run delete-dist",
"delete-dist": "rm -rf dist",
"clean": "git clean -dxf",
"test": "echo 'no tests specified'",
"lint": "npx eslint . --ext .ts",
"lint-fix": "npx eslint . --fix --ext .ts",
"build:tsc": "rm -rf dist && tsc",
"build:release": "gapi build --single-executable",
"build": "node build.js"
},
"repository": {
"type": "git",
"url": "[email protected]:r-html/rhtml.git"
},
"dependencies": {},
"devDependencies": {
"@types/jest": "^24.0.18",
"@rhtml/schematics": "^0.0.128",
"jest": "^24.9.0",
"ts-jest": "25.2.1",
"typescript": "^5.3.3",
"commander": "8.2.0",
"esbuild": "0.20.1"
},
"author": "Kristiyan Tachev",
"license": "MIT",
"browserslist": [
"last 1 chrome versions"
],
"files": [
"dist"
],
"bin": {
"rhtml": "./dist/index.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"module": "./dist/index.js",
"typings": "./dist/index.d.ts"
}
34 changes: 34 additions & 0 deletions packages/cli/src/commands/generate/abstract.runner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { ChildProcess, spawn, SpawnOptions } from 'child_process';

export class AbstractRunner {
constructor(protected binary: string) {}

public async run(
command: string,
collect = false,
cwd: string = process.cwd()
): Promise<null | string> {
const args: string[] = [command];
const options: SpawnOptions = {
cwd,
stdio: collect ? 'pipe' : 'inherit',
shell: true,
};
return new Promise<null | string>((resolve, reject) => {
const child: ChildProcess = spawn(this.binary, args, options);
if (collect) {
child.stdout!.on('data', (data) =>
resolve(data.toString().replace(/\r\n|\n/, ''))
);
}
child.on('close', (code) => {
if (code === 0) {
resolve(null);
} else {
console.error(`${this.binary} ${command}`);
reject();
}
});
});
}
}
21 changes: 21 additions & 0 deletions packages/cli/src/commands/generate/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { AbstractRunner } from './abstract.runner';
import { GenerateOptions } from './types';

export default (options: GenerateOptions) => {
const {
dryRun = false,
folder = 'src/app',
force = false,
internalArguments = '',
language = 'ts',
name = 'app',
schematicsName = '@rhtml/schematics',
spec = false,
type = 'module',
} = options;
return new AbstractRunner('npx schematics').run(
`${schematicsName}:${type} --name=${name} --force=${force} --dryRun=${dryRun} ${
spec ? '--spec' : ''
} --language='${language}' --sourceRoot='${folder}' ${internalArguments}`
);
};
29 changes: 29 additions & 0 deletions packages/cli/src/commands/generate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Command } from 'commander';

import { lazy } from '../../helpers';

export function registerGenerateCommands(program: Command) {
program
.command('generate')
.description('Generate specific schematic')
.option('-n, --name <name>', 'Name of the generated schematic')
.option(
'-t, --type <type>',
'Specify type name can be one of the followings "controller", "module", "service"'
)
.option('-f, --force', 'Force create schematics even with errors')
.option('--language <language>', 'Language can be ts or js')
.option(
'--folder <folder>',
'Choose folder where schematics will be generated default is src/app'
)
.option(
'--dry-run',
'Dry run the command to see if the folder structure will be correct'
)
.option(
'--spec',
'Whether or not to create .spec tests when creating schematics'
)
.action(lazy(() => import('./generate').then((m) => m.default)));
}
11 changes: 11 additions & 0 deletions packages/cli/src/commands/generate/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface GenerateOptions {
schematicsName: string;
type: string;
name: string;
force: boolean;
dryRun: boolean;
spec: boolean;
language: string;
folder: string;
internalArguments: string;
}
3 changes: 3 additions & 0 deletions packages/cli/src/commands/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { registerGenerateCommands } from './generate';

export const commands = [registerGenerateCommands];
45 changes: 45 additions & 0 deletions packages/cli/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import chalk from 'chalk';

export class CustomError extends Error {
get name(): string {
return this.constructor.name;
}
}

export class ExitCodeError extends CustomError {
readonly code: number;

constructor(code: number, command?: string) {
if (command) {
super(`Command '${command}' exited with code ${code}`);
} else {
super(`Child exited with code ${code}`);
}
this.code = code;
}
}

export function exitWithError(error: Error): never {
if (error instanceof ExitCodeError) {
process.stderr.write(`\n${chalk.red(error.message)}\n\n`);
process.exit(error.code);
} else {
process.stderr.write(`\n${chalk.red(`${error}`)}\n\n`);
process.exit(1);
}
}
export function lazy(
getActionFunc: () => Promise<(...args: any[]) => Promise<unknown>>
): (...args: any[]) => Promise<void> {
return async (...args: any[]) => {
try {
const actionFunc = await getActionFunc();
await actionFunc(...args);

process.exit(0);
} catch (error) {
exitWithError(error);
}
};
}
28 changes: 28 additions & 0 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#! /usr/bin/env node

import { program } from 'commander';

import { commands } from './commands';

export const main = (argv: string[]) => {
program.name('rhtml').version('0.0.1');

commands.map((command) => command(program));

program.on('command:*', () => {
console.log();
console.log(`Invalid command: ${program.args.join(' ')}`);
console.log();
program.outputHelp();
process.exit(1);
});

program.parse(argv);
};

/* If command is executed without arguments show help page */
if (process.argv.length === 2) {
process.argv.push('-h');
}

main(process.argv);
Loading

0 comments on commit eed807d

Please sign in to comment.