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
|
import contextlib
import glob
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import zipfile
class BadRCError(Exception):
pass
def run(cmd, cwd=None, env=None, echo=True):
if echo:
sys.stdout.write("Running cmd: %s\n" % cmd)
kwargs = {
'shell': True,
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
}
if isinstance(cmd, list):
kwargs['shell'] = False
if cwd is not None:
kwargs['cwd'] = cwd
if env is not None:
kwargs['env'] = env
p = subprocess.Popen(cmd, **kwargs)
stdout, stderr = p.communicate()
output = stdout.decode('utf-8') + stderr.decode('utf-8')
if p.returncode != 0:
raise BadRCError(
"Bad rc (%s) for cmd '%s': %s" % (p.returncode, cmd, output)
)
return output
def extract_zip(zipfile_name, target_dir):
with zipfile.ZipFile(zipfile_name, 'r') as zf:
for zf_info in zf.infolist():
# Works around extractall not preserving file permissions:
# https://bugs.python.org/issue15795
extracted_path = zf.extract(zf_info, target_dir)
os.chmod(extracted_path, zf_info.external_attr >> 16)
@contextlib.contextmanager
def tmp_dir():
dirname = tempfile.mkdtemp()
try:
yield dirname
finally:
shutil.rmtree(dirname)
@contextlib.contextmanager
def cd(dirname):
original = os.getcwd()
os.chdir(dirname)
try:
yield
finally:
os.chdir(original)
def bin_path():
"""Get the system's binary path, either `bin` on reasonable systems
or `Scripts` on Windows.
"""
path = "bin"
if platform.system() == "Windows":
path = "Scripts"
return path
def virtualenv_enabled():
# Helper function to see if we need to make
# our own virtualenv for installs.
return bool(os.environ.get('VIRTUAL_ENV'))
def update_metadata(dirname, **kwargs):
print('Update metadata values %s' % kwargs)
metadata_file = os.path.join(dirname, 'awscli', 'data', 'metadata.json')
with open(metadata_file) as f:
metadata = json.load(f)
for key, value in kwargs.items():
metadata[key] = value
with open(metadata_file, 'w') as f:
json.dump(metadata, f)
def save_to_zip(dirname, zipfile_name):
if zipfile_name.endswith('.zip'):
zipfile_name = zipfile_name[:-4]
shutil.make_archive(zipfile_name, 'zip', dirname)
|