Skip to content

Commit

Permalink
feat: support single-character flags
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Jun 18, 2024
1 parent 7629ed6 commit 2145f4d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 12 deletions.
8 changes: 4 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ const validateFlagName = (
throw new Error(`${errorPrefix} cannot be empty`);
}

if (flagName.length === 1) {
throw new Error(`${errorPrefix} must be longer than a character`);
}

const hasReservedCharacter = flagName.match(reservedCharactersPattern);
if (hasReservedCharacter) {
throw new Error(`${errorPrefix} cannot contain ${stringify(hasReservedCharacter?.[0])}`);
Expand Down Expand Up @@ -136,6 +132,10 @@ export const createRegistry = (
const { alias } = schema;
const errorPrefix = `Flag alias ${stringify(alias)} for flag ${stringify(flagName)}`;

if (flagName.length === 1) {
throw new Error(`${errorPrefix} cannot be defined for a single-character flag`);
}

if (alias.length === 0) {
throw new Error(`${errorPrefix} cannot be empty`);
}
Expand Down
50 changes: 42 additions & 8 deletions tests/specs/type-flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,6 @@ export default testSuite(({ describe }) => {
}).toThrow(/* 'Invalid flag name: empty' */);
});

test('Single character flag name', () => {
expect(() => {
typeFlag({
i: String,
}, []);
}).toThrow(/* 'Invalid flag name: single characters are reserved for aliases' */);
});

test('Reserved characters', () => {
expect(() => {
typeFlag({ 'flag a': String }, []);
Expand Down Expand Up @@ -70,6 +62,17 @@ export default testSuite(({ describe }) => {
}).toThrow(/* 'Empty alias' */);
});

test('Single-character alias', () => {
expect(() => {
typeFlag({
a: {
type: String,
alias: 'a',
},
}, []);
}).toThrow(/* must not be defined for a single-character flag */);
});

test('Multi-character alias', () => {
expect(() => {
typeFlag({
Expand Down Expand Up @@ -406,6 +409,37 @@ export default testSuite(({ describe }) => {
expect<string[]>(parsed.flags.alias).toStrictEqual(['', '', 'value']);
expect(argv).toStrictEqual([]);
});

test('single-character alias', () => {
const argv = ['-x', '1', '-y', '2'];
const parsed = typeFlag(
{
x: Number,
y: Number,
},
argv,
);

expect<number | undefined>(parsed.flags.x).toBe(1);
expect<number | undefined>(parsed.flags.y).toBe(2);
});

test('single-character alias grouping', () => {
const argv = ['-am', 'hello'];
const parsed = typeFlag(
{
a: Boolean,
message: {
type: String,
alias: 'm',
},
},
argv,
);

expect<boolean | undefined>(parsed.flags.a).toBe(true);
expect<string | undefined>(parsed.flags.message).toBe('hello');
});
});

test('unknown flags', () => {
Expand Down

0 comments on commit 2145f4d

Please sign in to comment.