Tweak the text on API Docs intro page [skip appveyor]
[scons.git] / site_scons / zip_utils.py
blob90fd15319b9688bbe5163bb2b4cd954350cdd5e7
1 # SPDX-License-Identifier: MIT
3 # Copyright The SCons Foundation
5 """
6 Actions to zip and unzip, for working with SCons release bundles.
7 Action for creating a zipapp.
8 """
10 import os.path
11 import zipfile
12 import zipapp
15 def zipit(env, target, source):
16 """Action function to zip *source* into *target*
18 Values extracted from *env*:
19 *CD*: the directory to work in
20 *PSV*: the directory name to walk down to find the files
21 """
22 print(f"Zipping {target[0]}:")
24 def visit(arg, dirname, filenames):
25 for filename in filenames:
26 path = os.path.join(dirname, filename)
27 if os.path.isfile(path):
28 arg.write(path)
30 # default ZipFile compression is ZIP_STORED
31 zf = zipfile.ZipFile(str(target[0]), 'w', compression=zipfile.ZIP_DEFLATED)
32 olddir = os.getcwd()
33 os.chdir(env.Dir(env['CD']).abspath)
34 try:
35 for dirname, dirnames, filenames in os.walk(env['PSV']):
36 visit(zf, dirname, filenames)
37 finally:
38 os.chdir(olddir)
39 zf.close()
42 def unzipit(env, target, source):
43 """Action function to unzip *source*"""
45 print(f"Unzipping {source[0]}:")
46 zf = zipfile.ZipFile(str(source[0]), 'r')
47 for name in zf.namelist():
48 dest = os.path.join(env['UNPACK_ZIP_DIR'], name)
49 dir = os.path.dirname(dest)
50 os.makedirs(dir, exist_ok=True)
51 print(dest, name)
52 # if the file exists, then delete it before writing
53 # to it so that we don't end up trying to write to a symlink:
54 if os.path.isfile(dest) or os.path.islink(dest):
55 os.unlink(dest)
56 if not os.path.isdir(dest):
57 with open(dest, 'wb') as fp:
58 fp.write(zf.read(name))
61 def zipappit(env, target, source):
62 """Action function to Create a zipapp *target* from specified directory.
64 Values extracted from *env*:
65 *CD*: the Dir node for the place we want to work.
66 *PSV*: the directory name to point :meth:`zipapp.create_archive` at
67 (note *source* is unused here in favor of PSV)
68 *main*: the entry point for the zipapp
69 """
70 print(f"Creating zipapp {target[0]}:")
71 dest = target[0].abspath
72 olddir = os.getcwd()
73 os.chdir(env['CD'].abspath)
74 try:
75 zipapp.create_archive(
76 source=env['PSV'],
77 target=dest,
78 main=env['entry'],
79 interpreter="/usr/bin/env python",
81 finally:
82 os.chdir(olddir)