summaryrefslogtreecommitdiffstats
path: root/meta/lib
diff options
context:
space:
mode:
Diffstat (limited to 'meta/lib')
-rw-r--r--meta/lib/rootfspostcommands.py44
1 files changed, 44 insertions, 0 deletions
diff --git a/meta/lib/rootfspostcommands.py b/meta/lib/rootfspostcommands.py
new file mode 100644
index 0000000000..6a9b8b47b7
--- /dev/null
+++ b/meta/lib/rootfspostcommands.py
@@ -0,0 +1,44 @@
1import os
2
3def sort_file(filename, mapping):
4 """
5 Sorts a passwd or group file based on the numeric ID in the third column.
6 If a mapping is given, the name from the first column is mapped via that
7 dictionary instead (necessary for /etc/shadow and /etc/gshadow). If not,
8 a new mapping is created on the fly and returned.
9 """
10 new_mapping = {}
11 with open(filename, 'rb+') as f:
12 lines = f.readlines()
13 # No explicit error checking for the sake of simplicity. /etc
14 # files are assumed to be well-formed, causing exceptions if
15 # not.
16 for line in lines:
17 entries = line.split(b':')
18 name = entries[0]
19 if mapping is None:
20 id = int(entries[2])
21 else:
22 id = mapping[name]
23 new_mapping[name] = id
24 # Sort by numeric id first, with entire line as secondary key
25 # (just in case that there is more than one entry for the same id).
26 lines.sort(key=lambda line: (new_mapping[line.split(b':')[0]], line))
27 # We overwrite the entire file, i.e. no truncate() necessary.
28 f.seek(0)
29 f.write(b''.join(lines))
30 return new_mapping
31
32def sort_passwd(sysconfdir):
33 """
34 Sorts passwd and group files in a rootfs /etc directory by ID.
35 """
36 for suffix in '', '-':
37 for main, shadow in (('passwd', 'shadow'),
38 ('group', 'gshadow')):
39 filename = os.path.join(sysconfdir, main + suffix)
40 if os.path.exists(filename):
41 mapping = sort_file(filename, None)
42 filename = os.path.join(sysconfdir, shadow + suffix)
43 if os.path.exists(filename):
44 sort_file(filename, mapping)