CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
build_scripts.py161 linesDownload Raw Back to command
1"""distutils.command.build_scripts2 3Implements the Distutils 'build_scripts' command."""4 5import os6import re7import tokenize8from distutils._log import log9from stat import ST_MODE10from typing import ClassVar11 12from .._modified import newer13from ..core import Command14from ..util import convert_path15 16shebang_pattern = re.compile('^#!.*python[0-9.]*([ \t].*)?$')17"""18Pattern matching a Python interpreter indicated in first line of a script.19"""20 21# for Setuptools compatibility22first_line_re = shebang_pattern23 24 25class build_scripts(Command):26    description = "\"build\" scripts (copy and fixup #! line)"27 28    user_options: ClassVar[list[tuple[str, str, str]]] = [29        ('build-dir=', 'd', "directory to \"build\" (copy) to"),30        ('force', 'f', "forcibly build everything (ignore file timestamps"),31        ('executable=', 'e', "specify final destination interpreter path"),32    ]33 34    boolean_options: ClassVar[list[str]] = ['force']35 36    def initialize_options(self):37        self.build_dir = None38        self.scripts = None39        self.force = None40        self.executable = None41 42    def finalize_options(self):43        self.set_undefined_options(44            'build',45            ('build_scripts', 'build_dir'),46            ('force', 'force'),47            ('executable', 'executable'),48        )49        self.scripts = self.distribution.scripts50 51    def get_source_files(self):52        return self.scripts53 54    def run(self):55        if not self.scripts:56            return57        self.copy_scripts()58 59    def copy_scripts(self):60        """61        Copy each script listed in ``self.scripts``.62 63        If a script is marked as a Python script (first line matches64        'shebang_pattern', i.e. starts with ``#!`` and contains65        "python"), then adjust in the copy the first line to refer to66        the current Python interpreter.67        """68        self.mkpath(self.build_dir)69        outfiles = []70        updated_files = []71        for script in self.scripts:72            self._copy_script(script, outfiles, updated_files)73 74        self._change_modes(outfiles)75 76        return outfiles, updated_files77 78    def _copy_script(self, script, outfiles, updated_files):79        shebang_match = None80        script = convert_path(script)81        outfile = os.path.join(self.build_dir, os.path.basename(script))82        outfiles.append(outfile)83 84        if not self.force and not newer(script, outfile):85            log.debug("not copying %s (up-to-date)", script)86            return87 88        # Always open the file, but ignore failures in dry-run mode89        # in order to attempt to copy directly.90        try:91            f = tokenize.open(script)92        except OSError:93            if not self.dry_run:94                raise95            f = None96        else:97            first_line = f.readline()98            if not first_line:99                self.warn(f"{script} is an empty file (skipping)")100                return101 102            shebang_match = shebang_pattern.match(first_line)103 104        updated_files.append(outfile)105        if shebang_match:106            log.info("copying and adjusting %s -> %s", script, self.build_dir)107            if not self.dry_run:108                post_interp = shebang_match.group(1) or ''109                shebang = "#!" + self.executable + post_interp + "\n"110                self._validate_shebang(shebang, f.encoding)111                with open(outfile, "w", encoding=f.encoding) as outf:112                    outf.write(shebang)113                    outf.writelines(f.readlines())114            if f:115                f.close()116        else:117            if f:118                f.close()119            self.copy_file(script, outfile)120 121    def _change_modes(self, outfiles):122        if os.name != 'posix':123            return124 125        for file in outfiles:126            self._change_mode(file)127 128    def _change_mode(self, file):129        if self.dry_run:130            log.info("changing mode of %s", file)131            return132 133        oldmode = os.stat(file)[ST_MODE] & 0o7777134        newmode = (oldmode | 0o555) & 0o7777135        if newmode != oldmode:136            log.info("changing mode of %s from %o to %o", file, oldmode, newmode)137            os.chmod(file, newmode)138 139    @staticmethod140    def _validate_shebang(shebang, encoding):141        # Python parser starts to read a script using UTF-8 until142        # it gets a #coding:xxx cookie. The shebang has to be the143        # first line of a file, the #coding:xxx cookie cannot be144        # written before. So the shebang has to be encodable to145        # UTF-8.146        try:147            shebang.encode('utf-8')148        except UnicodeEncodeError:149            raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")150 151        # If the script is encoded to a custom encoding (use a152        # #coding:xxx cookie), the shebang has to be encodable to153        # the script encoding too.154        try:155            shebang.encode(encoding)156        except UnicodeEncodeError:157            raise ValueError(158                f"The shebang ({shebang!r}) is not encodable "159                f"to the script encoding ({encoding})"160            )161 
Aluode/PerceptionLabPortable · CoolFace