@digigov/cli 1.1.2-daaf7bdf → 2.0.0-07ee8440

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,7 @@ $ npm install -g @digigov/cli
19
19
  $ digigov COMMAND
20
20
  running command...
21
21
  $ digigov (-v|--version|version)
22
- @digigov/cli/1.1.2-daaf7bdf linux-x64 node-v18.20.4
22
+ @digigov/cli/1.1.1 linux-x64 node-v18.20.3
23
23
  $ digigov --help [COMMAND]
24
24
  USAGE
25
25
  $ digigov COMMAND
package/index.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { DigigovCommand } from "./lib/command.js";
4
+ import { loadCommands } from "./load-commands.js";
5
+
6
+ const program = new DigigovCommand("digigov", import.meta.url);
7
+
8
+ await loadCommands(program);
9
+
10
+ await program.parseAsync(process.argv);
package/lib/command.js ADDED
@@ -0,0 +1,131 @@
1
+ import fs from "fs-extra";
2
+ import path from "path";
3
+ import * as execa from "execa";
4
+ import * as commander from "commander";
5
+ import { fileURLToPath } from "url";
6
+ import { logger } from "./logger.js";
7
+ import { findPackageJson } from "./project-utils.cjs";
8
+
9
+ /**
10
+ * A class that extends the Commander Command class with additional
11
+ * functionality.
12
+ *
13
+ * @extends commander.Command
14
+ */
15
+ export class DigigovCommand extends commander.Command {
16
+ /**
17
+ * The id of the command used for logging
18
+ * @type {string}
19
+ */
20
+ #id;
21
+ /** @type {string | null} */
22
+ context;
23
+
24
+ /**
25
+ * @constructor
26
+ * @param {string} name - The name of the command
27
+ * @param {string} [importMetaUrl] - The import.meta.url of the command
28
+ */
29
+ constructor(name, importMetaUrl) {
30
+ super(name);
31
+ this.#id = name;
32
+ this.context = importMetaUrl
33
+ ? path.dirname(fileURLToPath(importMetaUrl))
34
+ : null;
35
+
36
+ this.option("-d, --debug", "display debug information");
37
+
38
+ this.configureOutput({
39
+ writeErr: (str) => logger.error(str.replace(/^error: /i, "")),
40
+ });
41
+
42
+ if (this.context) {
43
+ if (this.context.endsWith("dist")) {
44
+ this.context = path.dirname(this.context);
45
+ }
46
+ const pkgPath = findPackageJson(this.context);
47
+ if (!pkgPath)
48
+ this.#throwError(`No package.json found in ${this.context}`);
49
+ const pkg = fs.readJSONSync(pkgPath);
50
+ this.description(pkg.description).version(pkg.version);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Display error message and exit
56
+ * @override
57
+ * @param {string} message - The message to log
58
+ * @param {commander.ErrorOptions} [errorOptions] - The error options
59
+ * @returns {never}
60
+ */
61
+ error(message, errorOptions) {
62
+ logger.error(message);
63
+ process.exit(errorOptions?.exitCode);
64
+ }
65
+
66
+ /**
67
+ * @override
68
+ * @param {(...args: any[]) => void | Promise<void>} fn - The function to run
69
+ * @returns {this} `this` command for chaining
70
+ */
71
+ action(fn) {
72
+ return super.action(async (...args) => {
73
+ try {
74
+ logger.time(`"${this.#id}" execution time`);
75
+ await fn(...args);
76
+ logger.timeEnd(`"${this.#id}" execution time`);
77
+ } catch (error) {
78
+ this.#throwError(error);
79
+ }
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Executes a script with the given arguments
85
+ *
86
+ * @param {string} script - The script to run
87
+ * @param {string[]} args - The arguments to pass to the script
88
+ * @param {execa.Options} [config] - The configuration for the script
89
+ */
90
+ exec(script, args, config) {
91
+ const __dirname =
92
+ this.context ?? path.dirname(fileURLToPath(import.meta.url));
93
+ const binLocation = [process.cwd(), __dirname].find((location) => {
94
+ return fs.existsSync(path.join(location, "node_modules", ".bin", script));
95
+ });
96
+ if (!binLocation || !fs.existsSync(binLocation)) {
97
+ this.#throwError(`Executable ${script} not installed`);
98
+ }
99
+ const executablePath = path.join(
100
+ binLocation,
101
+ "node_modules",
102
+ ".bin",
103
+ script,
104
+ );
105
+ const executableName = path.basename(executablePath);
106
+ logger.log(`Running: ${executableName} ${args.join(" ")}`);
107
+ try {
108
+ return execa.execa(executablePath, args, {
109
+ ...config,
110
+ stdio: "inherit",
111
+ });
112
+ } catch (error) {
113
+ this.#throwError(error);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * @param {unknown} error - The error to log
119
+ * @returns {never}
120
+ */
121
+ #throwError(error) {
122
+ if (typeof error === "string") logger.error(error);
123
+ if (typeof error === "object" && error) {
124
+ logger.error("stack" in error ? error.stack : error);
125
+ if ("exitCode" in error && typeof error.exitCode === "number") {
126
+ process.exit(error.exitCode);
127
+ }
128
+ }
129
+ process.exit(1);
130
+ }
131
+ }
package/lib/index.js CHANGED
@@ -1,5 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.run = void 0;
4
- var command_1 = require("@oclif/command");
5
- Object.defineProperty(exports, "run", { enumerable: true, get: function () { return command_1.run; } });
1
+ export * from "./command.js";
2
+ export * from "./project-utils.cjs";
3
+ export * from "./logger.js";
package/lib/logger.js ADDED
@@ -0,0 +1,72 @@
1
+ import chalk from "chalk";
2
+
3
+ const args = process.argv.slice(2);
4
+ const IS_DEBUG = args.includes("--debug") || args.includes("-d");
5
+
6
+ /**
7
+ * @param {any[]} data - The data to log
8
+ */
9
+ function log(...data) {
10
+ console.log(chalk.bgWhite.black(" LOG "), ...data);
11
+ }
12
+
13
+ /**
14
+ * @param {any[]} data - The data to log
15
+ */
16
+ function info(...data) {
17
+ console.log(chalk.bgBlue(" INFO "), chalk.blue(...data));
18
+ }
19
+
20
+ /**
21
+ * @param {any[]} data - The data to log
22
+ */
23
+ function error(...data) {
24
+ console.error(chalk.bgRed(" ERROR "), chalk.red(...data));
25
+ }
26
+
27
+ /**
28
+ * @param {any[]} data - The data to log
29
+ */
30
+ function success(...data) {
31
+ console.log("✅ ", chalk.green(...data));
32
+ }
33
+
34
+ /**
35
+ * @param {any[]} data - The data to log
36
+ */
37
+ function warn(...data) {
38
+ console.log(chalk.bgYellow.black(" WARN "), chalk.yellow(...data));
39
+ }
40
+
41
+ /**
42
+ * @param {any[]} data - The data to log
43
+ */
44
+ function debug(...data) {
45
+ if (IS_DEBUG)
46
+ console.log(chalk.dim.bgWhite.black(" DEBUG "), chalk.dim(...data));
47
+ }
48
+
49
+ /**
50
+ * @param {string} label - The label for the timer
51
+ */
52
+ function time(label) {
53
+ console.time(chalk.bgMagenta("⏱️ " + label));
54
+ }
55
+
56
+ /**
57
+ * @param {string} label - The label for the timer
58
+ */
59
+ function timeEnd(label) {
60
+ console.timeEnd(chalk.bgMagenta("⏱️ " + label));
61
+ }
62
+
63
+ export const logger = {
64
+ log,
65
+ info,
66
+ error,
67
+ success,
68
+ warn,
69
+ debug,
70
+ time,
71
+ timeEnd,
72
+ };
@@ -0,0 +1,260 @@
1
+ const fs = require("fs-extra");
2
+ const path = require("path");
3
+ const merge = require("deepmerge");
4
+ const rushLib = require("@microsoft/rush-lib");
5
+
6
+ /**
7
+ * Resolve the project configuration from the nearest package.json
8
+ *
9
+ * @param {string} [dir] - The directory to start package searching from
10
+ */
11
+ function resolveProject(dir) {
12
+ const pkg = findPackageJson(dir);
13
+ if (!pkg) throw new Error("No package.json found"); // TODO: reconsider this
14
+ const root = path.dirname(pkg);
15
+ let externalLockFile = false;
16
+ if (
17
+ fs.existsSync(path.join(root, "yarn.lock")) ||
18
+ fs.existsSync(path.join(root, "package-lock.json"))
19
+ ) {
20
+ externalLockFile = true;
21
+ }
22
+ let distDir = "dist";
23
+ let src = "src";
24
+
25
+ if (!fs.existsSync(path.join(root, src))) {
26
+ src = ".";
27
+ distDir = ".";
28
+ }
29
+ // project type heuristics
30
+ let isLib = false;
31
+ let isWorkspace = false;
32
+ let isApp = false;
33
+ let isDocs = false;
34
+
35
+ if (
36
+ fs.existsSync(path.join(root, "next.config.js")) ||
37
+ fs.existsSync(path.join(root, "pages"))
38
+ ) {
39
+ isApp = true;
40
+ }
41
+ if (
42
+ fs.existsSync(path.join(root, "docusaurus.config.js")) &&
43
+ fs.existsSync(path.join(root, "docs"))
44
+ ) {
45
+ isDocs = true;
46
+ }
47
+ if (fs.existsSync(path.join(root, "src")) && !isApp) {
48
+ isLib = true;
49
+ }
50
+
51
+ const rush = resolveWorkspace();
52
+ if (rush) isWorkspace = true;
53
+
54
+ const workspace = rush
55
+ ? {
56
+ config: rush,
57
+ root: rush.rushJsonFolder,
58
+ }
59
+ : {};
60
+
61
+ const isNodeLib = !isLib && !isApp && !isWorkspace && !isDocs;
62
+
63
+ /** @type {string | null} */
64
+ let ignore = path.resolve(root, ".gitignore");
65
+ if (!fs.existsSync(ignore) && workspace.root) {
66
+ ignore = path.resolve(workspace.root, ".gitignore");
67
+ }
68
+
69
+ if (!fs.existsSync(ignore)) {
70
+ ignore = null;
71
+ }
72
+
73
+ let digigov = {};
74
+ if (fs.existsSync(path.join(root, "digigovrc.json"))) {
75
+ digigov = fs.readJSONSync(path.join(root, "digigovrc.json"));
76
+ }
77
+ if (fs.existsSync(path.join(root, "digigovrc.js"))) {
78
+ digigov = require(path.join(root, "digigovrc.js"));
79
+ }
80
+
81
+ const packageJS = fs.readJSONSync(pkg);
82
+
83
+ const devDependencies = packageJS.devDependencies || {};
84
+ const dependencies = packageJS.dependencies || {};
85
+ const peerDependencies = packageJS.peerDependencies || {};
86
+ const isTs = Object.keys(devDependencies).includes("typescript");
87
+ const allDependencies = {
88
+ ...dependencies,
89
+ ...devDependencies,
90
+ ...peerDependencies,
91
+ };
92
+ // hook applies extra properties based on project type
93
+ return {
94
+ name: packageJS.name,
95
+ isTs,
96
+ isLib,
97
+ isApp,
98
+ isDocs,
99
+ isWorkspace,
100
+ isNodeLib,
101
+ distDir,
102
+ package: packageJS,
103
+ dependencies: allDependencies,
104
+ src,
105
+ root,
106
+ workspace,
107
+ ignore,
108
+ digigov,
109
+ externalLockFile,
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Recursively find the nearest package.json by walking up the directory tree.
115
+ *
116
+ * @param {string} startDir - The directory to start searching from
117
+ * @returns {string | undefined} package.json path, or undefined if not found.
118
+ */
119
+ function findPackageJson(startDir = process.cwd()) {
120
+ let currentDir = startDir;
121
+
122
+ if (!fs.existsSync(currentDir) || !fs.lstatSync(currentDir).isDirectory()) {
123
+ throw new Error(
124
+ `The start directory "${startDir}" is not a valid directory.`,
125
+ );
126
+ }
127
+
128
+ while (true) {
129
+ const packageJsonPath = path.join(currentDir, "package.json");
130
+ if (fs.existsSync(packageJsonPath)) {
131
+ return packageJsonPath;
132
+ }
133
+ const parentDir = path.resolve(currentDir, "..");
134
+ if (parentDir === currentDir) return undefined;
135
+
136
+ currentDir = parentDir;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Require a file relative to the project root
142
+ *
143
+ * @param {string} file - The file to require
144
+ */
145
+ function localRequire(file) {
146
+ const project = resolveProject();
147
+ const filePath = path.join(project.root, file);
148
+ if (!fs.existsSync(filePath)) return {};
149
+ if (file.endsWith(".json")) return fs.readJSONSync(filePath);
150
+ else return require(filePath);
151
+ }
152
+
153
+ function makeConfig(file, cfg = {}) {
154
+ let hook = {};
155
+ if (file && typeof file !== "string") {
156
+ hook = file;
157
+ } else if (typeof file === "string") {
158
+ hook = localRequire(file);
159
+ }
160
+ if (typeof hook === "function") {
161
+ return hook(cfg);
162
+ }
163
+ if (hook) {
164
+ return merge(cfg, hook);
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Resolve the project's Rush workspace configuration
170
+ *
171
+ * @returns {rushLib.RushConfiguration | null} - The Rush configuration or null if not found
172
+ */
173
+ function resolveWorkspace() {
174
+ try {
175
+ const rushConfiguration = rushLib.RushConfiguration.loadFromDefaultLocation(
176
+ {
177
+ startingFolder: process.cwd(),
178
+ },
179
+ );
180
+ return rushConfiguration;
181
+ } catch {
182
+ // No rush config, ignore error
183
+ }
184
+ return null;
185
+ }
186
+
187
+ /**
188
+ * @param {string[]} dependencies - The dependencies to resolve
189
+ * @returns {{ [key: string]: ReturnType<typeof resolveProject> }} - The local packages
190
+ */
191
+ function resolveLocalPackages(dependencies) {
192
+ const rush = resolveWorkspace();
193
+ /** @type {{ [key: string]: ReturnType<typeof resolveProject> }} */
194
+ let localPackages = {};
195
+ if (rush) {
196
+ const rushProjects = rush.projects;
197
+ for (const project of rushProjects) {
198
+ if (dependencies.includes(project.packageName)) {
199
+ localPackages[project.packageName] = resolveProject(
200
+ project.projectFolder,
201
+ );
202
+ }
203
+ }
204
+ }
205
+ return localPackages;
206
+ }
207
+ /**
208
+ * Map `resolveLocalPackages` result to a babel/jest compatible package aliases
209
+ * object. Use only packages which are declared as a dependency for the current
210
+ * project
211
+ *
212
+ * @param {boolean} absolute=false - Whether to return absolute paths
213
+ * @returns {{ [key: string]: string }} - The aliases object
214
+ *
215
+ */
216
+ function aliases(absolute = false) {
217
+ /** @type {{ [key: string]: string }} */
218
+ const aliases = {};
219
+ const project = resolveProject();
220
+ const depKeys = ["dependencies", "peerDependencies", "devDependencies"];
221
+ const root = project.root;
222
+ /** @type {string[]} */
223
+ let deps = [];
224
+ for (const key of depKeys) {
225
+ deps = deps.concat(Object.keys(project.package[key] || {}));
226
+ }
227
+ const packages = resolveLocalPackages(deps);
228
+ Object.keys(packages).forEach((key) => {
229
+ const project = packages[key];
230
+ if (
231
+ project &&
232
+ deps.includes(project.name) &&
233
+ project.package.devDependencies &&
234
+ project.package.devDependencies["@digigov/cli-build"] &&
235
+ project.isWorkspace
236
+ ) {
237
+ const projectSrc = path.join(project.root, project.src);
238
+ if (absolute) {
239
+ aliases[project.name] = path.resolve(root, projectSrc);
240
+ } else {
241
+ aliases[project.name] = projectSrc;
242
+ }
243
+ }
244
+ });
245
+ if (absolute) {
246
+ aliases[project.name] = path.resolve(root, project.src);
247
+ } else {
248
+ aliases[project.name] = project.src;
249
+ }
250
+ return aliases;
251
+ }
252
+
253
+ module.exports = {
254
+ resolveProject,
255
+ findPackageJson,
256
+ resolveWorkspace,
257
+ resolveLocalPackages,
258
+ aliases,
259
+ makeConfig,
260
+ };
@@ -0,0 +1,49 @@
1
+ import fs from "fs-extra";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { logger } from "./lib/index.js";
5
+ import { DigigovCommand, findPackageJson } from "./lib/index.js";
6
+
7
+ /**
8
+ * @param {DigigovCommand} program - The program to load commands into
9
+ */
10
+ export async function loadCommands(program) {
11
+ const packageFilePath = findPackageJson();
12
+ if (!packageFilePath) {
13
+ logger.warn("No package.json found");
14
+ return;
15
+ }
16
+ const packageFile = fs.readFileSync(packageFilePath);
17
+
18
+ const { dependencies, devDependencies } = JSON.parse(packageFile.toString());
19
+ const commandPackages = Object.keys({
20
+ ...dependencies,
21
+ ...devDependencies,
22
+ }).filter((p) => p.match(/@digigov\/cli-.*?/));
23
+ for (const commandPackage of commandPackages) {
24
+ try {
25
+ const modulePath = path.resolve(
26
+ process.cwd(),
27
+ "node_modules",
28
+ commandPackage,
29
+ "index.js",
30
+ );
31
+ const realPath = fs.realpathSync(modulePath);
32
+ const command = await import(
33
+ fileURLToPath(new URL(`file://${realPath}`))
34
+ );
35
+ program.addCommand(command.default);
36
+ } catch (error) {
37
+ const errorPrefix = `Could not load command package: ${commandPackage}`;
38
+ if (
39
+ error instanceof Error &&
40
+ error.message.endsWith("undefined (reading '_name')")
41
+ )
42
+ logger.warn(
43
+ errorPrefix,
44
+ "| Did you forget to default export the command?",
45
+ );
46
+ else logger.warn(errorPrefix, error);
47
+ }
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,74 +1,46 @@
1
1
  {
2
2
  "name": "@digigov/cli",
3
3
  "description": "CLI for Digigov apps and libs with plugin support",
4
- "version": "1.1.2-daaf7bdf",
4
+ "version": "2.0.0-07ee8440",
5
5
  "author": "GRNET Devs <devs@lists.grnet.gr>",
6
+ "type": "module",
6
7
  "bin": {
7
- "digigov": "./bin/run"
8
+ "digigov": "./index.js"
8
9
  },
9
10
  "dependencies": {
10
- "@oclif/command": "1.8.0",
11
- "@oclif/config": "1",
12
- "@oclif/plugin-help": "3",
13
- "tslib": "2.6.2",
14
- "cli-ux": "5.5.1",
15
- "@oclif/errors": "1.3.4",
16
- "pkg-up": "3.1.0",
17
11
  "fs-extra": "11.2.0",
18
- "deepmerge": "4.2.2",
19
- "execa": "5.0.0",
20
- "rimraf": "3.0.2",
21
- "glob": "7.1.6",
22
- "publint": "0.1.8"
12
+ "deepmerge": "4.3.1",
13
+ "execa": "8.0.1",
14
+ "@microsoft/rush-lib": "5.133.4",
15
+ "commander": "12.1.0",
16
+ "chalk": "4.1.0"
23
17
  },
24
18
  "devDependencies": {
25
- "@oclif/dev-cli": "1",
26
- "@oclif/test": "1",
27
- "@types/chai": "4",
28
- "@types/mocha": "5",
29
- "@types/node": "18.19.0",
30
- "chai": "4",
31
- "globby": "11.0.0",
32
- "mocha": "5",
33
- "nyc": "14",
34
- "ts-node": "10.9.2",
35
- "typescript": "5.6.2",
36
19
  "publint": "0.1.8",
37
- "@microsoft/rush-lib": "5.133.4"
20
+ "typescript": "5.6.2",
21
+ "@types/fs-extra": "11.0.4",
22
+ "@types/node": "18.19.0"
38
23
  },
39
24
  "engines": {
40
- "node": ">=12.13.0"
25
+ "node": ">=18"
41
26
  },
42
27
  "files": [
43
- "/bin",
28
+ "index.js",
29
+ "load-commands.js",
44
30
  "/lib",
45
- "/lib.js",
46
- "/resolveProject.js",
47
- "/npm-shrinkwrap.json",
48
- "/oclif.manifest.json"
49
- ],
50
- "homepage": "https://github.com/tooling/cli",
51
- "keywords": [
52
- "oclif"
31
+ "tsconfig.cli.json"
53
32
  ],
54
- "main": "lib/index.js",
55
- "oclif": {
56
- "commands": "./lib/commands",
57
- "bin": "digigov",
58
- "plugins": [
59
- "@oclif/plugin-help"
60
- ],
61
- "hooks": {
62
- "init": "./lib/hooks/init/addcommand"
63
- }
33
+ "main": "./index.js",
34
+ "exports": {
35
+ ".": "./index.js",
36
+ "./lib": {
37
+ "require": "./lib/project-utils.cjs",
38
+ "default": "./lib/index.js"
39
+ },
40
+ "./tsconfig.cli": "./tsconfig.cli.json"
64
41
  },
65
- "types": "lib/index.d.ts",
66
42
  "scripts": {
67
43
  "publint": "publint",
68
- "lint": "echo 'no lint needed (yet)'",
69
- "prepublish": "tsc",
70
- "test": "nyc --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
71
- "version": "oclif-dev readme && git add README.md",
72
- "build": "tsc"
44
+ "lint": "echo 'no lint needed (yet)'"
73
45
  }
74
46
  }
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "NodeNext",
4
+ "moduleResolution": "NodeNext",
5
+ "noEmit": true,
6
+ "allowJs": true,
7
+ "checkJs": true,
8
+ "strict": true,
9
+ "allowSyntheticDefaultImports": true,
10
+ "skipLibCheck": true,
11
+ "resolveJsonModule": true,
12
+ "esModuleInterop": true,
13
+ "forceConsistentCasingInFileNames": true,
14
+ "noImplicitReturns": true,
15
+ "noImplicitThis": true,
16
+ "noImplicitAny": false,
17
+ "strictNullChecks": true,
18
+ "noUnusedLocals": true,
19
+ "noUnusedParameters": true,
20
+ "strictFunctionTypes": true,
21
+ "strictBindCallApply": true,
22
+ "strictPropertyInitialization": true,
23
+ "alwaysStrict": true,
24
+ "noFallthroughCasesInSwitch": true,
25
+ "noUncheckedIndexedAccess": true,
26
+ "noPropertyAccessFromIndexSignature": true,
27
+ "skipDefaultLibCheck": true
28
+ }
29
+ }
package/bin/run DELETED
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- require('@oclif/command').run()
4
- .then(require('@oclif/command/flush'))
5
- .catch(require('@oclif/errors/handle'))
package/bin/run.cmd DELETED
@@ -1,3 +0,0 @@
1
- @echo off
2
-
3
- node "%~dp0\run" %*
@@ -1,9 +0,0 @@
1
- import { Command } from '@oclif/command';
2
- export default class Hello extends Command {
3
- static description: string;
4
- static examples: string[];
5
- static args: {
6
- name: string;
7
- }[];
8
- run(): Promise<void>;
9
- }
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const command_1 = require("@oclif/command");
4
- class Hello extends command_1.Command {
5
- async run() {
6
- var _a;
7
- const { args, flags } = this.parse(Hello);
8
- const name = (_a = flags.name) !== null && _a !== void 0 ? _a : 'world';
9
- this.log(`hello ${name} from ./src/commands/hello.ts`);
10
- if (args.file && flags.force) {
11
- this.log(`you input --force and --file: ${args.file}`);
12
- }
13
- }
14
- }
15
- Hello.description = 'describe the command here';
16
- Hello.examples = [
17
- `$ digigov hello
18
- hello world from ./src/hello.ts!
19
- `,
20
- ];
21
- Hello.args = [{ name: 'file' }];
22
- exports.default = Hello;
@@ -1,2 +0,0 @@
1
- declare const hook: (this: any) => Promise<void>;
2
- export default hook;
@@ -1,27 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- // @ts-nocheck
4
- const Config = require("@oclif/config");
5
- const pkgUp = require("pkg-up");
6
- const fs = require('fs');
7
- const packageFile = pkgUp.sync();
8
- const { dependencies, devDependencies } = JSON.parse(fs.readFileSync(packageFile).toString());
9
- const plugins = Object.keys(Object.assign(Object.assign({}, dependencies), devDependencies)).filter(p => p.match(/@digigov\/cli-.*?/));
10
- class DynamicPlugin extends Config.Plugin {
11
- get hooks() { return {}; }
12
- get topics() {
13
- return [];
14
- }
15
- get commandIDs() {
16
- return plugins.map(p => p.match(/@digigov\/cli-(.*?)$/)[1]);
17
- }
18
- get commands() {
19
- return plugins.map(plugin => {
20
- return require(plugin);
21
- });
22
- }
23
- }
24
- const hook = async function () {
25
- this.config.plugins.push(new DynamicPlugin(this.config));
26
- };
27
- exports.default = hook;
package/lib/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export { run } from '@oclif/command';
package/lib.js DELETED
@@ -1,45 +0,0 @@
1
- const fs = require("fs-extra");
2
- const path = require("path");
3
- const execa = require("execa");
4
- const glob = require("glob");
5
- const { Command } = require("@oclif/command");
6
- const {
7
- makeConfig,
8
- resolveLocalPackages,
9
- aliases,
10
- resolveProject,
11
- resolveWorkspace,
12
- extractCommandArgs
13
- } = require("./resolveProject");
14
-
15
-
16
- class DigigovCommand extends Command {
17
- async exec(script, args, config) {
18
- const binLocation = [process.cwd(), this.dirname, __dirname].find(
19
- (location) => {
20
- return fs.existsSync(
21
- path.join(location, "node_modules", ".bin", script),
22
- );
23
- },
24
- );
25
- if (!binLocation || !fs.existsSync(binLocation)) {
26
- throw new Error(`Executable ${script} not installed`);
27
- }
28
- let executable = path.join(binLocation, "node_modules", ".bin", script);
29
- console.log("Running ", executable, ...args);
30
- try {
31
- return await execa(executable, args, { ...config, stdio: "inherit" });
32
- } catch (err) {
33
- process.exit(err.exitCode);
34
- }
35
- }
36
- }
37
- module.exports = {
38
- makeConfig,
39
- resolveLocalPackages,
40
- aliases,
41
- DigigovCommand,
42
- resolveProject,
43
- resolveWorkspace,
44
- extractCommandArgs,
45
- };
@@ -1 +0,0 @@
1
- {"version":"1.1.2-daaf7bdf","commands":{"hello":{"id":"hello","description":"describe the command here","pluginName":"@digigov/cli","pluginType":"core","aliases":[],"examples":["$ digigov hello\nhello world from ./src/hello.ts!\n"],"flags":{},"args":[{"name":"file"}]}}}
package/resolveProject.js DELETED
@@ -1,217 +0,0 @@
1
- const pkgUp = require("pkg-up");
2
- const fs = require("fs-extra");
3
- const path = require("path");
4
- const merge = require("deepmerge");
5
-
6
- function resolveProject(dir) {
7
- const pkg = pkgUp.sync({ cwd: dir || process.cwd() });
8
- const root = path.dirname(pkg);
9
- let externalLockFile = false;
10
- if (fs.existsSync(path.join(root, "yarn.lock")) ||
11
- fs.existsSync(path.join(root, "package-lock.json"))) {
12
- externalLockFile = true;
13
- }
14
- let distDir = "dist";
15
- let src = "src";
16
- let workspace = {};
17
- if (!fs.existsSync(path.join(root, src))) {
18
- src = ".";
19
- distDir = ".";
20
- }
21
- // project type heuristics
22
- let isLib = false;
23
- let isWorkspace = false;
24
- let isApp = false;
25
- let isDocs = false;
26
-
27
- if (fs.existsSync(path.join(root, "next.config.js")) ||
28
- fs.existsSync(path.join(root, "pages"))) {
29
- isApp = true;
30
- }
31
- if (fs.existsSync(path.join(root, "docusaurus.config.js")) &&
32
- fs.existsSync(path.join(root, "docs"))) {
33
- isDocs = true;
34
- }
35
- if (fs.existsSync(path.join(root, "src")) && !isApp) {
36
- isLib = true;
37
- }
38
-
39
- const rush = resolveWorkspace();
40
- if (rush) {
41
- isWorkspace = true;
42
- workspace = {
43
- config: rush,
44
- root: rush.rushJsonFolder,
45
- };
46
- }
47
-
48
- const isNodeLib = !isLib && !isApp && !isWorkspace && !isDocs;
49
-
50
- let ignore = path.resolve(root, ".gitignore");
51
- if (!fs.existsSync(ignore) && workspace.root) {
52
- ignore = path.resolve(workspace.root, ".gitignore");
53
- }
54
-
55
- if (!fs.existsSync(ignore)) {
56
- ignore = null;
57
- }
58
-
59
- let digigov = {};
60
- if (fs.existsSync(path.join(root, "digigovrc.json"))) {
61
- digigov = require(path.join(root, "digigovrc.json"));
62
- }
63
- if (fs.existsSync(path.join(root, "digigovrc.js"))) {
64
- digigov = require(path.join(root, "digigovrc.js"));
65
- }
66
-
67
- const packageJS = require(pkg);
68
-
69
- const devDependencies = packageJS.devDependencies || {};
70
- const dependencies = packageJS.dependencies || {};
71
- const peerDependencies = packageJS.peerDependencies || {};
72
- const isTs = Object.keys(devDependencies).includes("typescript");
73
- const allDependencies = {
74
- ...dependencies,
75
- ...devDependencies,
76
- ...peerDependencies,
77
- };
78
- // hook applies extra properties based on project type
79
- return {
80
- name: packageJS.name,
81
- isTs,
82
- isLib,
83
- isApp,
84
- isDocs,
85
- isWorkspace,
86
- isNodeLib,
87
- distDir,
88
- package: packageJS,
89
- dependencies: allDependencies,
90
- src,
91
- root,
92
- workspace,
93
- ignore,
94
- digigov,
95
- externalLockFile,
96
- };
97
- }
98
- function localRequire(file, dflt) {
99
- const project = resolveProject();
100
- const filePath = path.join(project.root, file);
101
- if (fs.existsSync(filePath)) {
102
- return require(filePath);
103
- }
104
- return dflt;
105
- }
106
- function makeConfig(file, cfg) {
107
- let hook = {};
108
- if (file && typeof file !== "string") {
109
- hook = file;
110
- } else if (typeof file === "string") {
111
- hook = localRequire(file, {});
112
- }
113
- if (typeof hook === "function") {
114
- return hook(cfg);
115
- }
116
- if (hook) {
117
- return merge(cfg, hook);
118
- }
119
- }
120
- function resolveWorkspace(dir) {
121
- try {
122
- const rushLib = require("@microsoft/rush-lib");
123
- const rushConfiguration = rushLib.RushConfiguration.loadFromDefaultLocation(
124
- {
125
- startingFolder: process.cwd(),
126
- }
127
- );
128
- return rushConfiguration;
129
- } catch (err) {
130
- // console.log(err);
131
- }
132
- }
133
- /*
134
- Identify if project running the command from, is lerna-enabled. If so, return
135
- lerna registered projects metadata.
136
- */
137
- function resolveLocalPackages(dir, dependencies) {
138
- const packages = {};
139
- const rush = resolveWorkspace(dir);
140
- if (rush) {
141
- rush.projects.forEach((p) => {
142
- if (dependencies.includes(p.packageName)) {
143
- packages[p.packageName] = resolveProject(p.projectFolder);
144
- }
145
- });
146
- return packages;
147
- }
148
- return {};
149
- }
150
- /**
151
- * Map `resolveLocalPackages` result to a babel/jest compatible package aliases
152
- * object. Use only packages which are declared as a dependency for the current
153
- * project
154
- */
155
- function aliases(dir, absolute = false) {
156
- const aliases = {};
157
- const project = resolveProject(dir);
158
- const depKeys = ["dependencies", "peerDependencies", "devDependencies"];
159
- const root = project.root;
160
- const deps = depKeys.reduce((deps, key) => {
161
- return deps.concat(Object.keys(project.package[key] || {}));
162
- }, []);
163
- const packages = resolveLocalPackages(project.root, deps);
164
- Object.keys(packages).forEach((key) => {
165
- const project = packages[key];
166
- if (deps.includes(project.name) &&
167
- project.package.devDependencies &&
168
- project.package.devDependencies["@digigov/cli-build"] &&
169
- project.isWorkspace) {
170
- const projectSrc = path.join(project.root, project.src);
171
- if (absolute) {
172
- aliases[project.name] = path.resolve(root, projectSrc);
173
- } else {
174
- aliases[project.name] = projectSrc;
175
- }
176
- }
177
- });
178
- if (absolute) {
179
- aliases[project.name] = path.resolve(root, project.src);
180
- } else {
181
- aliases[project.name] = project.src;
182
- }
183
- return aliases;
184
- }
185
- const extractCommandArgs = (config, commandArgs) => {
186
- const vars = Object.values(args).reduce((values, v) => {
187
- return {
188
- ...values,
189
- ...(v.default && { [v.var]: v.default }),
190
- };
191
- }, {});
192
-
193
- const exclude = [];
194
- commandArgs.forEach((arg, idx) => {
195
- if (exclude.includes(idx)) {
196
- return;
197
- }
198
- if (args[arg]) {
199
- if (args[arg].type) {
200
- vars[args[arg].var] = args[arg].type(commandArgs[idx + 1]);
201
- exclude.push(idx + 1);
202
- } else {
203
- vars[args[arg].var] = true;
204
- }
205
- }
206
- });
207
- return vars;
208
- };
209
-
210
- module.exports = {
211
- makeConfig,
212
- resolveLocalPackages,
213
- aliases,
214
- resolveProject,
215
- resolveWorkspace,
216
- extractCommandArgs,
217
- };