Coverage for src/csv_schema_validator_cli/cli.py: 15%

74 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-21 14:35 +0200

1""" 

2Command-line interface for CSV schema validation. 

3""" 

4from __future__ import annotations 

5 

6import json 

7import os 

8import sys 

9 

10from csv_schema_validator import validate_csv 

11from csv_schema_validator.exceptions import InvalidJSONError, SchemaFileError 

12 

13""" 

14CLI usages: 

15csv-schema-validator <csv_file> <schema_file> # Validate CSV against schema 

16csv-schema-validator -h # Show help 

17csv-schema-validator --help # Show help 

18csv-schema-validator -v # Show version 

19csv-schema-validator --version # Show version 

20""" 

21 

22 

23def show_help() -> None: 

24 """Display help information.""" 

25 help_text = """ 

26csv-schema-validator - Validate CSV files against JSON schemas 

27 

28USAGE: 

29 csv-schema-validator <csv_file> <schema_file> 

30 

31ARGUMENTS: 

32 csv_file Path to the CSV file to validate 

33 schema_file Path to the JSON schema file 

34 

35OPTIONS: 

36 -h, --help Show this help message 

37 -v, --version Show version information 

38 

39EXAMPLES: 

40 # Validate a CSV file against a schema 

41 csv-schema-validator employees.csv employee_schema.json 

42  

43 # Show help 

44 csv-schema-validator --help 

45  

46 # Show version 

47 csv-schema-validator --version 

48 

49SCHEMA FORMAT: 

50 The schema file should be a JSON file with the following structure: 

51 { 

52 "name": "Schema Name", 

53 "description": "Schema description", 

54 "fields": [ 

55 { 

56 "name": "field_name", 

57 "type": "string|number|integer|boolean", 

58 "required": true|false, 

59 "description": "Field description", 

60 "pattern": "regex_pattern", // optional 

61 "enum": ["value1", "value2"], // optional 

62 "min": 0, // optional 

63 "max": 100 // optional 

64 } 

65 ] 

66 } 

67 

68EXIT CODES: 

69 0 Validation passed 

70 1 Validation failed or error occurred 

71 

72For more information, visit: https://github.com/your-repo/csv-schema-validator 

73""" 

74 print(help_text.strip()) 

75 

76 

77def show_version() -> None: 

78 """Display version information.""" 

79 print("csv-schema-validator 0.1.1") 

80 

81 

82def cli() -> None: 

83 """ 

84 Command-line interface. 

85 """ 

86 # Handle help and version flags 

87 if len(sys.argv) == 2: 

88 arg = sys.argv[1] 

89 if arg in ["-h", "--help"]: 

90 show_help() 

91 sys.exit(0) 

92 elif arg in ["-v", "--version"]: 

93 show_version() 

94 sys.exit(0) 

95 else: 

96 print("Usage: csv-schema-validator <csv_file> <schema_file>", file=sys.stderr) 

97 print("Use --help for more information.", file=sys.stderr) 

98 sys.exit(1) 

99 

100 # Check for help flags even with other arguments 

101 if len(sys.argv) > 1: 

102 for arg in sys.argv[1:]: 

103 if arg in ["-h", "--help"]: 

104 show_help() 

105 sys.exit(0) 

106 elif arg in ["-v", "--version"]: 

107 show_version() 

108 sys.exit(0) 

109 

110 if len(sys.argv) != 3: 

111 print("Usage: csv-schema-validator <csv_file> <schema_file>", file=sys.stderr) 

112 print("Use --help for more information.", file=sys.stderr) 

113 sys.exit(1) 

114 

115 csv_file, schema_file = sys.argv[1:3] 

116 

117 if not csv_file or not schema_file: 

118 print("Usage: csv-schema-validator <csv_file> <schema_file>") 

119 sys.exit(1) 

120 

121 if not os.path.exists(csv_file): 

122 print(f"Error: CSV file {csv_file} does not exist") 

123 sys.exit(1) 

124 

125 if not os.path.exists(schema_file): 

126 print(f"Error: Schema file {schema_file} does not exist") 

127 sys.exit(1) 

128 

129 try: 

130 with open(schema_file, "r", encoding="utf-8") as f: 

131 schema = json.load(f) 

132 except json.JSONDecodeError as e: 

133 error = InvalidJSONError(schema_file, str(e)) 

134 print(f"Error: {error.message}", file=sys.stderr) 

135 sys.exit(1) 

136 except IOError as e: 

137 error = SchemaFileError(f"Cannot read schema file: {str(e)}", schema_file) 

138 print(f"Error: {error.message}", file=sys.stderr) 

139 sys.exit(1) 

140 

141 try: 

142 result = validate_csv(csv_file, schema) 

143 print( 

144 f"❌ Validation failed: {len(result['errors'])} errors found" 

145 if not result["is_valid"] 

146 else "✅ Validation passed" 

147 ) 

148 print() 

149 for error in result["errors"]: 

150 print( 

151 f"Row {error['row'] if 'row' in error else -1}, Column {error['column'] if 'column' in error else -1}: {error['error_type'] if 'error_type' in error else 'Unknown error'}" 

152 ) 

153 print(f" Value: {error['value'] if 'value' in error else 'Unknown value'}") 

154 print( 

155 f" Details: {error['details'] if 'details' in error else 'Unknown details'}" 

156 ) 

157 print( 

158 f" Error message: {error['error_message'] if 'error_message' in error else 'Unknown error message'}" 

159 ) 

160 print() 

161 sys.stdout.flush() 

162 

163 # Exit with appropriate code 

164 sys.exit(0 if result["is_valid"] else 1) 

165 except ValueError as e: 

166 print(f"Error: {e}") 

167 sys.exit(1) 

168 

169 

170if __name__ == "__main__": 

171 cli()