1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
|
#!/usr/bin/env python3
# Copyright © 2012-2020 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import argparse
import contextlib
import gzip
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import urllib.parse
import apt
import apt_pkg
def is_po_path(path):
return path.endswith(('.po', '.pot'))
class Fetcher():
def __init__(self, urlbase):
self._urlbase = urlbase
self._progress = apt.progress.text.AcquireProgress()
self._acquire = apt_pkg.Acquire(self._progress)
self._files = []
self._tmpdir = tempfile.TemporaryDirectory(prefix='i18nspector.private.')
def add(self, url, name, urlbase=None):
if urlbase is None:
urlbase = self._urlbase
url = urllib.parse.urljoin(urlbase, url)
self._files += [apt_pkg.AcquireFile(
self._acquire,
uri=url,
descr=url,
destfile=os.path.join(self._tmpdir.name, name)
)]
def run(self):
acq = self._acquire
rc = acq.run()
if rc != acq.RESULT_CONTINUE:
raise RuntimeError('fetching failed')
for acqfile in self._files:
if acqfile.status != acqfile.STAT_DONE:
raise RuntimeError('fetching failed')
yield acqfile.destfile
def __enter__(self):
return self
def __exit__(self, exc, value, tb):
self.close()
def close(self):
self._tmpdir.cleanup()
_package_name_re = re.compile(r'\A[a-z0-9][a-z0-9.+-]+\Z')
def validate_package_name(pkg):
if _package_name_re.match(pkg):
pass
else:
raise RuntimeError('invalid package name: {pkg!r}'.format(pkg=pkg))
@contextlib.contextmanager
def chdir(new_cwd):
orig_cwd = os.getcwd()
try:
os.chdir(new_cwd)
yield
finally:
os.chdir(orig_cwd)
default_mirror = 'https://deb.debian.org/debian'
default_dist = 'stable'
default_areas = 'main'
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--mirror', metavar='URL', default=default_mirror,
help='Debian mirror to use (default: {mirror})'.format(mirror=default_mirror)
)
ap.add_argument('--contents-mirror', metavar='URL', default=None,
help='Debian mirror of Contents-* files to use (default: same as --mirror)'
)
ap.add_argument('--distribution', metavar='DIST', default=default_dist,
help='Debian distribution to use (default: {dist})'.format(dist=default_dist)
)
ap.add_argument('--areas', metavar='AREA[,AREA...]', default=default_areas,
help='archive areas to use (default: {areas})'.format(areas=default_areas)
)
ap.add_argument('--output', metavar='TARFILE', required=True,
help='output tar file'
)
options = ap.parse_args()
output = options.output
tarmode = 'w|'
for ext in 'gz', 'bz2', 'xz':
if options.output.endswith('.' + ext):
tarmode += ext
break
tar = tarfile.open(output, mode=tarmode)
mirror = options.mirror
cnts_mirror = options.contents_mirror
if cnts_mirror is None:
cnts_mirror = mirror
dist = options.distribution
areas = options.areas.split(',')
def tarfilter(tarinfo):
tarinfo.uid = tarinfo.gid = 0
tarinfo.uname = tarinfo.gname = 'root'
tarinfo.mode &= 0o700
tarinfo.mode |= 0o644
if tarinfo.mode & 0o100:
tarinfo.mode |= 0o111
prefix = 'po-corpus-{dist}/'.format(dist=dist)
tarinfo.name = prefix + tarinfo.name
if tarinfo.linkname:
tarinfo.linkname = prefix + tarinfo.linkname
return tarinfo
subprocess.check_call(['dpkg-source', '--version'], stdout=subprocess.DEVNULL)
for area in areas:
urlbase = '{mirror}/dists/{dist}/{area}/'.format(mirror=mirror, dist=dist, area=area)
cnts_urlbase = '{mirror}/dists/{dist}/{area}/'.format(mirror=cnts_mirror, dist=dist, area=area)
with Fetcher(urlbase=urlbase) as fetcher:
fetcher.add('Contents-source.gz', 'Contents.gz', urlbase=cnts_urlbase)
fetcher.add('source/Sources.xz', 'Sources.xz')
[contents_path, sources_path] = fetcher.run()
interesting_packages = set()
with gzip.open(contents_path, 'rt', encoding='UTF-8', newline='\n') as file:
for line in file:
try:
path, packages = line.rsplit('\t', 1)
except ValueError:
raise RuntimeError('malformed line: {!r}'.format(line))
if is_po_path(path):
packages = packages.rstrip('\n').split(',')
for pkg in packages:
validate_package_name(pkg)
interesting_packages.update(packages)
for para in apt_pkg.TagFile(sources_path):
pkg = para['Package']
if pkg not in interesting_packages:
continue
fileinfo = para['Files'].splitlines()
dscname = None
names = set()
for line in fileinfo:
_, name = line.rsplit(' ', 1)
ok = (
name.startswith(pkg + '_') and
'/' not in name and
name not in names
)
if not ok:
raise RuntimeError('Package {pkg}: bad Files line: {line!r}'.format(pkg=pkg, line=line))
names.add(name)
if name.endswith('.dsc'):
if dscname is not None:
raise RuntimeError('Package {pkg}: duplicate .dsc file'.format(pkg=pkg))
dscname = name
if dscname is None:
raise RuntimeError('Package {pkg}: missing .dsc file'.format(pkg=pkg))
names = list(names)
names.sort(key=dscname.__eq__)
pkgdir = para['Directory']
pkgurlbase = '{mirror}/{dir}/'.format(mirror=mirror, dir=pkgdir)
with Fetcher(urlbase=pkgurlbase) as pkgfetcher:
for name in names:
pkgfetcher.add(name, name)
for path in pkgfetcher.run():
pass
dscpath = path
unpacked = dscpath[:-4]
subprocess.check_call(['dpkg-source', '-x', dscpath, unpacked], stdout=sys.stderr)
with chdir(os.path.dirname(unpacked)):
for unp_root, unp_dirs, unp_files in os.walk(os.path.basename(unpacked)):
try:
unp_dirs.remove('.pc')
except ValueError:
pass
for unp_file in unp_files:
if is_po_path(unp_file):
unp_path = os.path.join(unp_root, unp_file)
tar.add(unp_path, filter=tarfilter)
tar.close()
if __name__ == '__main__':
main()
# vim:ts=4 sts=4 sw=4 et
|