blob: fe7f450c55e1c5173c05d7f626af86119a85d7eb [file] [log] [blame]
Brett Cannonf299abd2015-04-13 14:21:02 -04001"""Module/script to byte-compile all .py files to .pyc files.
Guido van Rossumc567b811998-01-19 23:07:55 +00002
3When called as a script with arguments, this compiles the directories
4given as arguments recursively; the -l option prevents it from
5recursing into directories.
6
7Without arguments, if compiles all modules on sys.path, without
8recursing into subdirectories. (Even though it should do so for
9packages -- for now, you'll have to deal with packages separately.)
10
11See module py_compile for details of the actual byte-compilation.
Guido van Rossumc567b811998-01-19 23:07:55 +000012"""
Guido van Rossum3bb54481994-08-29 10:52:58 +000013import os
14import sys
Brett Cannon7822e122013-06-14 23:04:02 -040015import importlib.util
Guido van Rossum3bb54481994-08-29 10:52:58 +000016import py_compile
Brett Cannonbefb14f2009-02-10 02:10:16 +000017import struct
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020018import filecmp
Guido van Rossum3bb54481994-08-29 10:52:58 +000019
Brett Cannonf1a8df02014-09-12 10:39:48 -040020from functools import partial
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020021from pathlib import Path
22
Matthias Klosec33b9022010-03-16 00:36:26 +000023__all__ = ["compile_dir","compile_file","compile_path"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000024
Victor Stinnereb1dda22019-10-15 11:26:13 +020025def _walk_dir(dir, maxlevels, quiet=0):
Berker Peksag812a2b62016-10-01 00:54:18 +030026 if quiet < 2 and isinstance(dir, os.PathLike):
27 dir = os.fspath(dir)
Brett Cannonf1a8df02014-09-12 10:39:48 -040028 if not quiet:
29 print('Listing {!r}...'.format(dir))
30 try:
31 names = os.listdir(dir)
32 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +030033 if quiet < 2:
34 print("Can't list {!r}".format(dir))
Brett Cannonf1a8df02014-09-12 10:39:48 -040035 names = []
36 names.sort()
37 for name in names:
38 if name == '__pycache__':
39 continue
40 fullname = os.path.join(dir, name)
Brett Cannonf1a8df02014-09-12 10:39:48 -040041 if not os.path.isdir(fullname):
42 yield fullname
43 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
44 os.path.isdir(fullname) and not os.path.islink(fullname)):
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020045 yield from _walk_dir(fullname, maxlevels=maxlevels - 1,
46 quiet=quiet)
Brett Cannonf1a8df02014-09-12 10:39:48 -040047
Victor Stinnereb1dda22019-10-15 11:26:13 +020048def compile_dir(dir, maxlevels=None, ddir=None, force=False,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020049 rx=None, quiet=0, legacy=False, optimize=-1, workers=1,
Gregory P. Smith02673352020-02-28 17:28:37 -080050 invalidation_mode=None, *, stripdir=None,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020051 prependdir=None, limit_sl_dest=None, hardlink_dupes=False):
Guido van Rossumc567b811998-01-19 23:07:55 +000052 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000053
Guido van Rossumc567b811998-01-19 23:07:55 +000054 Arguments (only dir is required):
55
56 dir: the directory to byte-compile
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020057 maxlevels: maximum recursion level (default `sys.getrecursionlimit()`)
R. David Murray94f58c32010-12-17 16:29:07 +000058 ddir: the directory that will be prepended to the path to the
59 file as it is compiled into each byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000060 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +030061 quiet: full output with False or 0, errors only with 1,
62 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +000063 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020064 optimize: int or list of optimization levels or -1 for level of
65 the interpreter. Multiple levels leads to multiple compiled
66 files each with one optimization level.
Brett Cannonf1a8df02014-09-12 10:39:48 -040067 workers: maximum number of parallel workers
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080068 invalidation_mode: how the up-to-dateness of the pyc will be checked
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020069 stripdir: part of path to left-strip from source file path
Jelle Zijlstraefb8dd52020-04-30 03:39:11 -070070 prependdir: path to prepend to beginning of original file path, applied
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020071 after stripdir
72 limit_sl_dest: ignore symlinks if they are pointing outside of
73 the defined path
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +020074 hardlink_dupes: hardlink duplicated pyc files
Guido van Rossumc567b811998-01-19 23:07:55 +000075 """
Dustin Spicuzza1d817e42018-11-23 12:06:55 -050076 ProcessPoolExecutor = None
Gregory P. Smith02673352020-02-28 17:28:37 -080077 if ddir is not None and (stripdir is not None or prependdir is not None):
78 raise ValueError(("Destination dir (ddir) cannot be used "
79 "in combination with stripdir or prependdir"))
80 if ddir is not None:
81 stripdir = dir
82 prependdir = ddir
83 ddir = None
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020084 if workers < 0:
85 raise ValueError('workers must be greater or equal to 0')
86 if workers != 1:
87 try:
88 # Only import when needed, as low resource platforms may
89 # fail to import it
90 from concurrent.futures import ProcessPoolExecutor
91 except ImportError:
92 workers = 1
Victor Stinnereb1dda22019-10-15 11:26:13 +020093 if maxlevels is None:
94 maxlevels = sys.getrecursionlimit()
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020095 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080096 success = True
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020097 if workers != 1 and ProcessPoolExecutor is not None:
98 # If workers == 0, let ProcessPoolExecutor choose
Brett Cannonf1a8df02014-09-12 10:39:48 -040099 workers = workers or None
100 with ProcessPoolExecutor(max_workers=workers) as executor:
101 results = executor.map(partial(compile_file,
102 ddir=ddir, force=force,
103 rx=rx, quiet=quiet,
104 legacy=legacy,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800105 optimize=optimize,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200106 invalidation_mode=invalidation_mode,
107 stripdir=stripdir,
108 prependdir=prependdir,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200109 limit_sl_dest=limit_sl_dest,
110 hardlink_dupes=hardlink_dupes),
Brett Cannonf1a8df02014-09-12 10:39:48 -0400111 files)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800112 success = min(results, default=True)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400113 else:
114 for file in files:
115 if not compile_file(file, ddir, force, rx, quiet,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200116 legacy, optimize, invalidation_mode,
117 stripdir=stripdir, prependdir=prependdir,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200118 limit_sl_dest=limit_sl_dest,
119 hardlink_dupes=hardlink_dupes):
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800120 success = False
Fred Drake9065ea31999-03-29 20:25:40 +0000121 return success
Guido van Rossumc567b811998-01-19 23:07:55 +0000122
Berker Peksag6554b862014-10-15 11:10:57 +0300123def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800124 legacy=False, optimize=-1,
Gregory P. Smith02673352020-02-28 17:28:37 -0800125 invalidation_mode=None, *, stripdir=None, prependdir=None,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200126 limit_sl_dest=None, hardlink_dupes=False):
Éric Araujo413d7b42010-12-23 18:44:31 +0000127 """Byte-compile one file.
128
129 Arguments (only fullname is required):
130
Barry Warsaw28a691b2010-04-17 00:19:56 +0000131 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000132 ddir: if given, the directory name compiled in to the
133 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000134 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300135 quiet: full output with False or 0, errors only with 1,
136 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000137 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200138 optimize: int or list of optimization levels or -1 for level of
139 the interpreter. Multiple levels leads to multiple compiled
140 files each with one optimization level.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800141 invalidation_mode: how the up-to-dateness of the pyc will be checked
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200142 stripdir: part of path to left-strip from source file path
Jelle Zijlstraefb8dd52020-04-30 03:39:11 -0700143 prependdir: path to prepend to beginning of original file path, applied
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200144 after stripdir
145 limit_sl_dest: ignore symlinks if they are pointing outside of
146 the defined path.
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200147 hardlink_dupes: hardlink duplicated pyc files
Matthias Klosec33b9022010-03-16 00:36:26 +0000148 """
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200149
150 if ddir is not None and (stripdir is not None or prependdir is not None):
151 raise ValueError(("Destination dir (ddir) cannot be used "
152 "in combination with stripdir or prependdir"))
153
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800154 success = True
Berker Peksag812a2b62016-10-01 00:54:18 +0300155 if quiet < 2 and isinstance(fullname, os.PathLike):
156 fullname = os.fspath(fullname)
Matthias Klosec33b9022010-03-16 00:36:26 +0000157 name = os.path.basename(fullname)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200158
159 dfile = None
160
Matthias Klosec33b9022010-03-16 00:36:26 +0000161 if ddir is not None:
162 dfile = os.path.join(ddir, name)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200163
164 if stripdir is not None:
165 fullname_parts = fullname.split(os.path.sep)
166 stripdir_parts = stripdir.split(os.path.sep)
167 ddir_parts = list(fullname_parts)
168
169 for spart, opart in zip(stripdir_parts, fullname_parts):
170 if spart == opart:
171 ddir_parts.remove(spart)
172
173 dfile = os.path.join(*ddir_parts)
174
175 if prependdir is not None:
176 if dfile is None:
177 dfile = os.path.join(prependdir, fullname)
178 else:
179 dfile = os.path.join(prependdir, dfile)
180
181 if isinstance(optimize, int):
182 optimize = [optimize]
183
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200184 # Use set() to remove duplicates.
185 # Use sorted() to create pyc files in a deterministic order.
186 optimize = sorted(set(optimize))
187
188 if hardlink_dupes and len(optimize) < 2:
189 raise ValueError("Hardlinking of duplicated bytecode makes sense "
190 "only for more than one optimization level")
191
Matthias Klosec33b9022010-03-16 00:36:26 +0000192 if rx is not None:
193 mo = rx.search(fullname)
194 if mo:
195 return success
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200196
197 if limit_sl_dest is not None and os.path.islink(fullname):
198 if Path(limit_sl_dest).resolve() not in Path(fullname).resolve().parents:
199 return success
200
201 opt_cfiles = {}
202
Matthias Klosec33b9022010-03-16 00:36:26 +0000203 if os.path.isfile(fullname):
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200204 for opt_level in optimize:
205 if legacy:
206 opt_cfiles[opt_level] = fullname + 'c'
Georg Brandl8334fd92010-12-04 10:26:46 +0000207 else:
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200208 if opt_level >= 0:
209 opt = opt_level if opt_level >= 1 else ''
210 cfile = (importlib.util.cache_from_source(
211 fullname, optimization=opt))
212 opt_cfiles[opt_level] = cfile
213 else:
214 cfile = importlib.util.cache_from_source(fullname)
215 opt_cfiles[opt_level] = cfile
216
Matthias Klosec33b9022010-03-16 00:36:26 +0000217 head, tail = name[:-3], name[-3:]
218 if tail == '.py':
219 if not force:
220 try:
221 mtime = int(os.stat(fullname).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800222 expect = struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
223 0, mtime)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200224 for cfile in opt_cfiles.values():
225 with open(cfile, 'rb') as chandle:
226 actual = chandle.read(12)
227 if expect != actual:
228 break
229 else:
Matthias Klosec33b9022010-03-16 00:36:26 +0000230 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200231 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000232 pass
233 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200234 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000235 try:
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200236 for index, opt_level in enumerate(optimize):
237 cfile = opt_cfiles[opt_level]
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200238 ok = py_compile.compile(fullname, cfile, dfile, True,
239 optimize=opt_level,
240 invalidation_mode=invalidation_mode)
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200241 if index > 0 and hardlink_dupes:
242 previous_cfile = opt_cfiles[optimize[index - 1]]
243 if filecmp.cmp(cfile, previous_cfile, shallow=False):
244 os.unlink(cfile)
245 os.link(previous_cfile, cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000246 except py_compile.PyCompileError as err:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800247 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300248 if quiet >= 2:
249 return success
250 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200251 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000252 else:
253 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000254 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000255 msg = err.msg.encode(sys.stdout.encoding,
256 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000257 msg = msg.decode(sys.stdout.encoding)
258 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200259 except (SyntaxError, UnicodeError, OSError) as e:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800260 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300261 if quiet >= 2:
262 return success
263 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200264 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000265 else:
266 print('*** ', end='')
267 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000268 else:
269 if ok == 0:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800270 success = False
Matthias Klosec33b9022010-03-16 00:36:26 +0000271 return success
272
Berker Peksag6554b862014-10-15 11:10:57 +0300273def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800274 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400275 invalidation_mode=None):
Guido van Rossumc567b811998-01-19 23:07:55 +0000276 """Byte-compile all module on sys.path.
277
278 Arguments (all optional):
279
Éric Araujo3b371cf2011-09-01 20:00:33 +0200280 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000281 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000282 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300283 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000284 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000285 optimize: as for compile_dir() (default -1)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800286 invalidation_mode: as for compiler_dir()
Guido van Rossumc567b811998-01-19 23:07:55 +0000287 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800288 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000289 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000290 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300291 if quiet < 2:
292 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000293 else:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800294 success = success and compile_dir(
295 dir,
296 maxlevels,
297 None,
298 force,
299 quiet=quiet,
300 legacy=legacy,
301 optimize=optimize,
302 invalidation_mode=invalidation_mode,
303 )
Fred Drake9065ea31999-03-29 20:25:40 +0000304 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000305
Matthias Klosec33b9022010-03-16 00:36:26 +0000306
Guido van Rossum3bb54481994-08-29 10:52:58 +0000307def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000308 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000309 import argparse
310
311 parser = argparse.ArgumentParser(
312 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000313 parser.add_argument('-l', action='store_const', const=0,
Victor Stinnereb1dda22019-10-15 11:26:13 +0200314 default=None, dest='maxlevels',
R. David Murray94f58c32010-12-17 16:29:07 +0000315 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500316 parser.add_argument('-r', type=int, dest='recursion',
317 help=('control the maximum recursion level. '
318 'if `-l` and `-r` options are specified, '
319 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000320 parser.add_argument('-f', action='store_true', dest='force',
321 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300322 parser.add_argument('-q', action='count', dest='quiet', default=0,
323 help='output only error messages; -qq will suppress '
324 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000325 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000326 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000327 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000328 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200329 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000330 'tracebacks in cases where the source file is '
331 'unavailable'))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200332 parser.add_argument('-s', metavar='STRIPDIR', dest='stripdir',
333 default=None,
334 help=('part of path to left-strip from path '
335 'to source file - for example buildroot. '
336 '`-d` and `-s` options cannot be '
337 'specified together.'))
338 parser.add_argument('-p', metavar='PREPENDDIR', dest='prependdir',
339 default=None,
340 help=('path to add as prefix to path '
341 'to source file - for example / to make '
342 'it absolute when some part is removed '
343 'by `-s` option. '
344 '`-d` and `-p` options cannot be '
345 'specified together.'))
R. David Murray650f1472010-11-20 21:18:51 +0000346 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200347 help=('skip files matching the regular expression; '
348 'the regexp is searched for in the full path '
349 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000350 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000351 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200352 'FILE to the list considered for compilation; '
353 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000354 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
355 help=('zero or more file and directory names '
356 'to compile; if no arguments given, defaults '
357 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400358 parser.add_argument('-j', '--workers', default=1,
359 type=int, help='Run compileall concurrently')
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800360 invalidation_modes = [mode.name.lower().replace('_', '-')
361 for mode in py_compile.PycInvalidationMode]
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400362 parser.add_argument('--invalidation-mode',
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800363 choices=sorted(invalidation_modes),
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400364 help=('set .pyc invalidation mode; defaults to '
365 '"checked-hash" if the SOURCE_DATE_EPOCH '
366 'environment variable is set, and '
367 '"timestamp" otherwise.'))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200368 parser.add_argument('-o', action='append', type=int, dest='opt_levels',
369 help=('Optimization levels to run compilation with.'
370 'Default is -1 which uses optimization level of'
371 'Python interpreter itself (specified by -O).'))
372 parser.add_argument('-e', metavar='DIR', dest='limit_sl_dest',
373 help='Ignore symlinks pointing outsite of the DIR')
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200374 parser.add_argument('--hardlink-dupes', action='store_true',
375 dest='hardlink_dupes',
376 help='Hardlink duplicated pyc files')
R. David Murray650f1472010-11-20 21:18:51 +0000377
Brett Cannonf1a8df02014-09-12 10:39:48 -0400378 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000379 compile_dests = args.compile_dest
380
R. David Murray650f1472010-11-20 21:18:51 +0000381 if args.rx:
382 import re
383 args.rx = re.compile(args.rx)
384
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200385 if args.limit_sl_dest == "":
386 args.limit_sl_dest = None
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500387
388 if args.recursion is not None:
389 maxlevels = args.recursion
390 else:
391 maxlevels = args.maxlevels
392
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200393 if args.opt_levels is None:
394 args.opt_levels = [-1]
395
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200396 if len(args.opt_levels) == 1 and args.hardlink_dupes:
397 parser.error(("Hardlinking of duplicated bytecode makes sense "
398 "only for more than one optimization level."))
399
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200400 if args.ddir is not None and (
401 args.stripdir is not None or args.prependdir is not None
402 ):
403 parser.error("-d cannot be used in combination with -s or -p")
404
R. David Murray650f1472010-11-20 21:18:51 +0000405 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000406 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000407 try:
408 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
409 for line in f:
410 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200411 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300412 if args.quiet < 2:
413 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000414 return False
R. David Murray650f1472010-11-20 21:18:51 +0000415
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400416 if args.invalidation_mode:
417 ivl_mode = args.invalidation_mode.replace('-', '_').upper()
418 invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
419 else:
420 invalidation_mode = None
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800421
R. David Murray95333e32010-12-14 22:32:50 +0000422 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000423 try:
R. David Murray650f1472010-11-20 21:18:51 +0000424 if compile_dests:
425 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000426 if os.path.isfile(dest):
427 if not compile_file(dest, args.ddir, args.force, args.rx,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800428 args.quiet, args.legacy,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200429 invalidation_mode=invalidation_mode,
430 stripdir=args.stripdir,
431 prependdir=args.prependdir,
432 optimize=args.opt_levels,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200433 limit_sl_dest=args.limit_sl_dest,
434 hardlink_dupes=args.hardlink_dupes):
R. David Murray5317e9c2010-12-16 19:08:51 +0000435 success = False
436 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500437 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000438 args.force, args.rx, args.quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800439 args.legacy, workers=args.workers,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200440 invalidation_mode=invalidation_mode,
441 stripdir=args.stripdir,
442 prependdir=args.prependdir,
443 optimize=args.opt_levels,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200444 limit_sl_dest=args.limit_sl_dest,
445 hardlink_dupes=args.hardlink_dupes):
R. David Murray95333e32010-12-14 22:32:50 +0000446 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000447 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000448 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500449 return compile_path(legacy=args.legacy, force=args.force,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800450 quiet=args.quiet,
451 invalidation_mode=invalidation_mode)
Guido van Rossumc567b811998-01-19 23:07:55 +0000452 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300453 if args.quiet < 2:
454 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000455 return False
456 return True
R. David Murray650f1472010-11-20 21:18:51 +0000457
Guido van Rossum3bb54481994-08-29 10:52:58 +0000458
459if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000460 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000461 sys.exit(exit_status)