-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
185 lines (151 loc) · 5.03 KB
/
cli.py
File metadata and controls
185 lines (151 loc) · 5.03 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
#!/usr/bin/env python3
"""
CEDARScript Editor CLI Interface
Provides command-line interface for executing CEDARScript commands
on code files using the CEDARScript Editor library.
"""
import sys
from pathlib import Path
from typing import Optional
import click
from cedarscript_ast_parser import CEDARScriptASTParser
from .cedarscript_editor import CEDARScriptEditor, CEDARScriptEditorException
from . import find_commands
@click.command(help="Execute CEDARScript commands on code files")
@click.option(
'--file', '-f',
type=click.File('r'),
help='Read CEDARScript commands from file'
)
@click.option(
'--root', '-r',
type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
default=Path.cwd(),
help='Base directory for file operations (default: current directory)'
)
@click.option(
'--quiet', '-q',
is_flag=True,
help='Minimal output (for scripting)'
)
@click.option(
'--check', '-c',
is_flag=True,
help='Syntax check only - parse commands without executing'
)
@click.option(
'--fenced', '-F',
is_flag=True,
default=False,
help='Require CEDARScript blocks to be fenced with ```CEDARScript (default: treat entire input as single block)'
)
@click.argument('command', required=False)
def main(
file: Optional[click.File],
root: Path,
quiet: bool,
check: bool,
fenced: bool,
command: Optional[str]
) -> None:
"""
CEDARScript Editor CLI
Execute CEDARScript commands to transform code files.
Examples:
\b
# Direct command
cedarscript "UPDATE myfile.py SET imports.append('import os')"
# From file (both short and long forms)
cedarscript -f commands.cedar
cedarscript --file commands.cedar
# From STDIN
cat commands.cedar | cedarscript
# With custom base directory
cedarscript -r /path/to/project -f commands.cedar
cedarscript --root /path/to/project -f commands.cedar
# Quiet mode for scripting
cedarscript -q -f commands.cedar
cedarscript --quiet -f commands.cedar
# Syntax check only
cedarscript -c -f commands.cedar
cedarscript --check -f commands.cedar
# With fenced requirement
cedarscript -F -f commands.cedar
cedarscript --fenced -f commands.cedar
# Mixed short and long flags
cedarscript -r /path/to -c -F --file commands.cedar
"""
try:
# Determine command source
commands = _get_commands_input(file, command, quiet)
if not commands.strip():
_echo_error("No CEDARScript commands provided", quiet)
sys.exit(1)
# Parse commands
if not quiet:
click.echo("Parsing CEDARScript commands...")
try:
parsed_commands = list(find_commands(commands, require_fenced=fenced))
except Exception as e:
_echo_error(f"Failed to parse CEDARScript: {e}", quiet)
sys.exit(1)
if not quiet:
click.echo(f"Parsed {len(parsed_commands)} command(s)")
# If syntax check only, exit here
if check:
if not quiet:
click.echo("Syntax check passed - commands are valid")
sys.exit(0)
# Execute commands
if not quiet:
click.echo(f"Executing commands in directory: {root}")
editor = CEDARScriptEditor(str(root))
results = editor.apply_commands(parsed_commands)
# Output results
if not quiet:
click.echo("\nResults:")
for result in results:
click.echo(f" {result}")
else:
# Quiet mode - just show success/failure
click.echo(f"Applied {len(results)} command(s)")
except CEDARScriptEditorException as e:
_echo_error(f"CEDARScript execution error: {e}", quiet)
sys.exit(2)
except KeyboardInterrupt:
_echo_error("Operation cancelled by user", quiet)
sys.exit(130)
except Exception as e:
_echo_error(f"Unexpected error: {e}", quiet)
sys.exit(3)
def _get_commands_input(
file: Optional[click.File],
command: Optional[str],
quiet: bool
) -> str:
"""
Determine the source of CEDARScript commands based on provided inputs.
Priority: command argument > file option > STDIN
"""
if command:
return command
if file:
return file.read()
# Check if STDIN has data (not a TTY)
if not sys.stdin.isatty():
try:
return sys.stdin.read()
except Exception as e:
_echo_error(f"Error reading from STDIN: {e}", quiet)
sys.exit(1)
return ""
def _echo_error(message: str, quiet: bool) -> None:
"""Echo error message with appropriate formatting."""
if quiet:
# In quiet mode, send errors to stderr but keep them brief
click.echo(f"Error: {message}", err=True)
else:
# In normal mode, use styled error output
click.echo(click.style(f"Error: {message}", fg='red'), err=True)
if __name__ == '__main__':
main()