strif 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- strif-1.0.0.dist-info/LICENSE +202 -0
- strif-1.0.0.dist-info/METADATA +31 -0
- strif-1.0.0.dist-info/RECORD +6 -0
- strif-1.0.0.dist-info/WHEEL +5 -0
- strif-1.0.0.dist-info/top_level.txt +1 -0
- strif.py +490 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright {yyyy} {name of copyright owner}
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: strif
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tiny, useful lib for strings and files
|
|
5
|
+
Home-page: https://github.com/jlevy/strif
|
|
6
|
+
Author: Joshua Levy
|
|
7
|
+
License: Apache 2
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
13
|
+
Classifier: Operating System :: POSIX
|
|
14
|
+
Classifier: Operating System :: Unix
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Utilities
|
|
24
|
+
Classifier: Topic :: Software Development
|
|
25
|
+
Requires-Python: >=3.6,<4.0
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
Strif is a tiny (<1000 loc) library of string and file utilities for Python 3.6+.
|
|
30
|
+
|
|
31
|
+
More information: https://github.com/jlevy/strif
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
strif.py,sha256=-prTCpuwjHX9SeDGMdQZqZdNxpP5j9LFW3_FHBJhb7A,14818
|
|
2
|
+
strif-1.0.0.dist-info/LICENSE,sha256=xllut76FgcGL5zbIRvuRc7aezPbvlMUTWJPsVr2Sugg,11358
|
|
3
|
+
strif-1.0.0.dist-info/METADATA,sha256=qpPgmmBjcBLu6MeZpw7FLWIojaYSt1Azo1CHe9FEmQM,1147
|
|
4
|
+
strif-1.0.0.dist-info/WHEEL,sha256=cpQTJ5IWu9CdaPViMhC9YzF8gZuS5-vlfoFihTBC86A,91
|
|
5
|
+
strif-1.0.0.dist-info/top_level.txt,sha256=O-shGNa3EMM4UEJfuO9FItCha5wSUneLiKec3grlhQM,6
|
|
6
|
+
strif-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
strif
|
strif.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Strif is a tiny (<1000 loc) library of string and file utilities for Python 3.6+.
|
|
3
|
+
|
|
4
|
+
More information: https://github.com/jlevy/strif
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from string import Template
|
|
8
|
+
import re
|
|
9
|
+
import os
|
|
10
|
+
import errno
|
|
11
|
+
import random
|
|
12
|
+
import shutil
|
|
13
|
+
import shlex
|
|
14
|
+
import tempfile
|
|
15
|
+
import hashlib
|
|
16
|
+
import codecs
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from datetime import datetime
|
|
19
|
+
|
|
20
|
+
__author__ = "jlevy"
|
|
21
|
+
|
|
22
|
+
VERSION = "1.0.0"
|
|
23
|
+
DESCRIPTION = "Tiny, useful lib for strings and files"
|
|
24
|
+
LONG_DESCRIPTION = __doc__
|
|
25
|
+
|
|
26
|
+
# The subprocess module has known threading issues, so prefer subprocess32, but as a soft dependency.
|
|
27
|
+
try:
|
|
28
|
+
import subprocess32 as subprocess # type: ignore
|
|
29
|
+
except ImportError:
|
|
30
|
+
import subprocess
|
|
31
|
+
|
|
32
|
+
# A pre-opened handle to /dev/null.
|
|
33
|
+
DEV_NULL = open(os.devnull, "wb")
|
|
34
|
+
|
|
35
|
+
BACKUP_SUFFIX = ".bak"
|
|
36
|
+
TIMESTAMP_VAR = "{timestamp}"
|
|
37
|
+
|
|
38
|
+
_RANDOM = random.SystemRandom()
|
|
39
|
+
_RANDOM.seed()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
#
|
|
43
|
+
# ---- Identifiers and base36 encodings ----
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def new_uid(bits=64):
|
|
47
|
+
"""
|
|
48
|
+
A random alphanumeric value with at least the specified bits of randomness. We use base 36,
|
|
49
|
+
i.e. not case sensitive. Note this makes it suitable for filenames even on case-insensitive disks.
|
|
50
|
+
"""
|
|
51
|
+
return "".join(
|
|
52
|
+
_RANDOM.sample("0123456789abcdefghijklmnopqrstuvwxyz", int(bits / 5.16) + 1)
|
|
53
|
+
) # log(26 + 10)/log(2) = 5.16
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def iso_timestamp():
|
|
57
|
+
"""
|
|
58
|
+
ISO timestamp. With the Z for usual clarity.
|
|
59
|
+
Example: 2015-09-12T08:41:12.397217Z
|
|
60
|
+
"""
|
|
61
|
+
return datetime.now().isoformat() + "Z"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def new_timestamped_uid(bits=32):
|
|
65
|
+
"""
|
|
66
|
+
A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of
|
|
67
|
+
randomness. The advantage of this is it sorts nicely by time, while still being unique.
|
|
68
|
+
Example: 20150912T084555Z-378465-43vtwbx
|
|
69
|
+
"""
|
|
70
|
+
return "%s-%s" % (
|
|
71
|
+
re.sub(r"[^\w.]", "", datetime.now().isoformat()).replace(".", "Z-"),
|
|
72
|
+
new_uid(bits),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_NON_ALPHANUM_CHARS = re.compile("[^a-z0-9]+", re.IGNORECASE)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def clean_alphanum(string, max_length=None):
|
|
80
|
+
"""
|
|
81
|
+
Convert a string to a clean, readable identifier that includes the (first) alphanumeric
|
|
82
|
+
characters of the given string.
|
|
83
|
+
|
|
84
|
+
This mapping is for readability only, and so can easily have collisions on different inputs.
|
|
85
|
+
"""
|
|
86
|
+
return _NON_ALPHANUM_CHARS.sub("_", string)[:max_length]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def clean_alphanum_hash(string, max_length=64, max_hash_len=None):
|
|
90
|
+
"""
|
|
91
|
+
Convert a string to a clean, readable identifier that includes the (first) alphanumeric
|
|
92
|
+
characters of the given string.
|
|
93
|
+
|
|
94
|
+
This includes a SHA1 hash so collisions are unlikely.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
hash = hash_string_base36(string, algorithm="sha1")
|
|
98
|
+
if max_hash_len:
|
|
99
|
+
hash = hash[:max_hash_len]
|
|
100
|
+
if max_length < len(hash) + 1:
|
|
101
|
+
return hash
|
|
102
|
+
else:
|
|
103
|
+
return clean_alphanum(string, max_length=max_length - len(hash)) + "_" + hash
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def base36_encode(n):
|
|
107
|
+
"""
|
|
108
|
+
Base 36 encode an integer.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
chars = "0123456789abcdefghijklmnopqrstuvwxyz"
|
|
112
|
+
encoded = ""
|
|
113
|
+
|
|
114
|
+
while n > 0:
|
|
115
|
+
n, remainder = divmod(n, 36)
|
|
116
|
+
encoded = chars[remainder] + encoded
|
|
117
|
+
|
|
118
|
+
return encoded
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def hash_string_base36(string, algorithm="sha1"):
|
|
122
|
+
"""
|
|
123
|
+
Hash string and return in base 36, which is good for short, friendly identifiers.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
h = hashlib.new(algorithm)
|
|
127
|
+
h.update(string.encode("utf8"))
|
|
128
|
+
return base36_encode(int.from_bytes(h.digest(), byteorder="big"))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
#
|
|
132
|
+
# ---- Abbreviations ----
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def abbreviate_str(string, max_len=80, indicator="…"):
|
|
136
|
+
"""
|
|
137
|
+
Abbreviate a string, adding an indicator like an ellipsis if required. Set max_len to
|
|
138
|
+
None or 0 not to truncate items.
|
|
139
|
+
"""
|
|
140
|
+
if not string or not max_len or len(string) <= max_len:
|
|
141
|
+
return string
|
|
142
|
+
elif max_len <= len(indicator):
|
|
143
|
+
return string[0:max_len]
|
|
144
|
+
else:
|
|
145
|
+
return string[0 : max_len - len(indicator)] + indicator
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="…"):
|
|
149
|
+
"""
|
|
150
|
+
Abbreviate a list, truncating each element and adding an indicator at the end if the
|
|
151
|
+
whole list was truncated. Set item_max_len to None or 0 not to truncate items.
|
|
152
|
+
"""
|
|
153
|
+
if not items:
|
|
154
|
+
return items
|
|
155
|
+
else:
|
|
156
|
+
shortened = [
|
|
157
|
+
abbreviate_str("%s" % item, max_len=item_max_len) for item in items[0:max_items]
|
|
158
|
+
]
|
|
159
|
+
if len(items) > max_items:
|
|
160
|
+
shortened.append(indicator)
|
|
161
|
+
return joiner.join(shortened)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
#
|
|
165
|
+
# ---- Templating ----
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def expand_variables(template_str, value_map, transformer=None):
|
|
169
|
+
"""
|
|
170
|
+
Expand a template string like "blah blah $FOO blah" using given value mapping.
|
|
171
|
+
"""
|
|
172
|
+
if template_str is None:
|
|
173
|
+
return None
|
|
174
|
+
else:
|
|
175
|
+
if transformer is None:
|
|
176
|
+
transformer = lambda v: v # noqa: E731
|
|
177
|
+
try:
|
|
178
|
+
# Don't bother iterating items for Python 2+3 compatibility.
|
|
179
|
+
transformed_value_map = {k: transformer(value_map[k]) for k in value_map}
|
|
180
|
+
return Template(template_str).substitute(transformed_value_map)
|
|
181
|
+
except Exception as e:
|
|
182
|
+
raise ValueError(
|
|
183
|
+
"could not expand variable names in command '%s': %s" % (template_str, e)
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def shell_expand_variables(template_str, value_map):
|
|
188
|
+
"""
|
|
189
|
+
Expand a shell template string like "cp $SOURCE $TARGET/blah", also quoting values as needed
|
|
190
|
+
to ensure shell safety.
|
|
191
|
+
"""
|
|
192
|
+
return expand_variables(template_str, value_map, transformer=shlex.quote)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def shell_expand_to_popen(template, values):
|
|
196
|
+
"""
|
|
197
|
+
Expand a template like "cp $SOURCE $TARGET/blah" into a list of popen arguments.
|
|
198
|
+
"""
|
|
199
|
+
return [expand_variables(item, values) for item in shlex.split(template)]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
#
|
|
203
|
+
# ---- File operations ----
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _expand_backup_suffix(backup_suffix):
|
|
207
|
+
return (
|
|
208
|
+
backup_suffix.replace(TIMESTAMP_VAR, new_timestamped_uid())
|
|
209
|
+
if TIMESTAMP_VAR in backup_suffix
|
|
210
|
+
else backup_suffix
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def move_to_backup(path, backup_suffix=BACKUP_SUFFIX):
|
|
215
|
+
"""
|
|
216
|
+
Move the given file or directory to the same name, with a backup suffix.
|
|
217
|
+
If backup_suffix not supplied, move it to the extension ".bak".
|
|
218
|
+
In backup_suffix, the string "{timestamp}", if present, will be replaced
|
|
219
|
+
by a new_timestamped_uid(), allowing infinite numbers of timestamped backups.
|
|
220
|
+
If backup_suffix is supplied and is None, don't do anything.
|
|
221
|
+
|
|
222
|
+
Important:
|
|
223
|
+
Without "{timestamp}", earlier backup files and directories, if they exist,
|
|
224
|
+
will be clobbered!
|
|
225
|
+
"""
|
|
226
|
+
if backup_suffix and os.path.exists(path):
|
|
227
|
+
backup_path = path + _expand_backup_suffix(backup_suffix)
|
|
228
|
+
# Some messy corner cases need to be handled for existing backups.
|
|
229
|
+
# TODO: Note if this is a directory, and we do this twice at once, there is a potential race
|
|
230
|
+
# that could leave one backup inside the other.
|
|
231
|
+
if os.path.islink(backup_path):
|
|
232
|
+
os.unlink(backup_path)
|
|
233
|
+
elif os.path.isdir(backup_path):
|
|
234
|
+
shutil.rmtree(backup_path)
|
|
235
|
+
shutil.move(path, backup_path)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def make_all_dirs(path, mode=0o777):
|
|
239
|
+
"""
|
|
240
|
+
Ensure local dir, with all its parent dirs, are created.
|
|
241
|
+
Unlike os.makedirs(), will not fail if the path already exists.
|
|
242
|
+
"""
|
|
243
|
+
# Avoid races inherent to doing this in two steps (check then create).
|
|
244
|
+
# Python 3 has exist_ok but the approach below works for Python 2+3.
|
|
245
|
+
# https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
|
|
246
|
+
try:
|
|
247
|
+
os.makedirs(path, mode=mode)
|
|
248
|
+
except OSError as e:
|
|
249
|
+
if e.errno == errno.EEXIST and os.path.isdir(path):
|
|
250
|
+
pass
|
|
251
|
+
else:
|
|
252
|
+
raise
|
|
253
|
+
return path
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def make_parent_dirs(path, mode=0o777):
|
|
257
|
+
"""
|
|
258
|
+
Ensure parent directories of a file are created as needed.
|
|
259
|
+
"""
|
|
260
|
+
parent = os.path.dirname(path)
|
|
261
|
+
if parent:
|
|
262
|
+
make_all_dirs(parent, mode)
|
|
263
|
+
return path
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@contextmanager
|
|
267
|
+
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"):
|
|
268
|
+
"""
|
|
269
|
+
A context manager for convenience in writing a file or directory in an atomic way. Set up
|
|
270
|
+
a temporary name, then rename it after the operation is done, optionally making a backup of
|
|
271
|
+
the previous file or directory, if present.
|
|
272
|
+
"""
|
|
273
|
+
if dest_path == os.devnull:
|
|
274
|
+
# Handle the (probably rare) case of writing to /dev/null.
|
|
275
|
+
yield dest_path
|
|
276
|
+
else:
|
|
277
|
+
tmp_path = ("%s" + suffix) % (dest_path, new_uid())
|
|
278
|
+
if make_parents:
|
|
279
|
+
make_parent_dirs(tmp_path)
|
|
280
|
+
|
|
281
|
+
yield tmp_path
|
|
282
|
+
|
|
283
|
+
# Note this is not in a finally block, so that result won't be renamed to final location
|
|
284
|
+
# in case of abnormal exit.
|
|
285
|
+
if not os.path.exists(tmp_path):
|
|
286
|
+
raise IOError(
|
|
287
|
+
"failure in writing file '%s': target file '%s' missing" % (dest_path, tmp_path)
|
|
288
|
+
)
|
|
289
|
+
if backup_suffix:
|
|
290
|
+
move_to_backup(dest_path, backup_suffix=backup_suffix)
|
|
291
|
+
# If the target already exists, and is a directory, it has to be removed.
|
|
292
|
+
if os.path.isdir(dest_path):
|
|
293
|
+
shutil.rmtree(dest_path)
|
|
294
|
+
shutil.move(tmp_path, dest_path)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False):
|
|
298
|
+
"""
|
|
299
|
+
A context manager for convenience in creating a temporary file,
|
|
300
|
+
which is deleted when exiting the context.
|
|
301
|
+
|
|
302
|
+
Usage:
|
|
303
|
+
with temp_output_file() as (fd, path):
|
|
304
|
+
...
|
|
305
|
+
"""
|
|
306
|
+
return _temp_output(
|
|
307
|
+
False,
|
|
308
|
+
prefix=prefix,
|
|
309
|
+
suffix=suffix,
|
|
310
|
+
dir=dir,
|
|
311
|
+
make_parents=make_parents,
|
|
312
|
+
always_clean=always_clean,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False):
|
|
317
|
+
"""
|
|
318
|
+
A context manager for convenience in creating a temporary directory,
|
|
319
|
+
which is deleted when exiting the context.
|
|
320
|
+
|
|
321
|
+
Usage:
|
|
322
|
+
with temp_output_dir() as dirname:
|
|
323
|
+
...
|
|
324
|
+
"""
|
|
325
|
+
return _temp_output(
|
|
326
|
+
True,
|
|
327
|
+
prefix=prefix,
|
|
328
|
+
suffix=suffix,
|
|
329
|
+
dir=dir,
|
|
330
|
+
make_parents=make_parents,
|
|
331
|
+
always_clean=always_clean,
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@contextmanager
|
|
336
|
+
def _temp_output(is_dir, prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False):
|
|
337
|
+
if dir and make_parents:
|
|
338
|
+
make_all_dirs(dir)
|
|
339
|
+
|
|
340
|
+
if is_dir:
|
|
341
|
+
path = tempfile.mkdtemp(prefix=prefix, suffix=suffix, dir=dir)
|
|
342
|
+
result = path
|
|
343
|
+
else:
|
|
344
|
+
(fd, path) = tempfile.mkstemp(prefix=prefix, suffix=suffix, dir=dir)
|
|
345
|
+
result = (fd, path)
|
|
346
|
+
|
|
347
|
+
def clean():
|
|
348
|
+
try:
|
|
349
|
+
rmtree_or_file(path, ignore_errors=True)
|
|
350
|
+
except OSError:
|
|
351
|
+
pass
|
|
352
|
+
|
|
353
|
+
if always_clean:
|
|
354
|
+
try:
|
|
355
|
+
yield result
|
|
356
|
+
finally:
|
|
357
|
+
clean()
|
|
358
|
+
else:
|
|
359
|
+
yield result
|
|
360
|
+
clean()
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def read_string_from_file(path, encoding="utf8"):
|
|
364
|
+
"""
|
|
365
|
+
Read entire contents of file into a string.
|
|
366
|
+
"""
|
|
367
|
+
with codecs.open(path, "rb", encoding=encoding) as f:
|
|
368
|
+
value = f.read()
|
|
369
|
+
return value
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def write_string_to_file(
|
|
373
|
+
path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8"
|
|
374
|
+
):
|
|
375
|
+
"""
|
|
376
|
+
Write entire file with given string contents, atomically. Keeps backup by default.
|
|
377
|
+
"""
|
|
378
|
+
with atomic_output_file(
|
|
379
|
+
path, make_parents=make_parents, backup_suffix=backup_suffix
|
|
380
|
+
) as tmp_path:
|
|
381
|
+
with codecs.open(tmp_path, "wb", encoding=encoding) as f:
|
|
382
|
+
f.write(string)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def set_file_mtime(path, mtime, atime=None):
|
|
386
|
+
"""Set access and modification times on a file."""
|
|
387
|
+
if not atime:
|
|
388
|
+
atime = mtime
|
|
389
|
+
f = open(path, "a")
|
|
390
|
+
try:
|
|
391
|
+
os.utime(path, (atime, mtime))
|
|
392
|
+
finally:
|
|
393
|
+
f.close()
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None):
|
|
397
|
+
"""
|
|
398
|
+
Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps.
|
|
399
|
+
"""
|
|
400
|
+
with atomic_output_file(
|
|
401
|
+
dest_path, make_parents=make_parents, backup_suffix=backup_suffix
|
|
402
|
+
) as tmp_path:
|
|
403
|
+
shutil.copyfile(source_path, tmp_path)
|
|
404
|
+
set_file_mtime(tmp_path, os.path.getmtime(source_path))
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def copytree_atomic(source_path, dest_path, make_parents=False, backup_suffix=None, symlinks=False):
|
|
408
|
+
"""
|
|
409
|
+
Copy a file or directory recursively, and atomically, reanaming file or top-level dir when done.
|
|
410
|
+
Unlike shutil.copytree, this will not fail on a file.
|
|
411
|
+
"""
|
|
412
|
+
if os.path.isdir(source_path):
|
|
413
|
+
with atomic_output_file(
|
|
414
|
+
dest_path, make_parents=make_parents, backup_suffix=backup_suffix
|
|
415
|
+
) as tmp_path:
|
|
416
|
+
shutil.copytree(source_path, tmp_path, symlinks=symlinks)
|
|
417
|
+
else:
|
|
418
|
+
copyfile_atomic(
|
|
419
|
+
source_path, dest_path, make_parents=make_parents, backup_suffix=backup_suffix
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def movefile(source_path, dest_path, make_parents=False, backup_suffix=None):
|
|
424
|
+
"""
|
|
425
|
+
Move file. With a few extra options.
|
|
426
|
+
"""
|
|
427
|
+
if make_parents:
|
|
428
|
+
make_parent_dirs(dest_path)
|
|
429
|
+
move_to_backup(dest_path, backup_suffix=backup_suffix) # type: ignore
|
|
430
|
+
shutil.move(source_path, dest_path)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def rmtree_or_file(path, ignore_errors=False, onerror=None):
|
|
434
|
+
"""
|
|
435
|
+
rmtree fails on files or symlinks. This removes the target, whatever it is.
|
|
436
|
+
"""
|
|
437
|
+
# TODO: Could add an rsync-based delete, as in
|
|
438
|
+
# https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143
|
|
439
|
+
if ignore_errors and not os.path.exists(path):
|
|
440
|
+
return
|
|
441
|
+
if os.path.isdir(path) and not os.path.islink(path):
|
|
442
|
+
shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror)
|
|
443
|
+
else:
|
|
444
|
+
os.unlink(path)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def chmod_native(path, mode_expression, recursive=False):
|
|
448
|
+
"""
|
|
449
|
+
This is ugly and will only work on POSIX, but the built-in Python os.chmod support
|
|
450
|
+
is very minimal, and neither supports fast recursive chmod nor "+X" type expressions,
|
|
451
|
+
both of which are slow for large trees. So just shell out.
|
|
452
|
+
"""
|
|
453
|
+
popenargs = ["chmod"]
|
|
454
|
+
if recursive:
|
|
455
|
+
popenargs.append("-R")
|
|
456
|
+
popenargs.append(mode_expression)
|
|
457
|
+
popenargs.append(path)
|
|
458
|
+
subprocess.check_call(popenargs)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def file_sha1(path):
|
|
462
|
+
"""
|
|
463
|
+
Compute SHA1 hash of a file.
|
|
464
|
+
"""
|
|
465
|
+
sha1 = hashlib.sha1()
|
|
466
|
+
with open(path, "rb") as f:
|
|
467
|
+
while True:
|
|
468
|
+
block = f.read(2**10)
|
|
469
|
+
if not block:
|
|
470
|
+
break
|
|
471
|
+
sha1.update(block)
|
|
472
|
+
return sha1.hexdigest()
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
#
|
|
476
|
+
# --- Misc ---
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def dict_merge(*dict_list):
|
|
480
|
+
"""
|
|
481
|
+
Given zero or more dicts, shallow copy and merge them into a new dict, with
|
|
482
|
+
precedence to dictionary values later in the dict list.
|
|
483
|
+
Helpful mainly before Python 3.5.
|
|
484
|
+
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
|
|
485
|
+
https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations
|
|
486
|
+
"""
|
|
487
|
+
result = {}
|
|
488
|
+
for d in dict_list:
|
|
489
|
+
result.update(d)
|
|
490
|
+
return result
|