Skip to content

Commit

Permalink
build: sort.py: add and require -i to edit in-place (netblue30#6290)
Browse files Browse the repository at this point in the history
Similarly to `sed -i` and `perl -i`.

This allows checking if sort.py correctly sorts the relevant lines in a
profile without having to overwrite it, which makes debugging and
testing easier (for example, in netblue30#6261).

Note: If it finds items that are not sorted, it still sorts them, prints
the diff and returns an error.
  • Loading branch information
kmk3 authored Mar 25, 2024
1 parent 7047e1a commit aa08aa1
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions contrib/sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
__doc__ = f"""\
Sort the arguments of commands in profiles.
Usage: {path.basename(argv[0])} [/path/to/profile ...]
Usage: {path.basename(argv[0])} [-i] [/path/to/profile ...]
The following commands are supported:
Expand All @@ -20,13 +20,14 @@
Note that this is only applicable to commands that support multiple arguments.
Keep in mind that this will overwrite your profile(s).
Options:
-i Edit the profile file(s) in-place.
Examples:
$ {argv[0]} MyAwesomeProfile.profile
$ {argv[0]} new_profile.profile second_new_profile.profile
$ {argv[0]} ~/.config/firejail/*.{{profile,inc,local}}
$ sudo {argv[0]} /etc/firejail/*.{{profile,inc,local}}
$ {argv[0]} -i MyAwesomeProfile.profile
$ {argv[0]} -i new_profile.profile second_new_profile.profile
$ {argv[0]} -i ~/.config/firejail/*.{{profile,inc,local}}
$ sudo {argv[0]} -i /etc/firejail/*.{{profile,inc,local}}
Exit Codes:
0: Success: No profiles needed fixing.
Expand Down Expand Up @@ -62,7 +63,7 @@ def sort_protocol(original_protocols):
return fixed_protocols[:-1]


def fix_profile(filename):
def check_profile(filename, overwrite):
with open(filename, "r+") as profile:
lines = profile.read().split("\n")
was_fixed = False
Expand All @@ -87,17 +88,24 @@ def fix_profile(filename):
f"{filename}:{lineno}:+{fixed_line}"
)
fixed_profile.append(fixed_line)

if was_fixed:
profile.seek(0)
profile.truncate()
profile.write("\n".join(fixed_profile))
profile.flush()
print(f"[ Fixed ] {filename}")
if overwrite:
profile.seek(0)
profile.truncate()
profile.write("\n".join(fixed_profile))
profile.flush()
print(f"[ Fixed ] {filename}")
return 101
return 0


def main(args):
overwrite = False
if len(args) > 0 and args[0] == "-i":
overwrite = True
args.pop(0)

if len(args) < 1:
print(__doc__, file=stderr)
return 2
Expand All @@ -108,9 +116,9 @@ def main(args):
for filename in args:
try:
if exit_code not in (1, 101):
exit_code = fix_profile(filename)
exit_code = check_profile(filename, overwrite)
else:
fix_profile(filename)
check_profile(filename, overwrite)
except FileNotFoundError as err:
print(f"[ Error ] {err}", file=stderr)
exit_code = 1
Expand Down

0 comments on commit aa08aa1

Please sign in to comment.