| 1 |
#!/usr/bin/python |
| 2 |
# SPDX-License-Identifier: MIT-0 |
| 3 |
|
| 4 |
""" |
| 5 |
|
| 6 |
Proof-of-concept systemd environment generator that makes sure that bin dirs |
| 7 |
are always after matching sbin dirs in the path. |
| 8 |
(Changes /sbin:/bin:/foo/bar to /bin:/sbin:/foo/bar.) |
| 9 |
|
| 10 |
This generator shows how to override the configuration possibly created by |
| 11 |
earlier generators. It would be easier to write in bash, but let's have it |
| 12 |
in Python just to prove that we can, and to serve as a template for more |
| 13 |
interesting generators. |
| 14 |
|
| 15 |
""" |
| 16 |
|
| 17 |
import os |
| 18 |
import pathlib |
| 19 |
|
| 20 |
|
| 21 |
def rearrange_bin_sbin(path): |
| 22 |
"""Make sure any pair of …/bin, …/sbin directories is in this order |
| 23 |
|
| 24 |
>>> rearrange_bin_sbin('/bin:/sbin:/usr/sbin:/usr/bin') |
| 25 |
'/bin:/sbin:/usr/bin:/usr/sbin' |
| 26 |
""" |
| 27 |
items = [pathlib.Path(p) for p in path.split(':')] |
| 28 |
for i in range(len(items)): |
| 29 |
if 'sbin' in items[i].parts: |
| 30 |
ind = items[i].parts.index('sbin') |
| 31 |
bin = pathlib.Path(*items[i].parts[:ind], 'bin', *items[i].parts[ind + 1 :]) |
| 32 |
if bin in items[i + 1 :]: |
| 33 |
j = i + 1 + items[i + 1 :].index(bin) |
| 34 |
items[i], items[j] = items[j], items[i] |
| 35 |
return ':'.join(p.as_posix() for p in items) |
| 36 |
|
| 37 |
|
| 38 |
if __name__ == '__main__': |
| 39 |
# This should be always set. If it is not, we will just crash, which is OK too. |
| 40 |
path = os.environ['PATH'] |
| 41 |
new = rearrange_bin_sbin(path) |
| 42 |
if new != path: |
| 43 |
print(f'PATH={new}') |