1 | #!/usr/bin/env python
|
---|
2 | #
|
---|
3 | # SPDX-FileCopyrightText: 2008 Martin Decky
|
---|
4 | # SPDX-FileCopyrightText: 2011 Martin Sucha
|
---|
5 | #
|
---|
6 | # SPDX-License-Identifier: BSD-3-Clause
|
---|
7 | #
|
---|
8 |
|
---|
9 | """
|
---|
10 | Utilities for filesystem image creators
|
---|
11 | """
|
---|
12 |
|
---|
13 | import os
|
---|
14 | import stat
|
---|
15 |
|
---|
16 | exclude_names = set(['.svn', '.bzr', '.git'])
|
---|
17 |
|
---|
18 | def align_up(size, alignment):
|
---|
19 | "Return size aligned up to alignment"
|
---|
20 |
|
---|
21 | if (size % alignment == 0):
|
---|
22 | return size
|
---|
23 |
|
---|
24 | return ((size // alignment) + 1) * alignment
|
---|
25 |
|
---|
26 | def count_up(size, alignment):
|
---|
27 | "Return units necessary to fit the size"
|
---|
28 |
|
---|
29 | if (size % alignment == 0):
|
---|
30 | return (size // alignment)
|
---|
31 |
|
---|
32 | return ((size // alignment) + 1)
|
---|
33 |
|
---|
34 | def num_of_trailing_bin_zeros(num):
|
---|
35 | "Return number of trailing zeros in binary representation"
|
---|
36 |
|
---|
37 | i = 0
|
---|
38 | if (num == 0): raise ValueError()
|
---|
39 | while num & 1 == 0:
|
---|
40 | i += 1
|
---|
41 | num = num >> 1
|
---|
42 | return i
|
---|
43 |
|
---|
44 | def get_bit(number, n):
|
---|
45 | "Return True if n-th least-significant bit is set in the given number"
|
---|
46 |
|
---|
47 | return bool((number >> n) & 1)
|
---|
48 |
|
---|
49 | def set_bit(number, n):
|
---|
50 | "Return the number with n-th least-significant bit set"
|
---|
51 |
|
---|
52 | return number | (1 << n)
|
---|
53 |
|
---|
54 | class ItemToPack:
|
---|
55 | "Stores information about one directory item to be added to the image"
|
---|
56 |
|
---|
57 | def __init__(self, parent, name):
|
---|
58 | self.parent = parent
|
---|
59 | self.name = name
|
---|
60 | self.path = os.path.join(parent, name)
|
---|
61 | self.stat = os.stat(self.path)
|
---|
62 | self.is_dir = stat.S_ISDIR(self.stat.st_mode)
|
---|
63 | self.is_file = stat.S_ISREG(self.stat.st_mode)
|
---|
64 | self.size = self.stat.st_size
|
---|
65 |
|
---|
66 | def listdir_items(path):
|
---|
67 | "Return a list of items to be packed inside a fs image"
|
---|
68 |
|
---|
69 | for name in os.listdir(path):
|
---|
70 | if name in exclude_names:
|
---|
71 | continue
|
---|
72 |
|
---|
73 | item = ItemToPack(path, name)
|
---|
74 |
|
---|
75 | if not (item.is_dir or item.is_file):
|
---|
76 | continue
|
---|
77 |
|
---|
78 | yield item
|
---|
79 |
|
---|
80 | def chunks(item, chunk_size):
|
---|
81 | "Iterate contents of a file in chunks of a given size"
|
---|
82 |
|
---|
83 | inf = open(item.path, 'rb')
|
---|
84 | rd = 0
|
---|
85 |
|
---|
86 | while (rd < item.size):
|
---|
87 | data = bytes(inf.read(chunk_size))
|
---|
88 | yield data
|
---|
89 | rd += len(data)
|
---|
90 |
|
---|
91 | inf.close()
|
---|