import os import tarfile from io import BytesIO from .utils import build_nm_path PEERS_DIR = ".peers" PEERS_INDEX = "index" def bundle_node_modules(build_root, peers, node_modules_path, bundle_path): """ Creates node_modules bundle. Bundle contains node_modules directory, peers' node_modules directories, and index file with the list of added peers (\\n delimited). :param build_root: arcadia build root :type build_root: str :param peers: list of peers (arcadia root related) :type peers: list of str :param node_modules_path: node_modules path :type node_modules_path: str :param bundle_path: tarball path :type bundle_path: str """ with tarfile.open(bundle_path, "w") as tf: tf.add(node_modules_path, arcname=".") # Peers' node_modules. added_peers = [] for p in peers: peer_nm_path = build_nm_path(os.path.join(build_root, p)) peer_bundled_nm_path = build_nm_path(os.path.join(PEERS_DIR, p)) if not os.path.isdir(peer_nm_path): continue tf.add(peer_nm_path, arcname=peer_bundled_nm_path) added_peers.append(p) # Peers index. peers_index = "\n".join(added_peers) ti = tarfile.TarInfo(name=os.path.join(PEERS_DIR, PEERS_INDEX)) ti.size = len(peers_index) tf.addfile(ti, BytesIO(peers_index.encode())) def extract_node_modules(build_root, node_modules_path, bundle_path): """ Extracts node_modules bundle. :param build_root: arcadia build root :type build_root: str :param node_modules_path: node_modules path :type node_modules_path: str :param bundle_path: tarball path :type bundle_path: str """ with tarfile.open(bundle_path) as tf: tf.extractall(node_modules_path) peers = open(os.path.join(node_modules_path, PEERS_DIR, PEERS_INDEX)).read().split("\n") for p in peers: if not p: continue bundled_nm_path = build_nm_path(os.path.join(node_modules_path, PEERS_DIR, p)) nm_path = build_nm_path(os.path.join(build_root, p)) os.rename(bundled_nm_path, nm_path)