Debian Codegraph @

debian/scripts/pypy3clean

raw
1 #!/usr/bin/pypy3
2
3 import argparse
4 import collections
5 import itertools
6 import os
7 import subprocess
8 import sys
9
10
11 def abort(message):
12 print(message, file=sys.stderr)
13 sys.exit(1)
14
15
16 def package_modules(package):
17 """Iterate through all python modules in an installed Debian package"""
18 env = os.environ.copy()
19 env['LC_ALL'] = 'C.UTF-8'
20 p = subprocess.Popen(('dpkg', '-L', package), stdout=subprocess.PIPE,
21 stderr=subprocess.PIPE, env=env)
22 files, stderr = p.communicate()
23 if p.returncode != 0:
24 abort('Unable to list files in %s. Is it installed?' % package)
25
26 for fn in files.decode('utf8').splitlines():
27 if fn.endswith('.py'):
28 if fn.startswith('/usr/share/doc/'):
29 continue
30 yield fn
31
32
33 def find_modules(root):
34 """Iterate through all python modules in directory tree root"""
35 if os.path.isfile(root):
36 yield root
37 return
38
39 for dirpath, dirnames, filenames in os.walk(root):
40 for fn in filenames:
41 if fn.endswith('.py'):
42 yield os.path.join(dirpath, fn)
43
44
45 def clean_modules(modules, verbose, tag):
46 """Remove all tag.pyc files for every module specified"""
47 clean = collections.defaultdict(list)
48 for module in modules:
49 dir_, basename = os.path.split(module)
50 clean[dir_].append(os.path.splitext(basename)[0])
51
52 for dir_, basenames in clean.items():
53 pycache = os.path.join(dir_, '__pycache__')
54 if not os.path.exists(pycache):
55 continue
56
57 empty = True
58 for fn in os.listdir(pycache):
59 parts = fn.rsplit('.', 2)
60 if parts[0] in basenames and parts[1] == tag and parts[2] == 'pyc':
61 if verbose:
62 print('Removing %s' % os.path.join(pycache, fn))
63 os.unlink(os.path.join(pycache, fn))
64 else:
65 empty = False
66
67 if empty:
68 if verbose:
69 print('Pruning %s' % pycache)
70 os.rmdir(pycache)
71
72
73 def clean_directories(directories, verbose, tag):
74 """Remove the specified tag.pyc files."""
75 suffix = '.{}.pyc'.format(tag)
76 for root in directories:
77 for dirpath, dirnames, filenames in os.walk(root):
78 if dirpath.endswith('/__pycache__'):
79 empty = True
80 for file_ in filenames:
81 if file_.endswith(suffix):
82 if verbose:
83 print('Removing %s' % os.path.join(dirpath, file_))
84 os.unlink(os.path.join(dirpath, file_))
85 else:
86 empty = False
87
88 if empty:
89 if verbose:
90 print('Pruning %s' % dirpath)
91 os.rmdir(dirpath)
92
93
94 def pypy3_tag(version):
95 """Return the tag used by the given PyPy3 version"""
96 parts = version.split('.')
97 if len(parts) == 3:
98 parts.pop()
99 if len(parts) != 2:
100 raise argparse.ArgumentTypeError('Version must be MAJOR.MINOR')
101 parts = (int(parts[0]), int(parts[1]))
102 if parts < (7, 3):
103 return 'pypy3-{}{}'.format(*parts)
104 # 7.3 started to use the cPython version:
105 return 'pypy311' # Compatible with 3.11
106
107
108 def main():
109 parser = argparse.ArgumentParser(
110 description='Remove byte-compiled files for a package')
111 parser.add_argument('-p', '--package', metavar='PACKAGE',
112 action='append', default=[],
113 help='Debian package to byte-compile '
114 '(may be specified multiple times)')
115 parser.add_argument('directory', nargs='*',
116 help='Directory tree (or file) to byte-compile')
117 parser.add_argument('-v', '--verbose', action='store_true',
118 help='Be more verbose')
119 parser.add_argument('-q', '--quiet', action='store_true',
120 help='Be quiet')
121 parser.add_argument('--version', metavar='VERSION',
122 default='{}.{}'.format(*sys.pypy_version_info[:2]),
123 dest='tag', type=pypy3_tag,
124 help='Clean up .pyc files left by the specified '
125 'pypy3 version')
126 args = parser.parse_args()
127
128 if not (args.package or args.directory):
129 parser.error('Either a package or a directory must be specified')
130 if args.quiet and args.verbose:
131 parser.error('--quiet and --verbose cannot both be specified')
132
133 modules_p = set(itertools.chain(*(
134 package_modules(package) for package in args.package)))
135 modules_d = set(itertools.chain(*(
136 find_modules(dir_) for dir_ in args.directory)))
137
138 if args.package and args.directory:
139 modules = modules_d & modules_p
140 elif args.package:
141 modules = modules_p
142 else:
143 # Split files from directories, so that we can completely clean any
144 # specified directories.
145 modules = set()
146 directories = set()
147 for fn in args.directory:
148 if os.path.isfile(fn) and fn.endswith('.py'):
149 modules.add(fn)
150 else:
151 directories.add(fn)
152 clean_directories(directories, args.verbose, args.tag)
153
154 clean_modules(modules, args.verbose, args.tag)
155
156
157 if __name__ == '__main__':
158 main()
159
160 # vim: ft=python