yargs-file-commands 0.0.10 → 0.0.12
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/CHANGELOG.md +32 -0
- package/dist/lib/fileCommands.js +5 -0
- package/dist/lib/importCommand.js +5 -0
- package/package.json +6 -3
- package/src/index.ts +1 -0
- package/src/lib/Command.ts +14 -0
- package/src/lib/buildSegmentTree.test.ts +90 -0
- package/src/lib/buildSegmentTree.ts +145 -0
- package/src/lib/fileCommands.test.ts +57 -0
- package/src/lib/fileCommands.ts +133 -0
- package/src/lib/fixtures/commands/db/health.ts +9 -0
- package/src/lib/fixtures/commands/db/migration/command.ts +12 -0
- package/src/lib/importCommand.test.ts +48 -0
- package/src/lib/importCommand.ts +122 -0
- package/src/lib/scanDirectory.test.ts +75 -0
- package/src/lib/scanDirectory.ts +109 -0
- package/src/lib/segmentPath.test.ts +71 -0
- package/src/lib/segmentPath.ts +38 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# yargs-file-commands
|
|
2
|
+
|
|
3
|
+
## 0.0.12
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- More explicit exceptions when bad parameters are passed in
|
|
8
|
+
- More robust parameter checking and logging
|
|
9
|
+
- Improved debugging logging
|
|
10
|
+
- More robust debug messages
|
|
11
|
+
|
|
12
|
+
## 0.0.11
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- More explicit exceptions when bad parameters are passed in
|
|
17
|
+
- Improved debugging logging
|
|
18
|
+
- More robust debug messages
|
|
19
|
+
|
|
20
|
+
## 0.0.10
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- Improved debugging logging
|
|
25
|
+
- More robust debug messages
|
|
26
|
+
|
|
27
|
+
## 0.0.9
|
|
28
|
+
|
|
29
|
+
### Patch Changes
|
|
30
|
+
|
|
31
|
+
- Improved debugging logging
|
|
32
|
+
- More robust debug messages
|
package/dist/lib/fileCommands.js
CHANGED
|
@@ -60,9 +60,14 @@ export const fileCommands = async (options) => {
|
|
|
60
60
|
const fullPath = path.resolve(commandDir);
|
|
61
61
|
console.debug(`Scanning directory for commands: ${fullPath}`);
|
|
62
62
|
const filePaths = await scanDirectory(commandDir, commandDir, fullOptions);
|
|
63
|
+
console.debug(`Importing found commands:`);
|
|
63
64
|
for (const filePath of filePaths) {
|
|
65
|
+
const localPath = path.relative(commandDir, filePath);
|
|
64
66
|
const segments = segmentPath(filePath, commandDir);
|
|
65
67
|
segments.pop(); // remove extension.
|
|
68
|
+
if (fullOptions.logLevel === 'debug') {
|
|
69
|
+
console.debug(` ${localPath} - importing command module`);
|
|
70
|
+
}
|
|
66
71
|
commands.push({
|
|
67
72
|
fullPath: filePath,
|
|
68
73
|
segments,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
1
2
|
import {} from 'yargs';
|
|
2
3
|
/**
|
|
3
4
|
* Imports a command module from a file
|
|
@@ -11,6 +12,10 @@ import {} from 'yargs';
|
|
|
11
12
|
* If no handler is provided, creates a null implementation.
|
|
12
13
|
*/
|
|
13
14
|
export const importCommandFromFile = async (filePath, name, options) => {
|
|
15
|
+
// ensure file exists using fs node library
|
|
16
|
+
if (fs.existsSync(filePath) === false) {
|
|
17
|
+
throw new Error(`Can not import command from non-existence file path: ${filePath}`);
|
|
18
|
+
}
|
|
14
19
|
const handlerModule = (await import(filePath));
|
|
15
20
|
const { logLevel = 'info' } = options;
|
|
16
21
|
const command = {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "yargs-file-commands",
|
|
3
3
|
"description": "A yargs helper function that lets you define your commands structure via directory and file naming conventions.",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.12",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -29,9 +29,11 @@
|
|
|
29
29
|
},
|
|
30
30
|
"files": [
|
|
31
31
|
"dist",
|
|
32
|
+
"src",
|
|
32
33
|
"package.json",
|
|
33
34
|
"README.md",
|
|
34
|
-
"LICENSE"
|
|
35
|
+
"LICENSE",
|
|
36
|
+
"CHANGELOG.md"
|
|
35
37
|
],
|
|
36
38
|
"peerDependencies": {
|
|
37
39
|
"yargs": "^17"
|
|
@@ -53,6 +55,7 @@
|
|
|
53
55
|
"typecheck": "tsc --noEmit",
|
|
54
56
|
"test": "tsc && node --test dist/**/*.test.js --test-concurrency=1",
|
|
55
57
|
"lint": "eslint --fix \"src/**/*.{ts,tsx}\"",
|
|
56
|
-
"format": "prettier \"src/**/*.{js,jsx,css,md,html,ts,tsx,json,yaml}\" --check"
|
|
58
|
+
"format": "prettier \"src/**/*.{js,jsx,css,md,html,ts,tsx,json,yaml}\" --check",
|
|
59
|
+
"prePublishOnly": "pnpm build && pnpm test"
|
|
57
60
|
}
|
|
58
61
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './lib/fileCommands.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CommandModule } from 'yargs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Represents a command structure with its file path and module information
|
|
5
|
+
* @interface Command
|
|
6
|
+
*/
|
|
7
|
+
export interface Command {
|
|
8
|
+
/** Full file system path to the command file */
|
|
9
|
+
fullPath: string;
|
|
10
|
+
/** Array of path segments representing the command hierarchy */
|
|
11
|
+
segments: string[];
|
|
12
|
+
/** The Yargs command module implementation */
|
|
13
|
+
commandModule: CommandModule;
|
|
14
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { describe, it } from 'node:test';
|
|
3
|
+
|
|
4
|
+
import { buildSegmentTree } from './buildSegmentTree.js';
|
|
5
|
+
import type { Command } from './Command.js';
|
|
6
|
+
|
|
7
|
+
describe('buildSegmentTree', async () => {
|
|
8
|
+
it('should build correct tree structure', () => {
|
|
9
|
+
const commands: Command[] = [
|
|
10
|
+
{
|
|
11
|
+
fullPath: '/commands/db/migration/command.js',
|
|
12
|
+
segments: ['db', 'migration'],
|
|
13
|
+
commandModule: {
|
|
14
|
+
command: 'migration',
|
|
15
|
+
describe: 'Migration command',
|
|
16
|
+
handler: async () => {
|
|
17
|
+
// Test handler
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
fullPath: '/commands/db/health.js',
|
|
23
|
+
segments: ['db', 'health'],
|
|
24
|
+
commandModule: {
|
|
25
|
+
command: 'health',
|
|
26
|
+
describe: 'Health command',
|
|
27
|
+
handler: async () => {
|
|
28
|
+
// Test handler
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const tree = buildSegmentTree(commands);
|
|
35
|
+
|
|
36
|
+
assert.equal(tree.length, 1, 'Should have one root node');
|
|
37
|
+
const rootNode = tree[0];
|
|
38
|
+
assert(rootNode, 'Root node should exist');
|
|
39
|
+
assert.equal(rootNode.segmentName, 'db', 'Root node should be "db"');
|
|
40
|
+
assert.equal(
|
|
41
|
+
rootNode.type,
|
|
42
|
+
'internal',
|
|
43
|
+
'Root node should be internal type'
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
if (rootNode.type !== 'internal') {
|
|
47
|
+
throw new Error('Expected internal node');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
assert.equal(rootNode.children.length, 2, 'Should have two child nodes');
|
|
51
|
+
|
|
52
|
+
const childSegments = rootNode.children
|
|
53
|
+
.map((child) => child.segmentName)
|
|
54
|
+
.sort();
|
|
55
|
+
assert.deepEqual(
|
|
56
|
+
childSegments,
|
|
57
|
+
['health', 'migration'],
|
|
58
|
+
'Should have "health" and "migration" sub-commands'
|
|
59
|
+
);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('should handle empty input', () => {
|
|
63
|
+
const tree = buildSegmentTree([]);
|
|
64
|
+
assert.equal(tree.length, 0, 'Should return empty array for empty input');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should handle single command', () => {
|
|
68
|
+
const commands: Command[] = [
|
|
69
|
+
{
|
|
70
|
+
fullPath: '/commands/test.ts',
|
|
71
|
+
segments: ['test'],
|
|
72
|
+
commandModule: {
|
|
73
|
+
command: 'test',
|
|
74
|
+
describe: 'Test command',
|
|
75
|
+
handler: async () => {
|
|
76
|
+
// Test handler
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
const tree = buildSegmentTree(commands);
|
|
83
|
+
|
|
84
|
+
assert.equal(tree.length, 1, 'Should have one node');
|
|
85
|
+
const node = tree[0];
|
|
86
|
+
assert(node, 'Node should exist');
|
|
87
|
+
assert.equal(node.segmentName, 'test', 'Should have correct segment');
|
|
88
|
+
assert.equal(node.type, 'leaf', 'Should be a leaf node');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type { Argv, CommandModule } from 'yargs';
|
|
2
|
+
|
|
3
|
+
import type { Command } from './Command';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Represents a node in the command tree structure
|
|
7
|
+
* @type {CommandTreeNode}
|
|
8
|
+
*/
|
|
9
|
+
type CommandTreeNode = {
|
|
10
|
+
/** Name of the command segment */
|
|
11
|
+
segmentName: string;
|
|
12
|
+
} & (
|
|
13
|
+
| {
|
|
14
|
+
/** Internal node type with children */
|
|
15
|
+
type: 'internal';
|
|
16
|
+
/** Child command nodes */
|
|
17
|
+
children: CommandTreeNode[];
|
|
18
|
+
}
|
|
19
|
+
| {
|
|
20
|
+
/** Leaf node type with command implementation */
|
|
21
|
+
type: 'leaf';
|
|
22
|
+
/** The command implementation */
|
|
23
|
+
command: Command;
|
|
24
|
+
}
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Builds a tree structure from command definitions
|
|
29
|
+
* @param {Command[]} commands - Array of command definitions
|
|
30
|
+
* @returns {CommandTreeNode[]} Root nodes of the command tree
|
|
31
|
+
*
|
|
32
|
+
* @description
|
|
33
|
+
* Constructs a hierarchical tree structure from flat command definitions,
|
|
34
|
+
* preserving the command hierarchy defined by the file system structure.
|
|
35
|
+
*/
|
|
36
|
+
export const buildSegmentTree = (commands: Command[]): CommandTreeNode[] => {
|
|
37
|
+
const rootTreeNodes: CommandTreeNode[] = [];
|
|
38
|
+
|
|
39
|
+
for (const command of commands) {
|
|
40
|
+
insertIntoTree(rootTreeNodes, command, 0);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return rootTreeNodes;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Inserts a command into the tree structure at the specified depth
|
|
48
|
+
* @param {CommandTreeNode[]} treeNodes - Current level tree nodes
|
|
49
|
+
* @param {Command} command - Command to insert
|
|
50
|
+
* @param {number} depth - Current depth in the segment tree
|
|
51
|
+
* @throws {Error} When there's a conflict between directory and command names
|
|
52
|
+
*/
|
|
53
|
+
function insertIntoTree(
|
|
54
|
+
treeNodes: CommandTreeNode[],
|
|
55
|
+
command: Command,
|
|
56
|
+
depth: number
|
|
57
|
+
): void {
|
|
58
|
+
// If we've processed all segments, we shouldn't be here
|
|
59
|
+
if (depth >= command.segments.length) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const currentSegmentName = command.segments[depth]!;
|
|
64
|
+
let currentSegment = treeNodes.find(
|
|
65
|
+
(s) => s.segmentName === currentSegmentName
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
// If this is the last segment, create a leaf node
|
|
69
|
+
if (depth === command.segments.length - 1) {
|
|
70
|
+
if (currentSegment == null) {
|
|
71
|
+
treeNodes.push({
|
|
72
|
+
type: 'leaf',
|
|
73
|
+
segmentName: currentSegmentName,
|
|
74
|
+
command
|
|
75
|
+
});
|
|
76
|
+
} else if (currentSegment.type === 'internal') {
|
|
77
|
+
throw new Error(
|
|
78
|
+
`Conflict: ${currentSegmentName} is both a directory and a command`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Creating or ensuring we have an internal node
|
|
85
|
+
if (currentSegment == null) {
|
|
86
|
+
currentSegment = {
|
|
87
|
+
type: 'internal',
|
|
88
|
+
segmentName: currentSegmentName,
|
|
89
|
+
children: []
|
|
90
|
+
};
|
|
91
|
+
treeNodes.push(currentSegment);
|
|
92
|
+
} else if (currentSegment.type === 'leaf') {
|
|
93
|
+
throw new Error(
|
|
94
|
+
`Conflict: ${currentSegmentName} is both a directory and a command`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Recurse into children
|
|
99
|
+
insertIntoTree(currentSegment.children, command, depth + 1);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Creates a Yargs command module from a tree node
|
|
104
|
+
* @param {CommandTreeNode} treeNode - The tree node to convert
|
|
105
|
+
* @returns {CommandModule} Yargs command module
|
|
106
|
+
*
|
|
107
|
+
* @description
|
|
108
|
+
* Recursively converts a tree node into a Yargs command module.
|
|
109
|
+
* For leaf nodes, returns the actual command implementation.
|
|
110
|
+
* For internal nodes, creates a parent command that manages subcommands.
|
|
111
|
+
*/
|
|
112
|
+
export const createCommand = (treeNode: CommandTreeNode): CommandModule => {
|
|
113
|
+
if (treeNode.type === 'leaf') {
|
|
114
|
+
return treeNode.command.commandModule;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const name = treeNode.segmentName;
|
|
118
|
+
// For internal nodes, create a command that registers all children
|
|
119
|
+
const command: CommandModule = {
|
|
120
|
+
command: name,
|
|
121
|
+
describe: `${name} commands`,
|
|
122
|
+
builder: (yargs: Argv): Argv => {
|
|
123
|
+
// Register all child segments as subcommands
|
|
124
|
+
yargs.command(treeNode.children.map((child) => createCommand(child)));
|
|
125
|
+
// Demand a subcommand unless we're at the root
|
|
126
|
+
yargs.demandCommand(1, `You must specify a ${name} subcommand`);
|
|
127
|
+
|
|
128
|
+
return yargs;
|
|
129
|
+
},
|
|
130
|
+
handler: async () => {
|
|
131
|
+
// Internal nodes don't need handlers as they'll demand subcommands
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return command;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
export const logCommandTree = (commands: CommandTreeNode[], level = 0) => {
|
|
139
|
+
commands.forEach((command) => {
|
|
140
|
+
console.debug(`${' '.repeat(level) + command.segmentName}`);
|
|
141
|
+
if (command.type === 'internal') {
|
|
142
|
+
logCommandTree(command.children, level + 1);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { describe, it } from 'node:test';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
import type { CommandModule } from 'yargs';
|
|
7
|
+
import yargs from 'yargs';
|
|
8
|
+
import { hideBin } from 'yargs/helpers';
|
|
9
|
+
|
|
10
|
+
import { fileCommands } from '../lib/fileCommands.js';
|
|
11
|
+
|
|
12
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
13
|
+
|
|
14
|
+
describe('fileCommands', async () => {
|
|
15
|
+
await it('should load commands from directory structure', async () => {
|
|
16
|
+
const commandsDir = path.join(__dirname, 'fixtures', 'commands');
|
|
17
|
+
const commands = await fileCommands({
|
|
18
|
+
commandDirs: [commandsDir],
|
|
19
|
+
extensions: ['.js'],
|
|
20
|
+
logLevel: 'debug'
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
assert.equal(commands.length, 1, 'Should have one root command');
|
|
24
|
+
const rootCommand = commands[0] as CommandModule;
|
|
25
|
+
assert(rootCommand, 'Root command should exist');
|
|
26
|
+
assert.equal(rootCommand.command, 'db', 'Root command should be "db"');
|
|
27
|
+
|
|
28
|
+
// Create a new yargs instance
|
|
29
|
+
const yargsInstance = yargs(hideBin(process.argv));
|
|
30
|
+
|
|
31
|
+
if (typeof rootCommand.builder === 'function') {
|
|
32
|
+
rootCommand.builder(yargsInstance);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Check that the command has subcommands by checking its description
|
|
36
|
+
const description = rootCommand.describe;
|
|
37
|
+
assert(
|
|
38
|
+
typeof description === 'string' && description.includes('db'),
|
|
39
|
+
'Command should have correct description'
|
|
40
|
+
);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
await it('should respect ignore patterns', async () => {
|
|
44
|
+
const commandsDir = path.join(__dirname, 'fixtures', 'commands');
|
|
45
|
+
const commands = await fileCommands({
|
|
46
|
+
commandDirs: [commandsDir],
|
|
47
|
+
extensions: ['.js'],
|
|
48
|
+
ignorePatterns: [/health/],
|
|
49
|
+
logLevel: 'debug'
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
assert.equal(commands.length, 1, 'Should have one root command');
|
|
53
|
+
const rootCommand = commands[0] as CommandModule;
|
|
54
|
+
assert(rootCommand, 'Root command should exist');
|
|
55
|
+
assert.equal(rootCommand.command, 'db', 'Root command should be "db"');
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
buildSegmentTree,
|
|
5
|
+
createCommand,
|
|
6
|
+
logCommandTree
|
|
7
|
+
} from './buildSegmentTree.js';
|
|
8
|
+
import type { Command } from './Command.js';
|
|
9
|
+
import { importCommandFromFile } from './importCommand.js';
|
|
10
|
+
import { scanDirectory, type ScanDirectoryOptions } from './scanDirectory.js';
|
|
11
|
+
import { segmentPath } from './segmentPath.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Configuration options for file-based command generation
|
|
15
|
+
* @interface FileCommandsOptions
|
|
16
|
+
*/
|
|
17
|
+
export type FileCommandsOptions = ScanDirectoryOptions & {
|
|
18
|
+
/** Array of directory paths to scan for command files */
|
|
19
|
+
commandDirs: string[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Default configuration options for file-based commands
|
|
24
|
+
* @constant
|
|
25
|
+
* @type {Partial<FileCommandsOptions>}
|
|
26
|
+
*/
|
|
27
|
+
export const DefaultFileCommandsOptions: Required<FileCommandsOptions> = {
|
|
28
|
+
/** Default directories to scan for command files */
|
|
29
|
+
commandDirs: [],
|
|
30
|
+
|
|
31
|
+
/** Default file extensions to process */
|
|
32
|
+
extensions: ['.js', '.ts'],
|
|
33
|
+
|
|
34
|
+
/** Default patterns to ignore when scanning directories */
|
|
35
|
+
ignorePatterns: [
|
|
36
|
+
/^[.|_].*/, // Hidden files and underscore files
|
|
37
|
+
/\.(?:test|spec)\.[jt]s$/, // Test files
|
|
38
|
+
/__(?:test|spec)__/, // Test directories
|
|
39
|
+
/\.d\.ts$/ // TypeScript declaration files
|
|
40
|
+
],
|
|
41
|
+
|
|
42
|
+
/** Default logging level */
|
|
43
|
+
logLevel: 'info',
|
|
44
|
+
|
|
45
|
+
/** Default log prefix */
|
|
46
|
+
logPrefix: ' '
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Generates a command tree structure from files in specified directories
|
|
51
|
+
* @async
|
|
52
|
+
* @param {FileCommandsOptions} options - Configuration options for command generation
|
|
53
|
+
* @returns {Promise<Command[]>} Array of root-level commands with their nested subcommands
|
|
54
|
+
*
|
|
55
|
+
* @description
|
|
56
|
+
* This function scans the specified directories for command files and builds a hierarchical
|
|
57
|
+
* command structure based on the file system layout. It processes files in parallel for better
|
|
58
|
+
* performance and supports nested commands through directory structure.
|
|
59
|
+
*
|
|
60
|
+
* The function will:
|
|
61
|
+
* 1. Scan all specified command directories
|
|
62
|
+
* 2. Process found files to extract command information
|
|
63
|
+
* 3. Build a tree structure based on file paths
|
|
64
|
+
* 4. Convert the tree into a command hierarchy
|
|
65
|
+
*/
|
|
66
|
+
export const fileCommands = async (options: FileCommandsOptions) => {
|
|
67
|
+
const fullOptions: Required<FileCommandsOptions> = {
|
|
68
|
+
...DefaultFileCommandsOptions,
|
|
69
|
+
...options
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// validate extensions have dots in them
|
|
73
|
+
if (fullOptions.extensions.some((ext) => !ext.startsWith('.'))) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid extensions provided, must start with a dot: ${fullOptions.extensions.join(
|
|
76
|
+
', '
|
|
77
|
+
)}`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
// check for empty list of directories to scan
|
|
81
|
+
if (fullOptions.commandDirs.length === 0) {
|
|
82
|
+
throw new Error('No command directories provided');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const commands: Command[] = [];
|
|
86
|
+
|
|
87
|
+
for (const commandDir of fullOptions.commandDirs) {
|
|
88
|
+
const fullPath = path.resolve(commandDir);
|
|
89
|
+
console.debug(`Scanning directory for commands: ${fullPath}`);
|
|
90
|
+
|
|
91
|
+
const filePaths = await scanDirectory(commandDir, commandDir, fullOptions);
|
|
92
|
+
|
|
93
|
+
console.debug(`Importing found commands:`);
|
|
94
|
+
for (const filePath of filePaths) {
|
|
95
|
+
const localPath = path.relative(commandDir, filePath);
|
|
96
|
+
const segments = segmentPath(filePath, commandDir);
|
|
97
|
+
segments.pop(); // remove extension.
|
|
98
|
+
|
|
99
|
+
if (fullOptions.logLevel === 'debug') {
|
|
100
|
+
console.debug(` ${localPath} - importing command module`);
|
|
101
|
+
}
|
|
102
|
+
commands.push({
|
|
103
|
+
fullPath: filePath,
|
|
104
|
+
segments,
|
|
105
|
+
commandModule: await importCommandFromFile(
|
|
106
|
+
filePath,
|
|
107
|
+
segments[segments.length - 1]!,
|
|
108
|
+
fullOptions
|
|
109
|
+
)
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// check if no commands were found
|
|
115
|
+
if (commands.length === 0) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
`No commands found in specified directories: ${fullOptions.commandDirs.join(
|
|
118
|
+
', '
|
|
119
|
+
)}`
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const commandRootNodes = buildSegmentTree(commands);
|
|
124
|
+
|
|
125
|
+
if (fullOptions.logLevel === 'debug') {
|
|
126
|
+
console.debug('Command tree structure:');
|
|
127
|
+
logCommandTree(commandRootNodes, 1);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const rootCommands = commandRootNodes.map((node) => createCommand(node));
|
|
131
|
+
|
|
132
|
+
return rootCommands;
|
|
133
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const describe = 'Database migration command';
|
|
2
|
+
|
|
3
|
+
export const builder = (yargs: any) => {
|
|
4
|
+
return yargs.option('force', {
|
|
5
|
+
type: 'boolean',
|
|
6
|
+
describe: 'Force migration'
|
|
7
|
+
});
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const handler = async (argv: any) => {
|
|
11
|
+
console.log('Migration handler called');
|
|
12
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { describe, it } from 'node:test';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
import { importCommandFromFile } from '../lib/importCommand.js';
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
describe('importCommandFromFile', async () => {
|
|
11
|
+
await it('should import command module correctly', async () => {
|
|
12
|
+
const commandPath = path.join(
|
|
13
|
+
__dirname,
|
|
14
|
+
'fixtures',
|
|
15
|
+
'commands',
|
|
16
|
+
'db',
|
|
17
|
+
'health.js'
|
|
18
|
+
);
|
|
19
|
+
const command = await importCommandFromFile(commandPath, 'health', {});
|
|
20
|
+
|
|
21
|
+
assert(command.describe, 'Should have describe property');
|
|
22
|
+
assert(
|
|
23
|
+
typeof command.builder === 'function',
|
|
24
|
+
'Should have builder function'
|
|
25
|
+
);
|
|
26
|
+
assert(
|
|
27
|
+
typeof command.handler === 'function',
|
|
28
|
+
'Should have handler function'
|
|
29
|
+
);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
await it('should handle non-existent files', async () => {
|
|
33
|
+
const nonExistentPath = path.join(
|
|
34
|
+
__dirname,
|
|
35
|
+
'fixtures',
|
|
36
|
+
'commands',
|
|
37
|
+
'non-existent.ts'
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
await assert.rejects(
|
|
41
|
+
async () => {
|
|
42
|
+
await importCommandFromFile(nonExistentPath, 'non-existent', {});
|
|
43
|
+
},
|
|
44
|
+
Error,
|
|
45
|
+
'Should throw error for non-existent file'
|
|
46
|
+
);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import {
|
|
3
|
+
type ArgumentsCamelCase,
|
|
4
|
+
type CommandBuilder,
|
|
5
|
+
type CommandModule
|
|
6
|
+
} from 'yargs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Represents command alias configuration
|
|
10
|
+
* @type {readonly string[] | string | undefined}
|
|
11
|
+
*/
|
|
12
|
+
export type CommandAlias = readonly string[] | string | undefined;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Represents command name configuration
|
|
16
|
+
* @type {readonly string[] | string | undefined}
|
|
17
|
+
*/
|
|
18
|
+
export type CommandName = readonly string[] | string | undefined;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Represents command deprecation configuration
|
|
22
|
+
* @type {boolean | string | undefined}
|
|
23
|
+
*/
|
|
24
|
+
export type CommandDeprecated = boolean | string | undefined;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Represents command description configuration
|
|
28
|
+
* @type {string | false | undefined}
|
|
29
|
+
*/
|
|
30
|
+
export type CommandDescribe = string | false | undefined;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Command handler function type
|
|
34
|
+
* @type {Function}
|
|
35
|
+
*/
|
|
36
|
+
export type CommandHandler = (
|
|
37
|
+
args: ArgumentsCamelCase<any>
|
|
38
|
+
) => void | Promise<any>;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parameters for file commands configuration
|
|
42
|
+
* @interface FileCommandsParams
|
|
43
|
+
*/
|
|
44
|
+
export interface FileCommandsParams {
|
|
45
|
+
/** Root directory for command files */
|
|
46
|
+
rootDir: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Structure of a command module import
|
|
51
|
+
* @interface CommandImportModule
|
|
52
|
+
*/
|
|
53
|
+
export interface CommandImportModule {
|
|
54
|
+
/** Command aliases */
|
|
55
|
+
alias?: CommandAlias;
|
|
56
|
+
/** Command builder function */
|
|
57
|
+
builder?: CommandBuilder;
|
|
58
|
+
/** Command name */
|
|
59
|
+
command?: CommandName;
|
|
60
|
+
/** Deprecation status */
|
|
61
|
+
deprecated?: CommandDeprecated;
|
|
62
|
+
/** Command description */
|
|
63
|
+
describe?: CommandDescribe;
|
|
64
|
+
/** Command handler function */
|
|
65
|
+
handler?: CommandHandler;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface ImportCommandOptions {
|
|
69
|
+
logLevel?: 'info' | 'debug';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Imports a command module from a file
|
|
74
|
+
* @async
|
|
75
|
+
* @param {string} filePath - Path to the command file
|
|
76
|
+
* @param {string} name - Command name
|
|
77
|
+
* @returns {Promise<CommandModule>} Imported command module
|
|
78
|
+
*
|
|
79
|
+
* @description
|
|
80
|
+
* Dynamically imports a command file and constructs a Yargs command module.
|
|
81
|
+
* If no handler is provided, creates a null implementation.
|
|
82
|
+
*/
|
|
83
|
+
export const importCommandFromFile = async (
|
|
84
|
+
filePath: string,
|
|
85
|
+
name: string,
|
|
86
|
+
options: ImportCommandOptions
|
|
87
|
+
) => {
|
|
88
|
+
// ensure file exists using fs node library
|
|
89
|
+
if (fs.existsSync(filePath) === false) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
`Can not import command from non-existence file path: ${filePath}`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const handlerModule = (await import(filePath)) as CommandImportModule;
|
|
96
|
+
const { logLevel = 'info' } = options;
|
|
97
|
+
|
|
98
|
+
const command = {
|
|
99
|
+
command: name,
|
|
100
|
+
describe: handlerModule.describe,
|
|
101
|
+
alias: handlerModule.alias,
|
|
102
|
+
builder: handlerModule.builder,
|
|
103
|
+
deprecated: handlerModule.deprecated,
|
|
104
|
+
handler:
|
|
105
|
+
handlerModule.handler ??
|
|
106
|
+
(async (args: ArgumentsCamelCase<any>) => {
|
|
107
|
+
// null implementation
|
|
108
|
+
})
|
|
109
|
+
} as CommandModule;
|
|
110
|
+
|
|
111
|
+
if (logLevel === 'debug') {
|
|
112
|
+
console.debug(
|
|
113
|
+
'Importing command from',
|
|
114
|
+
filePath,
|
|
115
|
+
'as',
|
|
116
|
+
name,
|
|
117
|
+
'with description',
|
|
118
|
+
command.describe
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return command;
|
|
122
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { describe, it } from 'node:test';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
import { scanDirectory } from '../lib/scanDirectory.js';
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
describe('scanDirectory', async () => {
|
|
11
|
+
await it('should find all command files in directory', async () => {
|
|
12
|
+
const commandsDir = path.join(__dirname, 'fixtures', 'commands');
|
|
13
|
+
console.log('Scan Directory: ', commandsDir);
|
|
14
|
+
const files = await scanDirectory(commandsDir, commandsDir, {
|
|
15
|
+
extensions: ['.js'],
|
|
16
|
+
logLevel: 'debug'
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
assert.equal(
|
|
20
|
+
files.length,
|
|
21
|
+
2,
|
|
22
|
+
`Should find two command files, instead found: ${files.join(', ')}`
|
|
23
|
+
);
|
|
24
|
+
assert(
|
|
25
|
+
files.some((f) => f.includes('health.js')),
|
|
26
|
+
`Should find health.js, instead found: ${files.join(', ')}`
|
|
27
|
+
);
|
|
28
|
+
assert(
|
|
29
|
+
files.some((f) => f.includes('command.js')),
|
|
30
|
+
`Should find command.js, instead found: ${files.join(', ')}`
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
await it('should respect ignore patterns', async () => {
|
|
35
|
+
const commandsDir = path.join(__dirname, 'fixtures', 'commands');
|
|
36
|
+
console.log('Scan Directory: ', commandsDir);
|
|
37
|
+
const files = await scanDirectory(commandsDir, commandsDir, {
|
|
38
|
+
extensions: ['.js'],
|
|
39
|
+
ignorePatterns: [/health/],
|
|
40
|
+
logLevel: 'debug'
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
assert.equal(
|
|
44
|
+
files.length,
|
|
45
|
+
1,
|
|
46
|
+
`Should find one command file, instead found: ${files.join(', ')}`
|
|
47
|
+
);
|
|
48
|
+
assert(
|
|
49
|
+
files.some((f) => f.includes('command.js')),
|
|
50
|
+
`Should find command.js, instead found: ${files.join(', ')}`
|
|
51
|
+
);
|
|
52
|
+
assert(
|
|
53
|
+
!files.some((f) => f.includes('health.js')),
|
|
54
|
+
`Should not find health.js, instead found: ${files.join(', ')}`
|
|
55
|
+
);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
await it('should handle non-existent directories', async () => {
|
|
59
|
+
const nonExistentDir = path.join(__dirname, 'fixtures', 'non-existent');
|
|
60
|
+
try {
|
|
61
|
+
console.log('Scan Directory: ', nonExistentDir);
|
|
62
|
+
await scanDirectory(nonExistentDir, nonExistentDir, {
|
|
63
|
+
extensions: ['.js'],
|
|
64
|
+
logLevel: 'debug'
|
|
65
|
+
});
|
|
66
|
+
assert.fail('Should have thrown an error');
|
|
67
|
+
} catch (error) {
|
|
68
|
+
assert(error instanceof Error);
|
|
69
|
+
assert(
|
|
70
|
+
error.message.includes('ENOENT'),
|
|
71
|
+
'Error should indicate directory not found'
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { readdir, stat } from 'fs/promises';
|
|
2
|
+
import path, { join } from 'path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Options for directory scanning
|
|
6
|
+
* @interface ScanDirectoryOptions
|
|
7
|
+
*/
|
|
8
|
+
export interface ScanDirectoryOptions {
|
|
9
|
+
/** File extensions to consider when scanning for command files */
|
|
10
|
+
extensions?: string[];
|
|
11
|
+
/** Regular expressions for patterns to ignore when scanning directories */
|
|
12
|
+
ignorePatterns?: RegExp[];
|
|
13
|
+
/** Logging verbosity level */
|
|
14
|
+
logLevel?: 'info' | 'debug';
|
|
15
|
+
/** Prefix for log messages */
|
|
16
|
+
logPrefix?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Recursively scans a directory for command files
|
|
21
|
+
* @async
|
|
22
|
+
* @param {string} dirPath - The directory path to scan
|
|
23
|
+
* @param {ScanDirectoryOptions} options - Scanning configuration options
|
|
24
|
+
* @returns {Promise<string[]>} Array of full paths to command files
|
|
25
|
+
*
|
|
26
|
+
* @description
|
|
27
|
+
* Performs a recursive directory scan, filtering files based on:
|
|
28
|
+
* - Ignore patterns (skips matching files/directories)
|
|
29
|
+
* - File extensions (only includes matching files)
|
|
30
|
+
* The scan is performed in parallel for better performance.
|
|
31
|
+
*/
|
|
32
|
+
export const scanDirectory = async (
|
|
33
|
+
dirPath: string,
|
|
34
|
+
commandDir: string,
|
|
35
|
+
options: ScanDirectoryOptions = {}
|
|
36
|
+
): Promise<string[]> => {
|
|
37
|
+
const {
|
|
38
|
+
ignorePatterns = [],
|
|
39
|
+
extensions = ['.js', '.ts'],
|
|
40
|
+
logLevel = 'info',
|
|
41
|
+
logPrefix = ''
|
|
42
|
+
} = options;
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
const entries = await readdir(dirPath);
|
|
46
|
+
|
|
47
|
+
const commandPaths: string[] = [];
|
|
48
|
+
for (const entry of entries) {
|
|
49
|
+
const fullPath = join(dirPath, entry);
|
|
50
|
+
|
|
51
|
+
const localPath = fullPath.replace(commandDir, '');
|
|
52
|
+
|
|
53
|
+
// apply ignore pattern and early return if matched
|
|
54
|
+
const shouldIgnore = ignorePatterns.some((pattern) =>
|
|
55
|
+
pattern.test(localPath)
|
|
56
|
+
);
|
|
57
|
+
if (shouldIgnore) {
|
|
58
|
+
if (logLevel === 'debug') {
|
|
59
|
+
console.debug(
|
|
60
|
+
`${logPrefix}${localPath} - ignoring because it matches ignorePattern: ${ignorePatterns
|
|
61
|
+
.filter((pattern) => pattern.test(localPath))
|
|
62
|
+
.join(', ')}`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const stats = await stat(fullPath);
|
|
69
|
+
|
|
70
|
+
if (stats.isDirectory()) {
|
|
71
|
+
if (logLevel === 'debug') {
|
|
72
|
+
console.debug(
|
|
73
|
+
`${logPrefix}${localPath} - directory, scanning for commands:`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
commandPaths.push(
|
|
77
|
+
...(await scanDirectory(fullPath, commandDir, {
|
|
78
|
+
...options,
|
|
79
|
+
logPrefix: `${logPrefix} `
|
|
80
|
+
}))
|
|
81
|
+
);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const extension = path.extname(fullPath);
|
|
85
|
+
if (!extensions.includes(extension)) {
|
|
86
|
+
if (logLevel === 'debug') {
|
|
87
|
+
console.debug(
|
|
88
|
+
`${logPrefix}${localPath} - ignoring as its extension, ${extension}, doesn't match required extension: ${extensions.join(
|
|
89
|
+
', '
|
|
90
|
+
)}`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (logLevel === 'debug') {
|
|
97
|
+
console.debug(`${logPrefix}${localPath} - possible command file`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
commandPaths.push(fullPath);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return commandPaths;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
`${logPrefix}Failed to scan directory ${dirPath}: ${error}`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { describe, it } from 'node:test';
|
|
2
|
+
|
|
3
|
+
import assert from 'assert';
|
|
4
|
+
|
|
5
|
+
import { segmentPath } from './segmentPath.js';
|
|
6
|
+
|
|
7
|
+
describe('segmentPath', () => {
|
|
8
|
+
it('should segment a path correctly', () => {
|
|
9
|
+
const fullPath =
|
|
10
|
+
'/Users/username/Coding/Personal/yargs-file-commands/packages/yargs-file-commands/src/lib/segmentPath.ts';
|
|
11
|
+
const baseDir = '/Users/username/Coding/Personal/yargs-file-commands/';
|
|
12
|
+
const expected = [
|
|
13
|
+
'packages',
|
|
14
|
+
'yargs-file-commands',
|
|
15
|
+
'src',
|
|
16
|
+
'lib',
|
|
17
|
+
'segmentPath',
|
|
18
|
+
'ts'
|
|
19
|
+
];
|
|
20
|
+
const result = segmentPath(fullPath, baseDir);
|
|
21
|
+
assert.deepStrictEqual(result, expected);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('should handle paths with periods correctly', () => {
|
|
25
|
+
const fullPath =
|
|
26
|
+
'/Users/username/Coding/Personal/yargs-file-commands/packages/yargs-file-commands/src/lib/segmentPath.test.ts';
|
|
27
|
+
const baseDir = '/Users/username/Coding/Personal/yargs-file-commands/';
|
|
28
|
+
const expected = [
|
|
29
|
+
'packages',
|
|
30
|
+
'yargs-file-commands',
|
|
31
|
+
'src',
|
|
32
|
+
'lib',
|
|
33
|
+
'segmentPath',
|
|
34
|
+
'test',
|
|
35
|
+
'ts'
|
|
36
|
+
];
|
|
37
|
+
const result = segmentPath(fullPath, baseDir);
|
|
38
|
+
assert.deepStrictEqual(result, expected);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should filter out "command" segments', () => {
|
|
42
|
+
const fullPath =
|
|
43
|
+
'/Users/username/Coding/Personal/yargs-file-commands/packages/yargs-file-commands/src/lib/commandPath.ts';
|
|
44
|
+
const baseDir = '/Users/username/Coding/Personal/yargs-file-commands/';
|
|
45
|
+
const expected = [
|
|
46
|
+
'packages',
|
|
47
|
+
'yargs-file-commands',
|
|
48
|
+
'src',
|
|
49
|
+
'lib',
|
|
50
|
+
'commandPath',
|
|
51
|
+
'ts'
|
|
52
|
+
];
|
|
53
|
+
const result = segmentPath(fullPath, baseDir);
|
|
54
|
+
assert.deepStrictEqual(result, expected);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should handle empty segments correctly', () => {
|
|
58
|
+
const fullPath =
|
|
59
|
+
'/Users/username/Coding/Personal/yargs-file-commands/packages/yargs-file-commands/src/lib/.hiddenFile';
|
|
60
|
+
const baseDir = '/Users/username/Coding/Personal/yargs-file-commands/';
|
|
61
|
+
const expected = [
|
|
62
|
+
'packages',
|
|
63
|
+
'yargs-file-commands',
|
|
64
|
+
'src',
|
|
65
|
+
'lib',
|
|
66
|
+
'hiddenFile'
|
|
67
|
+
];
|
|
68
|
+
const result = segmentPath(fullPath, baseDir);
|
|
69
|
+
assert.deepStrictEqual(result, expected);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Converts a file path into an array of command segments
|
|
3
|
+
* @param {string} fullPath - The complete file system path to the command file
|
|
4
|
+
* @param {string} baseDir - The base directory to make the path relative to
|
|
5
|
+
* @returns {string[]} Array of segments representing the command hierarchy
|
|
6
|
+
*
|
|
7
|
+
* @description
|
|
8
|
+
* This function processes a file path into command segments by:
|
|
9
|
+
* 1. Making the path relative to the base directory
|
|
10
|
+
* 2. Splitting on directory separators
|
|
11
|
+
* 3. Removing file extensions
|
|
12
|
+
* 4. Splitting on dots for nested commands
|
|
13
|
+
* 5. Filtering out empty segments and 'command' keyword
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* segmentPath('/base/dir/hello/world.command.ts', '/base/dir')
|
|
17
|
+
* // Returns: ['hello', 'world']
|
|
18
|
+
*/
|
|
19
|
+
export const segmentPath = (fullPath: string, baseDir: string): string[] => {
|
|
20
|
+
// Remove base directory and normalize slashes
|
|
21
|
+
const relativePath = fullPath.replace(baseDir, '').replace(/^[/\\\\]+/, '');
|
|
22
|
+
|
|
23
|
+
// Split into path segments and filename
|
|
24
|
+
const allSegments = relativePath.split(/[/\\\\]/);
|
|
25
|
+
|
|
26
|
+
// Process all segments including filename (without extension)
|
|
27
|
+
const processedSegments = allSegments
|
|
28
|
+
// Remove extension from the last segment (filename)
|
|
29
|
+
.map((segment, index, array) =>
|
|
30
|
+
index === array.length - 1 ? segment.replace(/\\.[^/.]+$/, '') : segment
|
|
31
|
+
)
|
|
32
|
+
// Split segments containing periods
|
|
33
|
+
.flatMap((segment) => segment.split('.'))
|
|
34
|
+
// Filter out empty segments and 'command'
|
|
35
|
+
.filter((segment) => segment !== '' && segment !== 'command');
|
|
36
|
+
|
|
37
|
+
return processedSegments;
|
|
38
|
+
};
|