-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_cmd
More file actions
executable file
·54 lines (43 loc) · 1.26 KB
/
split_cmd
File metadata and controls
executable file
·54 lines (43 loc) · 1.26 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
#!/usr/bin/env python3
r"""
Split a bash command over several lines, using backslashes.
Example:
./split_cmd 'some_cmd --flag "afds df qq" arg2'
some_cmd \
--flag \
"afds df qq" \
arg2
"""
import sys
def join_first_two_parts(parts):
first_part = f"{parts[0]} {parts[1]}"
new_parts = [first_part] + parts[2:]
return new_parts
def main(original_command):
"""Splits a command string into a multi-line string with escaped newlines."""
parts = []
in_quotes = False
current_part = ""
for char in original_command:
if char == '"' or char == "'":
in_quotes = not in_quotes
current_part += char
elif char == " " and not in_quotes:
parts.append(current_part)
current_part = ""
else:
current_part += char
# In most cases we want at least one arg along with the binary.
parts = join_first_two_parts(parts)
# If it's a target.
if parts[1].startswith("//"):
parts = join_first_two_parts(parts)
if parts[1] == "--":
parts = join_first_two_parts(parts)
parts.append(current_part)
result = " \\\n ".join(parts)
print(result)
if __name__ == "__main__":
args = sys.argv[1:]
command = " ".join(args)
main(command)