-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
377 lines (307 loc) · 10.5 KB
/
cli.py
File metadata and controls
377 lines (307 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""
cli.py - Enhanced Command Line Interface for Compgrapher
This module provides a rich CLI with logging, configuration file support,
progress bars, and comprehensive argument handling.
"""
import argparse
import logging
import os
import sys
from pathlib import Path
from typing import Dict, List, Optional, Any
import yaml
# Version info
__version__ = "1.0.0"
def setup_logging(verbose: bool = False, quiet: bool = False, log_file: Optional[str] = None) -> logging.Logger:
"""
Configure logging based on verbosity settings.
Args:
verbose: Enable debug-level logging
quiet: Suppress all but error messages
log_file: Optional file path for logging
Returns:
Configured logger instance
"""
if quiet:
level = logging.ERROR
elif verbose:
level = logging.DEBUG
else:
level = logging.INFO
# Create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Configure root logger
logger = logging.getLogger('compgrapher')
logger.setLevel(level)
# Console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# File handler if specified
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def load_config(config_path: str) -> Dict[str, Any]:
"""
Load configuration from YAML file.
Args:
config_path: Path to config file
Returns:
Configuration dictionary
Raises:
FileNotFoundError: If config file doesn't exist
yaml.YAMLError: If config file is invalid
"""
config_file = Path(config_path)
if not config_file.exists():
raise FileNotFoundError(f"Configuration file not found: {config_path}")
with open(config_file, 'r') as f:
config = yaml.safe_load(f)
return config or {}
def merge_config_with_args(config: Dict[str, Any], args: argparse.Namespace) -> argparse.Namespace:
"""
Merge configuration file settings with command line arguments.
Command line arguments take precedence.
Args:
config: Configuration dictionary from file
args: Parsed command line arguments
Returns:
Updated arguments namespace
"""
# Map config keys to argument names
config_mapping = {
'input': 'i',
'output': 'formats',
'client': 'client',
'validate': 'validate',
'verbose': 'verbose',
'quiet': 'quiet',
'show_grid': 'show_grid',
'show_labels': 'show_labels',
'summary': 'summary',
}
defaults = config.get('defaults', {})
for config_key, arg_name in config_mapping.items():
if config_key in defaults:
# Only set if not explicitly provided on command line
if getattr(args, arg_name, None) is None:
setattr(args, arg_name, defaults[config_key])
return args
def create_parser() -> argparse.ArgumentParser:
"""
Create and configure the argument parser.
Returns:
Configured ArgumentParser instance
"""
parser = argparse.ArgumentParser(
prog='compgrapher',
description='Generate floating bar graphs from compensation market data.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
%(prog)s -i data.csv
%(prog)s -i data.csv html pdf png
%(prog)s -i data.csv --client "Acme Corp" --validate
%(prog)s --config config.yaml --verbose
For more information, visit: https://github.com/nstapc/compgrapher
'''
)
# Version
parser.add_argument(
'--version', '-V',
action='version',
version=f'%(prog)s {__version__}'
)
# Input/Output
parser.add_argument(
'-i',
type=str,
default='input/csv/example_table.csv',
help='Path to data file (supports .csv, .xls, .xlsx, .ods)',
metavar='FILE'
)
parser.add_argument(
'formats',
nargs='*',
default=['png'],
choices=['html', 'pdf', 'png', 'svg', 'jpg', 'jpeg', 'webp', 'eps', []],
help='Output format(s): html, pdf, png, svg, jpg, jpeg, webp, eps (default: png)',
metavar='FORMAT'
)
parser.add_argument(
'--client', '-c',
type=str,
help='Name of the employer to highlight (defaults to first employer in data)',
metavar='NAME'
)
# Configuration
parser.add_argument(
'--config',
type=str,
help='Path to YAML configuration file',
metavar='FILE'
)
# Validation
parser.add_argument(
'--validate',
action='store_true',
help='Run data validation checks and report issues'
)
parser.add_argument(
'--validate-only',
action='store_true',
help='Only validate data without generating graphs'
)
# Display options
parser.add_argument(
'--show-grid',
action='store_true',
default=True,
help='Show grid lines on graphs (default: True)'
)
parser.add_argument(
'--no-grid',
action='store_false',
dest='show_grid',
help='Hide grid lines on graphs'
)
parser.add_argument(
'--show-labels',
action='store_true',
default=False,
help='Show salary labels on bars'
)
parser.add_argument(
'--summary',
action='store_true',
help='Generate a summary statistics report'
)
# Logging
parser.add_argument(
'--verbose', '-v',
action='store_true',
help='Enable verbose output (debug level)'
)
parser.add_argument(
'--quiet', '-q',
action='store_true',
help='Suppress all output except errors'
)
parser.add_argument(
'--log-file',
type=str,
help='Write logs to specified file',
metavar='FILE'
)
return parser
def validate_args(args: argparse.Namespace) -> None:
"""
Validate command line arguments.
Args:
args: Parsed arguments
Raises:
ValueError: If arguments are invalid
"""
# Check input file exists
if not Path(args.i).exists():
raise ValueError(f"Input file not found: {args.i}")
# Check file extension is supported
ext = Path(args.i).suffix.lower()
if ext not in ['.csv', '.xls', '.xlsx', '.ods']:
raise ValueError(f"Unsupported file format: {ext}")
# Check for conflicting options
if args.verbose and args.quiet:
raise ValueError("Cannot use --verbose and --quiet together")
def run_cli(args: Optional[List[str]] = None) -> int:
"""
Main CLI entry point.
Args:
args: Optional list of arguments (uses sys.argv if None)
Returns:
Exit code (0 for success, non-zero for errors)
"""
parser = create_parser()
parsed_args = parser.parse_args(args)
# Load config file if specified
if parsed_args.config:
try:
config = load_config(parsed_args.config)
parsed_args = merge_config_with_args(config, parsed_args)
except (FileNotFoundError, yaml.YAMLError) as e:
print(f"Error loading config: {e}", file=sys.stderr)
return 1
# Setup logging
logger = setup_logging(
verbose=parsed_args.verbose,
quiet=parsed_args.quiet,
log_file=getattr(parsed_args, 'log_file', None)
)
try:
# Validate arguments
validate_args(parsed_args)
logger.info(f"Compgrapher v{__version__}")
logger.info(f"Input file: {parsed_args.i}")
output_formats = parsed_args.formats if parsed_args.formats else ['png']
logger.info(f"Output formats: {output_formats}")
# ------------------------------------------------------------------ #
# Data validation (--validate / --validate-only) #
# ------------------------------------------------------------------ #
if parsed_args.validate or parsed_args.validate_only:
from data_parser import CompensationDataParser, DataValidationError
logger.info("Running data validation...")
try:
dp = CompensationDataParser(parsed_args.i)
data, warnings = dp.process(validate=True)
if warnings:
logger.warning(f"Validation found {len(warnings)} issue(s):")
for w in warnings:
logger.warning(f" • {w}")
else:
logger.info("Validation passed — no issues found.")
except DataValidationError as exc:
logger.error(f"Validation error: {exc}")
return 1
if parsed_args.validate_only:
logger.info("--validate-only: skipping chart generation.")
return 0
# ------------------------------------------------------------------ #
# Chart generation #
# ------------------------------------------------------------------ #
from main import process
show_grid = getattr(parsed_args, 'show_grid', True)
show_labels = getattr(parsed_args, 'show_labels', False)
generate_summary = getattr(parsed_args, 'summary', False)
process(
file_path=parsed_args.i,
output_formats=output_formats,
client_name=getattr(parsed_args, 'client', None),
show_labels=show_labels,
show_grid=show_grid,
generate_summary=generate_summary,
)
logger.info("Processing complete!")
return 0
except ValueError as e:
logger.error(f"Validation error: {e}")
return 1
except FileNotFoundError as e:
logger.error(f"File not found: {e}")
return 1
except SystemExit as e:
# process() calls sys.exit() on unrecoverable errors; propagate the code.
return int(e.code) if e.code is not None else 1
except Exception as e:
logger.exception(f"Unexpected error: {e}")
return 1
def main():
"""Console script entry point."""
sys.exit(run_cli())
if __name__ == '__main__':
main()