2 # SPDX-License-Identifier: MIT-0
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.)
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.
20 def rearrange_bin_sbin(path
):
21 """Make sure any pair of …/bin, …/sbin directories is in this order
23 >>> rearrange_bin_sbin('/bin:/sbin:/usr/sbin:/usr/bin')
24 '/bin:/sbin:/usr/bin:/usr/sbin'
26 items
= [pathlib
.Path(p
) for p
in path
.split(':')]
27 for i
in range(len(items
)):
28 if 'sbin' in items
[i
].parts
:
29 ind
= items
[i
].parts
.index('sbin')
30 bin
= pathlib
.Path(*items
[i
].parts
[:ind
], 'bin', *items
[i
].parts
[ind
+1:])
31 if bin
in items
[i
+1:]:
32 j
= i
+ 1 + items
[i
+1:].index(bin
)
33 items
[i
], items
[j
] = items
[j
], items
[i
]
34 return ':'.join(p
.as_posix() for p
in items
)
36 if __name__
== '__main__':
37 path
= os
.environ
['PATH'] # This should be always set.
38 # If it's not, we'll just crash, which is OK too.
39 new
= rearrange_bin_sbin(path
)
41 print('PATH={}'.format(new
))