codekingpro/portable-devtools
114k
1"""distutils.command.build_scripts2 3Implements the Distutils 'build_scripts' command."""4 5import os6import re7import tokenize8from distutils import sysconfig9from distutils._log import log10from stat import ST_MODE11 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 = [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 = ['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): # noqa: C90179 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("%s is an empty file (skipping)" % script)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 if not sysconfig.python_build:109 executable = self.executable110 else:111 executable = os.path.join(112 sysconfig.get_config_var("BINDIR"),113 "python{}{}".format(114 sysconfig.get_config_var("VERSION"),115 sysconfig.get_config_var("EXE"),116 ),117 )118 post_interp = shebang_match.group(1) or ''119 shebang = "#!" + executable + post_interp + "\n"120 self._validate_shebang(shebang, f.encoding)121 with open(outfile, "w", encoding=f.encoding) as outf:122 outf.write(shebang)123 outf.writelines(f.readlines())124 if f:125 f.close()126 else:127 if f:128 f.close()129 self.copy_file(script, outfile)130 131 def _change_modes(self, outfiles):132 if os.name != 'posix':133 return134 135 for file in outfiles:136 self._change_mode(file)137 138 def _change_mode(self, file):139 if self.dry_run:140 log.info("changing mode of %s", file)141 return142 143 oldmode = os.stat(file)[ST_MODE] & 0o7777144 newmode = (oldmode | 0o555) & 0o7777145 if newmode != oldmode:146 log.info("changing mode of %s from %o to %o", file, oldmode, newmode)147 os.chmod(file, newmode)148 149 @staticmethod150 def _validate_shebang(shebang, encoding):151 # Python parser starts to read a script using UTF-8 until152 # it gets a #coding:xxx cookie. The shebang has to be the153 # first line of a file, the #coding:xxx cookie cannot be154 # written before. So the shebang has to be encodable to155 # UTF-8.156 try:157 shebang.encode('utf-8')158 except UnicodeEncodeError:159 raise ValueError(f"The shebang ({shebang!r}) is not encodable to utf-8")160 161 # If the script is encoded to a custom encoding (use a162 # #coding:xxx cookie), the shebang has to be encodable to163 # the script encoding too.164 try:165 shebang.encode(encoding)166 except UnicodeEncodeError:167 raise ValueError(168 f"The shebang ({shebang!r}) is not encodable "169 f"to the script encoding ({encoding})"170 )171 