forked from cxcsds/ciao-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mk_script_tarfile
executable file
·257 lines (197 loc) · 7.18 KB
/
mk_script_tarfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python
"""Usage:
./mk_script_tarfile <version string>
Aim:
Create the tar file for the contributed scripts package, using
the dotted version string, which should be 4.14.0 or 4.14.dev
(adjust version appropriately).
The VERSION file (ciao-<>/contrib/VERSION.CIAO_scripts) is not
tracked by git.
The approach taken by this script has changed - it was manual, then
based on setuptools - but now with setuptools moving to a buildm
rather than install, system we are going back to running things
manually.
Files or directories called tests are not included in the tar
file. This may be changed in the future (it may be useful to
be able to run tests from an installed version), but the tests
are currently very ad-hoc so it's not worth it.
"""
from collections import defaultdict
import glob
import os
from pathlib import Path
import shutil
import subprocess as sbp
import sys
import time
def build_dist(version, dirname, outdir, python="python3.10"):
"""Build contrib scripts package into a separate temp dir"""
outdir = Path(outdir)
outdir /= dirname
if outdir.exists():
raise OSError(f"Exists: {outdir}")
outdir /= "contrib"
if outdir.exists():
raise OSError(f"Exists: {outdir}")
# This uses the default mode for the parent directories.
#
outdir.mkdir(parents=True)
# Copy directories over to this directory
#
for basedir in ["bin", "share/doc/xml", "share/xspec/install", "data", "config", "param"]:
newdir = outdir / basedir
newdir.mkdir(parents=True)
nfiles = 0
for infile in glob.glob(f"{basedir}/*"):
if infile.endswith('~'):
continue
bname = os.path.basename(infile)
if bname.startswith('#'):
continue
shutil.copy2(infile, str(outdir / infile))
nfiles += 1
print(f'Copy to {basedir}: {nfiles} files')
# Create the lib structure. Unlike the other directories here we have
# to recurse into directories.
#
libdir = outdir / "lib" / python / "site-packages"
libdir.mkdir(parents=True)
for infile in ["lightcurves.py", "color_color.py"]:
shutil.copy2(infile, str(libdir / infile))
for basedir in ['ciao_contrib', 'coords', 'crates_contrib', 'dax',
'sherpa_contrib']:
for dirpath, dirnames, filenames in os.walk(basedir):
newdir = libdir / dirpath
newdir.mkdir()
# copy over the files
nfiles = 0
for infile in filenames:
if infile.endswith('~') or infile.startswith('#'):
continue
shutil.copy2(f'{dirpath}/{infile}', str(newdir / infile))
nfiles += 1
print(f'Copy to lib/{python}/site-packages/{dirpath}: {nfiles} files')
# Create the egg info file: is it needed?
#
if python == 'python':
raise RuntimeError("What should the egg version be now?")
pyver = python[6:]
eggfile = libdir / f"ciao_contrib-{version}-py{pyver}.egg-info"
with open(eggfile, 'wt') as fh:
fh.write(f'''Metadata-Version: 1.0
Name: ciao-contrib
Version: {version}
Summary: CIAO Contributed scripts
Home-page: https://github.com/cxcsds/ciao-contrib/
Author: CXCSDS and Friends
Author-email: [email protected]
License: GNU GPL v3
Description: UNKNOWN
Platform: UNKNOWN
''')
# Need to ensure all the bin files have a valid shebang - fortunately we
# don't need to replace anything so this is more a check.
#
scripts = defaultdict(int)
for infile in glob.glob(f"{outdir}/bin/*"):
firstline = open(infile, 'rt').readline().rstrip()
if not firstline.startswith('#!'):
raise OSError(f"shebang line for {infile}: {firstline}")
toks = firstline[2:].lstrip().split()
if (len(toks) == 1) and (toks[0] in ['/bin/sh', '/bin/bash']):
scripts[toks[0]] += 1
continue
if len(toks) != 2:
raise OSError(f"shebang line for {infile}: {firstline}")
if toks[0] != '/usr/bin/env':
raise OSError(f"shebang line for {infile}: {firstline}")
scripts[toks[1]] += 1
print("Script breakdown:")
for k, v in scripts.items():
print(f" {k:10s}: {v}")
print("")
# libs
# Copy files over
#
for infile in ["Changes.CIAO_scripts"]: #, "README_CIAO_scripts"]:
shutil.copy2(infile, str(outdir / infile))
# Create version file
#
with open(outdir / 'VERSION.CIAO_scripts', 'wt') as fh:
datestr = f"scripts {version} "
datestr += time.strftime("%A, %B %e, %Y")
fh.write(datestr)
fh.write('\n')
print(f"Updated VERSION file: {datestr}")
def make_tarfile(tarfilegz, dname):
"""Create versioned tar file"""
print(f"Building {tarfilegz}")
# This does not keep soft links.
#
# sbp.check_call(["tar", "chf", tarfile, "./" + cver["root"]])
#
args = ["tar"]
for ename in [".gitignore", "tests", "__pycache__"]:
args.append("--exclude={}".format(ename))
args.extend(["-czf", tarfilegz, f"./{dname}"])
sbp.check_call(args)
print(f"\nCreated: {tarfilegz}")
def is_int(x):
try:
v = int(x)
except ValueError:
sys.stderr.write("ERROR: version string should be 4.14.0 or 4.14.dev\n")
sys.exit(1)
if v < 1:
sys.stderr.write("ERROR: major and minor terms must be >= 1\n")
sys.exit(1)
def is_micro(x):
if x.upper() == 'DEV':
return 'DEV'
try:
v = int(x)
except ValueError:
sys.stderr.write("ERROR: version string should be 4.14.0 or 4.14.dev\n")
sys.exit(1)
if v < 0:
sys.stderr.write("ERROR: micro terms must be >= 0\n")
sys.exit(1)
return x
if __name__ == "__main__":
nargs = len(sys.argv)
if nargs != 2:
sys.stderr.write(f"Usage: {sys.argv[0]} <release>\n\n")
sys.stderr.write(f"Examples:\n")
sys.stderr.write(f" {sys.argv[0]} 4.14.0\n")
sys.stderr.write(f" {sys.argv[0]} 4.14.dev\n")
sys.stderr.write('\n')
sys.exit(1)
userversion = sys.argv[1]
toks = userversion.split('.')
if len(toks) != 3:
sys.stderr.write("ERROR: version string should be 4.14.0 or 4.14.dev\n")
sys.exit(1)
is_int(toks[0])
is_int(toks[1])
major = toks[0]
minor = toks[1]
micro = is_micro(toks[2])
dirname = f"ciao-{major}.{minor}"
version = f"{major}.{minor}.{micro}"
cwd = os.getcwd()
tarfile = f"{dirname}-contrib-{micro}.tar"
tarfile = os.path.join(cwd, tarfile)
tarfilegz = f'{tarfile}.gz'
if micro != 'DEV':
if os.path.exists(tarfile) or os.path.exists(tarfilegz):
sys.stderr.write("ERROR: output file already exists\n")
sys.stderr.write(f" {tarfile}\n")
sys.stderr.write(f" {tarfilegz}\n")
sys.stderr.write(" Does the version number need updating?")
sys.stderr.write("\n\n")
sys.exit(1)
from tempfile import TemporaryDirectory
with TemporaryDirectory(prefix=dirname) as tmpdir:
build_dist(version, dirname, tmpdir)
os.chdir(tmpdir)
make_tarfile(tarfilegz, dirname)