Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
build_scripts.py151 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        f = tokenize.open(script)91 92        first_line = f.readline()93        if not first_line:94            self.warn(f"{script} is an empty file (skipping)")95            return96 97        shebang_match = shebang_pattern.match(first_line)98 99        updated_files.append(outfile)100        if shebang_match:101            log.info("copying and adjusting %s -> %s", script, self.build_dir)102            post_interp = shebang_match.group(1) or ''103            shebang = "#!" + self.executable + post_interp + "\n"104            self._validate_shebang(shebang, f.encoding)105            with open(outfile, "w", encoding=f.encoding) as outf:106                outf.write(shebang)107                outf.writelines(f.readlines())108            if f:109                f.close()110        else:111            if f:112                f.close()113            self.copy_file(script, outfile)114 115    def _change_modes(self, outfiles):116        if os.name != 'posix':117            return118 119        for file in outfiles:120            self._change_mode(file)121 122    def _change_mode(self, file):123        oldmode = os.stat(file)[ST_MODE] & 0o7777124        newmode = (oldmode | 0o555) & 0o7777125        if newmode != oldmode:126            log.info("changing mode of %s from %o to %o", file, oldmode, newmode)127            os.chmod(file, newmode)128 129    @staticmethod130    def _validate_shebang(shebang, encoding):131        # Python parser starts to read a script using UTF-8 until132        # it gets a #coding:xxx cookie. The shebang has to be the133        # first line of a file, the #coding:xxx cookie cannot be134        # written before. So the shebang has to be encodable to135        # UTF-8.136        try:137            shebang.encode('utf-8')138        except UnicodeEncodeError:139            raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")140 141        # If the script is encoded to a custom encoding (use a142        # #coding:xxx cookie), the shebang has to be encodable to143        # the script encoding too.144        try:145            shebang.encode(encoding)146        except UnicodeEncodeError:147            raise ValueError(148                f"The shebang ({shebang!r}) is not encodable "149                f"to the script encoding ({encoding})"150            )151 
codekingpro/portable-devtools · Team Ai