#!/usr/bin/env python3
"""
Create a tar archive of node_modules files belonging to the given packages'
transitive dependency trees, written to stdout.  If no packages are given,
defaults to all entries in package.json dependencies.
"""

import argparse
import contextlib
import io
import json
import logging
import mimetypes
import os
import subprocess
import sys
import tarfile
from collections.abc import Generator, Iterator, Mapping
from pathlib import Path
from typing import IO, Any

logger = logging.getLogger(__name__)


class PackageDB:
    def __init__(self) -> None:
        with Path('package-lock.json').open() as fp:
            self.packages: Mapping[str, Any] = json.load(fp)['packages']

    def depends(self) -> Iterator[str]:
        with Path('package.json').open() as fp:
            yield from json.load(fp).get('dependencies', {})

    def resolve(self, name: str, scope: Path) -> tuple[Path, Any]:
        while True:
            key = scope / 'node_modules' / name
            try:
                return key, self.packages[str(key)]
            except KeyError:
                if scope == Path('.'):
                    raise
                scope = scope.parent.parent  # skip past node_modules/pkg

    def files(self, name: str, scope: Path = Path('.')) -> Iterator[Path]:
        key, pkg = self.resolve(name, scope)

        for dirpath, dirnames, filenames in os.walk(key):
            # Don't descend into nested node_modules — those are separate lockfile entries.
            dirnames[:] = [d for d in dirnames if d != 'node_modules']
            for fname in filenames:
                yield Path(dirpath) / fname

        for dep_name in pkg.get('dependencies', {}):
            yield from self.files(dep_name, scope=key)


@contextlib.contextmanager
def xz_compress(stream: IO[bytes]) -> Generator[IO[bytes], None, None]:
    proc: subprocess.Popen[bytes] = subprocess.Popen(['xz', '-c'], stdin=subprocess.PIPE, stdout=stream)
    assert proc.stdin is not None
    try:
        with proc.stdin:
            yield proc.stdin
    finally:
        proc.wait()
    if proc.returncode:
        raise subprocess.CalledProcessError(proc.returncode, 'xz')


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('-C', '--directory', type=Path, default=Path('.'))
    parser.add_argument('--package-lock', action='store_true')
    parser.add_argument('--check-arch-independent', action='store_true')
    parser.add_argument('-J', '--xz', action='store_true')
    parser.add_argument('packages', nargs='*', metavar='PACKAGE')
    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)

    if sys.stdout.isatty():
        sys.exit('refusing to write tar to a terminal')

    os.chdir(args.directory)

    db = PackageDB()
    packages = args.packages or db.depends()

    files: set[Path] = set()
    if args.package_lock:
        files.add(Path('node_modules') / '.package-lock.json')
    for pkg in packages:
        files.update(db.files(pkg))

    outfile = sys.stdout.buffer

    with contextlib.ExitStack() as stack:
        if args.xz:
            outfile = stack.enter_context(xz_compress(outfile))

        tf = stack.enter_context(tarfile.open(mode='w|', fileobj=outfile, format=tarfile.USTAR_FORMAT))

        for file in sorted(files):
            with file.open('rb') as fp:
                info = tf.gettarinfo(arcname=str(file), fileobj=fp)
                info.uid = info.gid = 0
                info.uname = info.gname = 'root'
                data = fp.read()

            if args.check_arch_independent:
                mime, _ = mimetypes.guess_type(str(file))
                if mime is not None and mime.startswith(('image/', 'font/')):
                    logger.debug('%r: accepted mime type %r', file, mime)
                else:
                    try:
                        data.decode('utf-8')
                        logger.debug('%r: accepted as utf-8 text (mime %r)', file, mime)
                    except UnicodeDecodeError:
                        sys.exit(f'node-archive: binary file in archive: {file}')

            tf.addfile(info, io.BytesIO(data))


if __name__ == '__main__':
    main()
