yargs-file-commands 0.0.19 → 1.0.1

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.
Files changed (57) hide show
  1. package/README.md +59 -13
  2. package/dist/index.js +1 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/lib/Command.js +1 -0
  5. package/dist/lib/Command.js.map +1 -0
  6. package/dist/lib/buildSegmentTree.d.ts +1 -1
  7. package/dist/lib/buildSegmentTree.js +7 -3
  8. package/dist/lib/buildSegmentTree.js.map +1 -0
  9. package/dist/lib/buildSegmentTree.test.js +279 -26
  10. package/dist/lib/buildSegmentTree.test.js.map +1 -0
  11. package/dist/lib/fileCommands.d.ts +2 -1
  12. package/dist/lib/fileCommands.js +39 -21
  13. package/dist/lib/fileCommands.js.map +1 -0
  14. package/dist/lib/fileCommands.test.js +107 -30
  15. package/dist/lib/fileCommands.test.js.map +1 -0
  16. package/dist/lib/fixtures/commands/$default.js +1 -0
  17. package/dist/lib/fixtures/commands/$default.js.map +1 -0
  18. package/dist/lib/fixtures/commands/create.js +1 -0
  19. package/dist/lib/fixtures/commands/create.js.map +1 -0
  20. package/dist/lib/fixtures/commands/db/health.d.ts +2 -1
  21. package/dist/lib/fixtures/commands/db/health.js +2 -3
  22. package/dist/lib/fixtures/commands/db/health.js.map +1 -0
  23. package/dist/lib/fixtures/commands/db/migration/command.d.ts +9 -2
  24. package/dist/lib/fixtures/commands/db/migration/command.js +6 -7
  25. package/dist/lib/fixtures/commands/db/migration/command.js.map +1 -0
  26. package/dist/lib/importCommand.d.ts +8 -4
  27. package/dist/lib/importCommand.js +66 -21
  28. package/dist/lib/importCommand.js.map +1 -0
  29. package/dist/lib/importCommand.test.js +157 -34
  30. package/dist/lib/importCommand.test.js.map +1 -0
  31. package/dist/lib/scanDirectory.js +54 -25
  32. package/dist/lib/scanDirectory.js.map +1 -0
  33. package/dist/lib/scanDirectory.test.js +148 -25
  34. package/dist/lib/scanDirectory.test.js.map +1 -0
  35. package/dist/lib/segmentPath.js +8 -6
  36. package/dist/lib/segmentPath.js.map +1 -0
  37. package/dist/lib/segmentPath.test.js +10 -38
  38. package/dist/lib/segmentPath.test.js.map +1 -0
  39. package/dist/tsconfig.tsbuildinfo +1 -0
  40. package/package.json +6 -9
  41. package/CHANGELOG.md +0 -56
  42. package/src/index.ts +0 -1
  43. package/src/lib/Command.ts +0 -16
  44. package/src/lib/buildSegmentTree.test.ts +0 -90
  45. package/src/lib/buildSegmentTree.ts +0 -149
  46. package/src/lib/fileCommands.test.ts +0 -55
  47. package/src/lib/fileCommands.ts +0 -149
  48. package/src/lib/fixtures/commands/$default.ts +0 -5
  49. package/src/lib/fixtures/commands/create.ts +0 -6
  50. package/src/lib/fixtures/commands/db/health.ts +0 -9
  51. package/src/lib/fixtures/commands/db/migration/command.ts +0 -12
  52. package/src/lib/importCommand.test.ts +0 -65
  53. package/src/lib/importCommand.ts +0 -148
  54. package/src/lib/scanDirectory.test.ts +0 -75
  55. package/src/lib/scanDirectory.ts +0 -109
  56. package/src/lib/segmentPath.test.ts +0 -71
  57. package/src/lib/segmentPath.ts +0 -38
