blob: 672cb439718692e96ee62a91687895fddf51d2e1 [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:
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080087 # Check if this is a system where ProcessPoolExecutor can function.
88 from concurrent.futures.process import _check_system_limits
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020089 try:
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080090 _check_system_limits()
91 except NotImplementedError:
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020092 workers = 1
Asheesh Laroiabf2e7e52021-02-07 19:15:51 -080093 else:
94 from concurrent.futures import ProcessPoolExecutor
Victor Stinnereb1dda22019-10-15 11:26:13 +020095 if maxlevels is None:
96 maxlevels = sys.getrecursionlimit()
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +020097 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080098 success = True
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020099 if workers != 1 and ProcessPoolExecutor is not None:
100 # If workers == 0, let ProcessPoolExecutor choose
Brett Cannonf1a8df02014-09-12 10:39:48 -0400101 workers = workers or None
102 with ProcessPoolExecutor(max_workers=workers) as executor:
103 results = executor.map(partial(compile_file,
104 ddir=ddir, force=force,
105 rx=rx, quiet=quiet,
106 legacy=legacy,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800107 optimize=optimize,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200108 invalidation_mode=invalidation_mode,
109 stripdir=stripdir,
110 prependdir=prependdir,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200111 limit_sl_dest=limit_sl_dest,
112 hardlink_dupes=hardlink_dupes),
Brett Cannonf1a8df02014-09-12 10:39:48 -0400113 files)
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800114 success = min(results, default=True)
Brett Cannonf1a8df02014-09-12 10:39:48 -0400115 else:
116 for file in files:
117 if not compile_file(file, ddir, force, rx, quiet,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200118 legacy, optimize, invalidation_mode,
119 stripdir=stripdir, prependdir=prependdir,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200120 limit_sl_dest=limit_sl_dest,
121 hardlink_dupes=hardlink_dupes):
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800122 success = False
Fred Drake9065ea31999-03-29 20:25:40 +0000123 return success
Guido van Rossumc567b811998-01-19 23:07:55 +0000124
Berker Peksag6554b862014-10-15 11:10:57 +0300125def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800126 legacy=False, optimize=-1,
Gregory P. Smith02673352020-02-28 17:28:37 -0800127 invalidation_mode=None, *, stripdir=None, prependdir=None,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200128 limit_sl_dest=None, hardlink_dupes=False):
Éric Araujo413d7b42010-12-23 18:44:31 +0000129 """Byte-compile one file.
130
131 Arguments (only fullname is required):
132
Barry Warsaw28a691b2010-04-17 00:19:56 +0000133 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000134 ddir: if given, the directory name compiled in to the
135 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300137 quiet: full output with False or 0, errors only with 1,
138 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000139 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200140 optimize: int or list of optimization levels or -1 for level of
141 the interpreter. Multiple levels leads to multiple compiled
142 files each with one optimization level.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800143 invalidation_mode: how the up-to-dateness of the pyc will be checked
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200144 stripdir: part of path to left-strip from source file path
Jelle Zijlstraefb8dd52020-04-30 03:39:11 -0700145 prependdir: path to prepend to beginning of original file path, applied
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200146 after stripdir
147 limit_sl_dest: ignore symlinks if they are pointing outside of
148 the defined path.
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200149 hardlink_dupes: hardlink duplicated pyc files
Matthias Klosec33b9022010-03-16 00:36:26 +0000150 """
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200151
152 if ddir is not None and (stripdir is not None or prependdir is not None):
153 raise ValueError(("Destination dir (ddir) cannot be used "
154 "in combination with stripdir or prependdir"))
155
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800156 success = True
Berker Peksag812a2b62016-10-01 00:54:18 +0300157 if quiet < 2 and isinstance(fullname, os.PathLike):
158 fullname = os.fspath(fullname)
Matthias Klosec33b9022010-03-16 00:36:26 +0000159 name = os.path.basename(fullname)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200160
161 dfile = None
162
Matthias Klosec33b9022010-03-16 00:36:26 +0000163 if ddir is not None:
164 dfile = os.path.join(ddir, name)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200165
166 if stripdir is not None:
167 fullname_parts = fullname.split(os.path.sep)
168 stripdir_parts = stripdir.split(os.path.sep)
169 ddir_parts = list(fullname_parts)
170
171 for spart, opart in zip(stripdir_parts, fullname_parts):
172 if spart == opart:
173 ddir_parts.remove(spart)
174
175 dfile = os.path.join(*ddir_parts)
176
177 if prependdir is not None:
178 if dfile is None:
179 dfile = os.path.join(prependdir, fullname)
180 else:
181 dfile = os.path.join(prependdir, dfile)
182
183 if isinstance(optimize, int):
184 optimize = [optimize]
185
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200186 # Use set() to remove duplicates.
187 # Use sorted() to create pyc files in a deterministic order.
188 optimize = sorted(set(optimize))
189
190 if hardlink_dupes and len(optimize) < 2:
191 raise ValueError("Hardlinking of duplicated bytecode makes sense "
192 "only for more than one optimization level")
193
Matthias Klosec33b9022010-03-16 00:36:26 +0000194 if rx is not None:
195 mo = rx.search(fullname)
196 if mo:
197 return success
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200198
199 if limit_sl_dest is not None and os.path.islink(fullname):
200 if Path(limit_sl_dest).resolve() not in Path(fullname).resolve().parents:
201 return success
202
203 opt_cfiles = {}
204
Matthias Klosec33b9022010-03-16 00:36:26 +0000205 if os.path.isfile(fullname):
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200206 for opt_level in optimize:
207 if legacy:
208 opt_cfiles[opt_level] = fullname + 'c'
Georg Brandl8334fd92010-12-04 10:26:46 +0000209 else:
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200210 if opt_level >= 0:
211 opt = opt_level if opt_level >= 1 else ''
212 cfile = (importlib.util.cache_from_source(
213 fullname, optimization=opt))
214 opt_cfiles[opt_level] = cfile
215 else:
216 cfile = importlib.util.cache_from_source(fullname)
217 opt_cfiles[opt_level] = cfile
218
Matthias Klosec33b9022010-03-16 00:36:26 +0000219 head, tail = name[:-3], name[-3:]
220 if tail == '.py':
221 if not force:
222 try:
223 mtime = int(os.stat(fullname).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800224 expect = struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
225 0, mtime)
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200226 for cfile in opt_cfiles.values():
227 with open(cfile, 'rb') as chandle:
228 actual = chandle.read(12)
229 if expect != actual:
230 break
231 else:
Matthias Klosec33b9022010-03-16 00:36:26 +0000232 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200233 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000234 pass
235 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200236 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000237 try:
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200238 for index, opt_level in enumerate(optimize):
239 cfile = opt_cfiles[opt_level]
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200240 ok = py_compile.compile(fullname, cfile, dfile, True,
241 optimize=opt_level,
242 invalidation_mode=invalidation_mode)
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200243 if index > 0 and hardlink_dupes:
244 previous_cfile = opt_cfiles[optimize[index - 1]]
245 if filecmp.cmp(cfile, previous_cfile, shallow=False):
246 os.unlink(cfile)
247 os.link(previous_cfile, cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000248 except py_compile.PyCompileError as err:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800249 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300250 if quiet >= 2:
251 return success
252 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200253 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000254 else:
255 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000256 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000257 msg = err.msg.encode(sys.stdout.encoding,
258 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000259 msg = msg.decode(sys.stdout.encoding)
260 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200261 except (SyntaxError, UnicodeError, OSError) as e:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800262 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300263 if quiet >= 2:
264 return success
265 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200266 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000267 else:
268 print('*** ', end='')
269 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000270 else:
271 if ok == 0:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800272 success = False
Matthias Klosec33b9022010-03-16 00:36:26 +0000273 return success
274
Berker Peksag6554b862014-10-15 11:10:57 +0300275def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800276 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400277 invalidation_mode=None):
Guido van Rossumc567b811998-01-19 23:07:55 +0000278 """Byte-compile all module on sys.path.
279
280 Arguments (all optional):
281
Éric Araujo3b371cf2011-09-01 20:00:33 +0200282 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000283 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000284 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300285 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000286 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000287 optimize: as for compile_dir() (default -1)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800288 invalidation_mode: as for compiler_dir()
Guido van Rossumc567b811998-01-19 23:07:55 +0000289 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800290 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000291 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000292 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300293 if quiet < 2:
294 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 else:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800296 success = success and compile_dir(
297 dir,
298 maxlevels,
299 None,
300 force,
301 quiet=quiet,
302 legacy=legacy,
303 optimize=optimize,
304 invalidation_mode=invalidation_mode,
305 )
Fred Drake9065ea31999-03-29 20:25:40 +0000306 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000307
Matthias Klosec33b9022010-03-16 00:36:26 +0000308
Guido van Rossum3bb54481994-08-29 10:52:58 +0000309def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000310 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000311 import argparse
312
313 parser = argparse.ArgumentParser(
314 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000315 parser.add_argument('-l', action='store_const', const=0,
Victor Stinnereb1dda22019-10-15 11:26:13 +0200316 default=None, dest='maxlevels',
R. David Murray94f58c32010-12-17 16:29:07 +0000317 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500318 parser.add_argument('-r', type=int, dest='recursion',
319 help=('control the maximum recursion level. '
320 'if `-l` and `-r` options are specified, '
321 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000322 parser.add_argument('-f', action='store_true', dest='force',
323 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300324 parser.add_argument('-q', action='count', dest='quiet', default=0,
325 help='output only error messages; -qq will suppress '
326 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000327 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000328 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000329 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000330 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200331 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000332 'tracebacks in cases where the source file is '
333 'unavailable'))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200334 parser.add_argument('-s', metavar='STRIPDIR', dest='stripdir',
335 default=None,
336 help=('part of path to left-strip from path '
337 'to source file - for example buildroot. '
338 '`-d` and `-s` options cannot be '
339 'specified together.'))
340 parser.add_argument('-p', metavar='PREPENDDIR', dest='prependdir',
341 default=None,
342 help=('path to add as prefix to path '
343 'to source file - for example / to make '
344 'it absolute when some part is removed '
345 'by `-s` option. '
346 '`-d` and `-p` options cannot be '
347 'specified together.'))
R. David Murray650f1472010-11-20 21:18:51 +0000348 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200349 help=('skip files matching the regular expression; '
350 'the regexp is searched for in the full path '
351 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000352 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000353 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200354 'FILE to the list considered for compilation; '
355 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000356 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
357 help=('zero or more file and directory names '
358 'to compile; if no arguments given, defaults '
359 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400360 parser.add_argument('-j', '--workers', default=1,
361 type=int, help='Run compileall concurrently')
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800362 invalidation_modes = [mode.name.lower().replace('_', '-')
363 for mode in py_compile.PycInvalidationMode]
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400364 parser.add_argument('--invalidation-mode',
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800365 choices=sorted(invalidation_modes),
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400366 help=('set .pyc invalidation mode; defaults to '
367 '"checked-hash" if the SOURCE_DATE_EPOCH '
368 'environment variable is set, and '
369 '"timestamp" otherwise.'))
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200370 parser.add_argument('-o', action='append', type=int, dest='opt_levels',
371 help=('Optimization levels to run compilation with.'
372 'Default is -1 which uses optimization level of'
373 'Python interpreter itself (specified by -O).'))
374 parser.add_argument('-e', metavar='DIR', dest='limit_sl_dest',
375 help='Ignore symlinks pointing outsite of the DIR')
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200376 parser.add_argument('--hardlink-dupes', action='store_true',
377 dest='hardlink_dupes',
378 help='Hardlink duplicated pyc files')
R. David Murray650f1472010-11-20 21:18:51 +0000379
Brett Cannonf1a8df02014-09-12 10:39:48 -0400380 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000381 compile_dests = args.compile_dest
382
R. David Murray650f1472010-11-20 21:18:51 +0000383 if args.rx:
384 import re
385 args.rx = re.compile(args.rx)
386
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200387 if args.limit_sl_dest == "":
388 args.limit_sl_dest = None
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500389
390 if args.recursion is not None:
391 maxlevels = args.recursion
392 else:
393 maxlevels = args.maxlevels
394
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200395 if args.opt_levels is None:
396 args.opt_levels = [-1]
397
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200398 if len(args.opt_levels) == 1 and args.hardlink_dupes:
399 parser.error(("Hardlinking of duplicated bytecode makes sense "
400 "only for more than one optimization level."))
401
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200402 if args.ddir is not None and (
403 args.stripdir is not None or args.prependdir is not None
404 ):
405 parser.error("-d cannot be used in combination with -s or -p")
406
R. David Murray650f1472010-11-20 21:18:51 +0000407 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000408 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000409 try:
410 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
411 for line in f:
412 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200413 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300414 if args.quiet < 2:
415 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000416 return False
R. David Murray650f1472010-11-20 21:18:51 +0000417
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400418 if args.invalidation_mode:
419 ivl_mode = args.invalidation_mode.replace('-', '_').upper()
420 invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
421 else:
422 invalidation_mode = None
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800423
R. David Murray95333e32010-12-14 22:32:50 +0000424 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000425 try:
R. David Murray650f1472010-11-20 21:18:51 +0000426 if compile_dests:
427 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000428 if os.path.isfile(dest):
429 if not compile_file(dest, args.ddir, args.force, args.rx,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800430 args.quiet, args.legacy,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200431 invalidation_mode=invalidation_mode,
432 stripdir=args.stripdir,
433 prependdir=args.prependdir,
434 optimize=args.opt_levels,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200435 limit_sl_dest=args.limit_sl_dest,
436 hardlink_dupes=args.hardlink_dupes):
R. David Murray5317e9c2010-12-16 19:08:51 +0000437 success = False
438 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500439 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000440 args.force, args.rx, args.quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800441 args.legacy, workers=args.workers,
Lumír 'Frenzy' Balhar8e7bb992019-09-26 08:28:26 +0200442 invalidation_mode=invalidation_mode,
443 stripdir=args.stripdir,
444 prependdir=args.prependdir,
445 optimize=args.opt_levels,
Lumír 'Frenzy' Balhare77d4282020-05-14 16:17:22 +0200446 limit_sl_dest=args.limit_sl_dest,
447 hardlink_dupes=args.hardlink_dupes):
R. David Murray95333e32010-12-14 22:32:50 +0000448 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000449 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500451 return compile_path(legacy=args.legacy, force=args.force,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800452 quiet=args.quiet,
453 invalidation_mode=invalidation_mode)
Guido van Rossumc567b811998-01-19 23:07:55 +0000454 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300455 if args.quiet < 2:
456 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000457 return False
458 return True
R. David Murray650f1472010-11-20 21:18:51 +0000459
Guido van Rossum3bb54481994-08-29 10:52:58 +0000460
461if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000462 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000463 sys.exit(exit_status)