-
Notifications
You must be signed in to change notification settings - Fork 0
/
inplace.py
executable file
·51 lines (41 loc) · 1.27 KB
/
inplace.py
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
#!/usr/bin/env python3
import argparse, pathlib, shutil, subprocess, tempfile
def run_substituted_cmd(
cmd: list[str], file: pathlib.Path, placeholder: str
) -> bytes:
cmd = (
[str(file) if arg == placeholder else arg for arg in cmd]
if placeholder in cmd
else cmd + [str(file)]
)
return subprocess.run(cmd, capture_output=True, check=True).stdout
def replace_file(file: pathlib.Path, contents: bytes):
with tempfile.NamedTemporaryFile() as tmp:
tmp.write(contents)
tmp.flush()
shutil.copy(tmp.name, file)
def main():
parser = argparse.ArgumentParser(
description="Run any command on a list of files and overwrite them with the output."
)
parser.add_argument(
"-p",
"--placeholder",
default="%",
help="Placeholder for the file name (default: %)",
)
parser.add_argument(
"-f",
"--files",
type=pathlib.Path,
nargs="+",
required=True,
help="Files to edit (required)",
)
parser.add_argument("cmd", nargs="+")
opts = parser.parse_args()
for file in opts.files:
output = run_substituted_cmd(opts.cmd, file, opts.placeholder)
replace_file(file, output)
if __name__ == "__main__":
main()