@@ -1,149 +0,0 @@
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
- // throw if some command directories are not absolute, first filter to find non-absolute an then throw, listing those that are not absolute
86
- const nonAbsoluteDirs = fullOptions.commandDirs.filter(
87
- (dir) => !path.isAbsolute(dir)
88
- );
89
- if (nonAbsoluteDirs.length > 0) {
90
- throw new Error(
91
- `Command directories must be absolute paths: ${nonAbsoluteDirs.join(
92
- ', '
93
- )}`
94
- );
95
- }
96
-
97
- const commands: Command[] = [];
98
-
99
- for (const commandDir of fullOptions.commandDirs) {
100
- const fullPath = path.resolve(commandDir);
101
- if (fullOptions.logLevel === 'debug') {
102
- console.debug(`Scanning directory for commands: ${fullPath}`);
103
- }
104
-
105
- const filePaths = await scanDirectory(commandDir, commandDir, fullOptions);
106
-
107
- if (fullOptions.logLevel === 'debug') {
108
- console.debug(`Importing found commands:`);
109
- }
110
- for (const filePath of filePaths) {
111
- const localPath = path.relative(commandDir, filePath);
112
- const segments = segmentPath(filePath, commandDir);
113
- segments.pop(); // remove extension.
114
-
115
- if (fullOptions.logLevel === 'debug') {
116
- console.debug(` ${localPath} - importing command module`);
117
- }
118
- commands.push({
119
- fullPath: filePath,
120
- segments,
121
- commandModule: await importCommandFromFile(
122
- filePath,
123
- segments[segments.length - 1]!,
124
- fullOptions
125
- )
126
- });
127
- }
128
- }
129
-
130
- // check if no commands were found
131
- if (commands.length === 0) {
132
- throw new Error(
133
- `No commands found in specified directories: ${fullOptions.commandDirs.join(
134
- ', '
135
- )}`
136
- );
137
- }
138
-
139
- const commandRootNodes = buildSegmentTree(commands);
140
-
141
- if (fullOptions.logLevel === 'debug') {
142
- console.debug('Command tree structure:');
143
- logCommandTree(commandRootNodes, 1);
144
- }
145
-
146
- const rootCommands = commandRootNodes.map((node) => createCommand(node));
147
-
148
- return rootCommands;
149
- };
@@ -1,5 +0,0 @@
1
- export const describe = 'Default command';
2
-
3
- export const handler = async () => {
4
- // Default command implementation
5
- };
@@ -1,6 +0,0 @@
1
- export const command = 'create [name]';
2
- export const describe = 'Create something with a name';
3
-
4
- export const handler = async () => {
5
- // Create command implementation
6
- };
@@ -1,9 +0,0 @@
1
- export const describe = 'Database health check';
2
-
3
- export const builder = (yargs: any) => {
4
- return yargs;
5
- };
6
-
7
- export const handler = async () => {
8
- console.log('Health check handler called');
9
- };
@@ -1,12 +0,0 @@
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
- };
@@ -1,65 +0,0 @@
1
- import path from 'path';
2
- import { test } from 'node:test';
3
- import assert from 'node:assert';
4
-
5
- import { importCommandFromFile } from './importCommand.js';
6
-
7
- // get __dirname in ESM style
8
- const __dirname = path.dirname(new URL(import.meta.url).pathname);
9
-
10
- test('should import command module correctly', async () => {
11
- const filePath = path.join(
12
- __dirname,
13
- 'fixtures',
14
- 'commands',
15
- 'db',
16
- 'health.js'
17
- );
18
- const command = await importCommandFromFile(filePath, 'health', {
19
- logLevel: 'info'
20
- });
21
-
22
- assert.equal(command.describe, 'Database health check');
23
- });
24
-
25
- test('should handle non-existent files', async () => {
26
- const filePath = path.join(
27
- __dirname,
28
- 'fixtures',
29
- 'commands',
30
- 'non-existent.js'
31
- );
32
- try {
33
- await importCommandFromFile(filePath, 'non-existent', {
34
- logLevel: 'info'
35
- });
36
- assert.fail('Should have thrown an error');
37
- } catch (error) {
38
- assert.ok(error instanceof Error);
39
- assert.ok(
40
- (error as Error).message.includes(
41
- 'Can not import command from non-existence'
42
- )
43
- );
44
- }
45
- });
46
-
47
- test('should handle explicit command names', async () => {
48
- const filePath = path.join(__dirname, 'fixtures', 'commands', 'create.js');
49
- const command = await importCommandFromFile(filePath, 'create', {
50
- logLevel: 'info'
51
- });
52
-
53
- assert.equal(command.command, 'create [name]');
54
- assert.equal(command.describe, 'Create something with a name');
55
- });
56
-
57
- test('should handle default commands', async () => {
58
- const filePath = path.join(__dirname, 'fixtures', 'commands', '$default.js');
59
- const command = await importCommandFromFile(filePath, '$default', {
60
- logLevel: 'info'
61
- });
62
-
63
- assert.equal(command.command, '$0');
64
- assert.equal(command.describe, 'Default command');
65
- });
@@ -1,148 +0,0 @@
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 url = 'file://' + filePath;
96
-
97
- const handlerModule = (await import(url)) as CommandImportModule;
98
- const { logLevel = 'info' } = options;
99
-
100
- // Check if this is the default command
101
- const isDefault = name === '$default';
102
-
103
- const command = {
104
- command: handlerModule.command ?? (isDefault ? '$0' : name),
105
- describe: handlerModule.describe,
106
- alias: handlerModule.alias,
107
- builder: handlerModule.builder,
108
- deprecated: handlerModule.deprecated,
109
- handler:
110
- handlerModule.handler ??
111
- (async (args: ArgumentsCamelCase<any>) => {
112
- // null implementation
113
- })
114
- } as CommandModule;
115
-
116
- const supportedNames = [
117
- 'command',
118
- 'describe',
119
- 'alias',
120
- 'builder',
121
- 'deprecated',
122
- 'handler'
123
- ];
124
- const module = handlerModule as Record<string, any>;
125
- const unsupportedExports = Object.keys(module).filter(
126
- (key) => !supportedNames.includes(key)
127
- );
128
- if (unsupportedExports.length > 0) {
129
- throw new Error(
130
- `Command module ${name} in ${filePath} has some unsupported exports, probably a misspelling: ${unsupportedExports.join(
131
- ', '
132
- )}`
133
- );
134
- }
135
-
136
- if (logLevel === 'debug') {
137
- console.debug(
138
- 'Importing command from',
139
- filePath,
140
- 'as',
141
- name,
142
- 'with description',
143
- command.describe
144
- );
145
- }
146
-
147
- return command;
148
- };
@@ -1,75 +0,0 @@
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
- 4,
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/, /.d.ts/],
40
- logLevel: 'debug'
41
- });
42
-
43
- assert.equal(
44
- files.length,
45
- 3,
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
- });
@@ -1,109 +0,0 @@
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
- };
@@ -1,71 +0,0 @@
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
- });
@@ -1,38 +0,0 @@
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
- };