feat: add comprehensive centralized command line flag validation
Replaces scattered ad-hoc validation with a centralized, testable validation system. Provides consistent error messages and comprehensive coverage of flag combinations and edge cases. Changes: - Add flagValidator module with comprehensive validation functions - Test coverage for all validation scenarios (17 tests) - Replace scattered validation in index.ts with centralized validateFlags() - Validate flag dependencies (--format/--silent require -p) - Validate conflicting flags (--readonly vs --auto) - Validate permission flag values (no empty tool names) - Consistent error formatting and exit handling All existing validation behavior preserved while adding new validations for edge cases like empty permission tool names.
This commit is contained in:
parent
94dea97540
commit
7fea7fb369
3 changed files with 417 additions and 20 deletions
209
src/flags/flagValidator.test.ts
Normal file
209
src/flags/flagValidator.test.ts
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
import { validateFlags, handleValidationErrors, ValidationOptions } from './flagValidator.js';
|
||||
|
||||
describe('validateFlags', () => {
|
||||
describe('format flag validation', () => {
|
||||
test('should pass when format is used with print', () => {
|
||||
const result = validateFlags({
|
||||
format: 'json',
|
||||
print: true,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when format is used without print', () => {
|
||||
const result = validateFlags({
|
||||
format: 'json',
|
||||
print: false,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('FORMAT_REQUIRES_PRINT');
|
||||
expect(result.errors[0].message).toContain('--format flag can only be used with -p/--print');
|
||||
});
|
||||
|
||||
test('should fail when format value is invalid', () => {
|
||||
const result = validateFlags({
|
||||
format: 'xml',
|
||||
print: true,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('INVALID_FORMAT_VALUE');
|
||||
expect(result.errors[0].message).toContain("--format currently only supports 'json'");
|
||||
});
|
||||
});
|
||||
|
||||
describe('silent flag validation', () => {
|
||||
test('should pass when silent is used with print', () => {
|
||||
const result = validateFlags({
|
||||
silent: true,
|
||||
print: true,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when silent is used without print', () => {
|
||||
const result = validateFlags({
|
||||
silent: true,
|
||||
print: false,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('SILENT_REQUIRES_PRINT');
|
||||
expect(result.errors[0].message).toContain('--silent flag can only be used with -p/--print');
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode flags validation', () => {
|
||||
test('should pass with readonly only', () => {
|
||||
const result = validateFlags({
|
||||
readonly: true,
|
||||
auto: false,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should pass with auto only', () => {
|
||||
const result = validateFlags({
|
||||
readonly: false,
|
||||
auto: true,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when both readonly and auto are used', () => {
|
||||
const result = validateFlags({
|
||||
readonly: true,
|
||||
auto: true,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('CONFLICTING_MODE_FLAGS');
|
||||
expect(result.errors[0].message).toContain('Cannot use both --readonly and --auto');
|
||||
});
|
||||
});
|
||||
|
||||
describe('permission flags validation', () => {
|
||||
test('should pass with valid permission flags', () => {
|
||||
const result = validateFlags({
|
||||
allow: ['readFile', 'searchCode'],
|
||||
ask: ['writeFile'],
|
||||
exclude: ['Write', 'Bash'],
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in allow', () => {
|
||||
const result = validateFlags({
|
||||
allow: ['readFile', '', 'searchCode'],
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_ALLOW_TOOL');
|
||||
expect(result.errors[0].message).toContain('--allow requires a tool name');
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in ask', () => {
|
||||
const result = validateFlags({
|
||||
ask: ['writeFile', ' ', 'editFile'],
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_ASK_TOOL');
|
||||
expect(result.errors[0].message).toContain('--ask requires a tool name');
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in exclude', () => {
|
||||
const result = validateFlags({
|
||||
exclude: ['Write', '', 'Bash'],
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_EXCLUDE_TOOL');
|
||||
expect(result.errors[0].message).toContain('--exclude requires a tool name');
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiple errors', () => {
|
||||
test('should return all validation errors', () => {
|
||||
const result = validateFlags({
|
||||
format: 'xml',
|
||||
print: false,
|
||||
silent: true,
|
||||
readonly: true,
|
||||
auto: true,
|
||||
allow: ['readFile', ''],
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors.length).toBeGreaterThan(1);
|
||||
|
||||
const errorCodes = result.errors.map(e => e.code);
|
||||
expect(errorCodes).toContain('FORMAT_REQUIRES_PRINT');
|
||||
expect(errorCodes).toContain('INVALID_FORMAT_VALUE');
|
||||
expect(errorCodes).toContain('SILENT_REQUIRES_PRINT');
|
||||
expect(errorCodes).toContain('CONFLICTING_MODE_FLAGS');
|
||||
expect(errorCodes).toContain('EMPTY_ALLOW_TOOL');
|
||||
});
|
||||
});
|
||||
|
||||
describe('config path validation', () => {
|
||||
test('should pass with valid config path', () => {
|
||||
const result = validateFlags({
|
||||
config: './my-config.yaml',
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should pass with undefined config', () => {
|
||||
const result = validateFlags({
|
||||
config: undefined,
|
||||
});
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleValidationErrors', () => {
|
||||
test('should be a function that accepts validation errors', () => {
|
||||
// Test function signature without calling it (since it calls process.exit)
|
||||
expect(typeof handleValidationErrors).toBe('function');
|
||||
expect(handleValidationErrors.length).toBe(1);
|
||||
});
|
||||
|
||||
test('should accept proper error format', () => {
|
||||
const validErrors = [
|
||||
{ code: 'TEST_ERROR', message: 'Test message' },
|
||||
{ code: 'ANOTHER_ERROR', message: 'Another message' }
|
||||
];
|
||||
|
||||
// Verify the function exists and would accept this format
|
||||
// We don't call it since it would exit the process
|
||||
expect(() => {
|
||||
const errorArray = validErrors;
|
||||
expect(Array.isArray(errorArray)).toBe(true);
|
||||
expect(errorArray.every(e => e.code && e.message)).toBe(true);
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
191
src/flags/flagValidator.ts
Normal file
191
src/flags/flagValidator.ts
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
/**
|
||||
* Centralized command line flag validation
|
||||
* Provides consistent validation across all commands and proper error reporting
|
||||
*/
|
||||
|
||||
export interface ValidationOptions {
|
||||
// Root command specific flags
|
||||
print?: boolean;
|
||||
format?: string;
|
||||
silent?: boolean;
|
||||
|
||||
// Common flags
|
||||
readonly?: boolean;
|
||||
auto?: boolean;
|
||||
config?: string;
|
||||
|
||||
// Permission flags
|
||||
allow?: string[];
|
||||
ask?: string[];
|
||||
exclude?: string[];
|
||||
|
||||
// Command context
|
||||
isRootCommand?: boolean;
|
||||
commandName?: string;
|
||||
}
|
||||
|
||||
export interface ValidationError {
|
||||
message: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export interface ValidationResult {
|
||||
isValid: boolean;
|
||||
errors: ValidationError[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that --format flag only works with -p/--print
|
||||
*/
|
||||
function validateFormatFlag(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
if (options.format && !options.print) {
|
||||
errors.push({
|
||||
code: 'FORMAT_REQUIRES_PRINT',
|
||||
message: 'Error: --format flag can only be used with -p/--print flag'
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that --silent flag only works with -p/--print
|
||||
*/
|
||||
function validateSilentFlag(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
if (options.silent && !options.print) {
|
||||
errors.push({
|
||||
code: 'SILENT_REQUIRES_PRINT',
|
||||
message: 'Error: --silent flag can only be used with -p/--print flag'
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate format value is supported
|
||||
*/
|
||||
function validateFormatValue(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
if (options.format && options.format !== 'json') {
|
||||
errors.push({
|
||||
code: 'INVALID_FORMAT_VALUE',
|
||||
message: "Error: --format currently only supports 'json'"
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that --readonly and --auto are mutually exclusive
|
||||
* This validation is now handled in flagProcessor.ts, but we keep it here for completeness
|
||||
*/
|
||||
function validateModeFlags(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
if (options.readonly && options.auto) {
|
||||
errors.push({
|
||||
code: 'CONFLICTING_MODE_FLAGS',
|
||||
message: 'Error: Cannot use both --readonly and --auto flags together'
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate config path exists (basic check)
|
||||
*/
|
||||
function validateConfigPath(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
// Note: We don't check file existence here since the config loader handles that
|
||||
// and provides better error messages. This is just for basic validation.
|
||||
if (options.config && typeof options.config !== 'string') {
|
||||
errors.push({
|
||||
code: 'INVALID_CONFIG_PATH',
|
||||
message: 'Error: --config must be a valid path'
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate permission flag combinations
|
||||
*/
|
||||
function validatePermissionFlags(options: ValidationOptions): ValidationError[] {
|
||||
const errors: ValidationError[] = [];
|
||||
|
||||
// Check for empty permission arrays (likely user error)
|
||||
if (options.allow?.some(tool => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_ALLOW_TOOL',
|
||||
message: 'Error: --allow requires a tool name (e.g., --allow readFile)'
|
||||
});
|
||||
}
|
||||
|
||||
if (options.ask?.some(tool => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_ASK_TOOL',
|
||||
message: 'Error: --ask requires a tool name (e.g., --ask writeFile)'
|
||||
});
|
||||
}
|
||||
|
||||
if (options.exclude?.some(tool => !tool.trim())) {
|
||||
errors.push({
|
||||
code: 'EMPTY_EXCLUDE_TOOL',
|
||||
message: 'Error: --exclude requires a tool name (e.g., --exclude Write)'
|
||||
});
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all validation checks on the provided options
|
||||
*/
|
||||
export function validateFlags(options: ValidationOptions): ValidationResult {
|
||||
const allErrors: ValidationError[] = [];
|
||||
|
||||
// Run all validation functions
|
||||
const validators = [
|
||||
validateFormatFlag,
|
||||
validateSilentFlag,
|
||||
validateFormatValue,
|
||||
validateModeFlags,
|
||||
validateConfigPath,
|
||||
validatePermissionFlags,
|
||||
];
|
||||
|
||||
for (const validator of validators) {
|
||||
allErrors.push(...validator(options));
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: allErrors.length === 0,
|
||||
errors: allErrors,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Display validation errors and exit process
|
||||
* Provides consistent error formatting across all commands
|
||||
*/
|
||||
export function handleValidationErrors(errors: ValidationError[]): never {
|
||||
for (const error of errors) {
|
||||
console.error(error.message);
|
||||
}
|
||||
|
||||
if (errors.length > 1) {
|
||||
console.error(`\nFound ${errors.length} validation errors.`);
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
37
src/index.ts
37
src/index.ts
|
|
@ -8,6 +8,7 @@ import { remoteTest } from "./commands/remote-test.js";
|
|||
import { remote } from "./commands/remote.js";
|
||||
import { serve } from "./commands/serve.js";
|
||||
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
|
||||
import { validateFlags, handleValidationErrors } from "./flags/flagValidator.js";
|
||||
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
|
||||
import logger from "./util/logger.js";
|
||||
import { readStdinSync } from "./util/stdin.js";
|
||||
|
|
@ -53,27 +54,23 @@ addCommonOptions(program)
|
|||
configureConsoleForHeadless(isHeadless);
|
||||
logger.configureHeadlessMode(isHeadless);
|
||||
|
||||
// Validate --format flag only works with -p/--print
|
||||
if (options.format && !options.print) {
|
||||
console.error(
|
||||
"Error: --format flag can only be used with -p/--print flag"
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
// Validate all command line flags
|
||||
const validation = validateFlags({
|
||||
print: options.print,
|
||||
format: options.format,
|
||||
silent: options.silent,
|
||||
readonly: options.readonly,
|
||||
auto: options.auto,
|
||||
config: options.config,
|
||||
allow: options.allow,
|
||||
ask: options.ask,
|
||||
exclude: options.exclude,
|
||||
isRootCommand: true,
|
||||
commandName: 'cn'
|
||||
});
|
||||
|
||||
// Validate --silent flag only works with -p/--print
|
||||
if (options.silent && !options.print) {
|
||||
console.error(
|
||||
"Error: --silent flag can only be used with -p/--print flag"
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
// Validate format value
|
||||
if (options.format && options.format !== "json") {
|
||||
console.error("Error: --format currently only supports 'json'");
|
||||
process.exit(1);
|
||||
if (!validation.isValid) {
|
||||
handleValidationErrors(validation.errors);
|
||||
}
|
||||
|
||||
if (options.verbose) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue