summaryrefslogtreecommitdiffstats
path: root/debian/repack.py
blob: 32c307d35b25b4d7426711c361c43800746ac6d5 (plain)
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
#!/usr/bin/python3

import email
import fnmatch
import io
import os
import re
import sys
import tarfile
import urllib.request, urllib.error, urllib.parse

from optparse import OptionParser
from urllib.parse import urlparse


class URLFile(object):
    '''Simple proxy to urllib2.urlopen, that responds to seek only if
       it's called before read. This is enough for tarfile to be happy'''

    def __init__(self, url):
        self.file = urllib.request.urlopen(url)

    def seek(self, offset, whence = os.SEEK_SET):
        if whence != os.SEEK_SET or offset != 0 or self.read == self._read:
            raise "unsupported"

    def _read(self, size = -1):
        return self.file.read(size)

    def read(self, size = -1):
        self.read = self._read
        return self._read(size)

    def close(self):
        self.file.close()


def dirname(filespec):
    '''Returns os.path.dirname if a file, and '' if an url'''
    if urlparse(filespec).scheme:
        return ''
    return os.path.dirname(filespec)


class TarFilterList(object):
    def __init__(self, filename):
        self.patterns = {}
        for filt in open(filename).readlines():
            f = filt.strip().split(None, 1)
            if len(f) == 1:
                [pat] = f
                cmd = None
            else:
                [pat, cmd] = f

            pat = pat.split(os.sep)
            self.add_pattern(pat, self.patterns, cmd)

    def add_pattern(self, pat, patterns, cmd):
        if re.search(r'[\[\?\*]', pat[0]):
            if not '*' in patterns:
                patterns['*'] = []
            patterns['*'].append([os.sep.join(pat), cmd, False])
        else:
            if not pat[0] in patterns:
                patterns[pat[0]] = {}
            if len(pat) > 2:
                self.add_pattern(pat[1:], patterns[pat[0]], cmd)
            else:
                if not '*' in patterns[pat[0]]:
                    patterns[pat[0]]['*'] = []
                patterns[pat[0]]['*'].append([os.sep.join(pat[1:]), cmd, False])

    def match(self, name):
        name = name.split(os.sep)[1:]
        if len(name) == 0:
            return False
        return self._match(name, self.patterns)

    def _match(self, name, patterns):
        if len(name) > 1 and name[0] in patterns:
            cmd = self._match(name[1:], patterns[name[0]])
            if cmd != False:
                return cmd
        if '*' in patterns:
            for pat in patterns['*']:
                if fnmatch.fnmatch(name[0], pat[0]) or fnmatch.fnmatch(os.sep.join(name), pat[0]):
                    pat[2] = True
                    return pat[1]
        return False

    def unused(self, patterns=None, root=''):
        result = []
        if root:
            root += '/'
        if not patterns:
            patterns = self.patterns
        for pat in patterns:
            if pat != '*':
                result += self.unused(patterns[pat], root + pat)
            else:
                for p in patterns[pat]:
                    if not p[2]:
                        result.append(root + p[0])
        return result


def file_extension(name):
    return os.path.splitext(name)[1][1:]


def filter_tar(orig, new, filt):
    def u8(x):
        return x.decode('utf-8')

    filt = TarFilterList(filt)
    if urlparse(orig).scheme:
        tar = tarfile.open(orig, "r:" + file_extension(orig), URLFile(orig))
    else:
        tar = tarfile.open(orig, "r:" + file_extension(orig))
    new_tar = tarfile.open(f'{new}.new', "w:" + file_extension(new))

    while True:
        info = tar.next()
        if not info:
            break
        do_filt = filt.match(info.name)
        if do_filt == None:
            print(f'Removing {info.name}', file=sys.stderr)
            continue

        if info.isfile():
            file = tar.extractfile(info)
            if do_filt:
                print(f'Filtering {info.name}', file=sys.stderr)
                orig = file
                file = io.BytesIO()
                the_filt = lambda l: u8(l)
                if do_filt[0].isalpha():
                    f = do_filt.split(do_filt[1])
                    if f[0] == 's':
                        the_filt = lambda l: re.sub(f[1], f[2], u8(l))
                else:
                    f = do_filt.split(do_filt[0])
                    if f[2] == 'd':
                        the_filt = lambda l: "" if re.search(f[1], u8(l)) else u8(l)
                file.writelines([x.encode('utf-8') for x in map(the_filt, orig.readlines())])
                file.seek(2, 0)
                info.size = file.tell()
                file.seek(0);
            new_tar.addfile(info, file)
        else:
            new_tar.addfile(info)

    tar.close()
    new_tar.close()
    os.rename(new_tar.name, new)
    unused = filt.unused()
    if unused:
        print('\nUnused filters:')
        for ele in unused:
            if not ele.startswith('#'):
                print(ele)


def get_package_name():
    control = os.path.join(os.path.dirname(__file__), "control")
    return email.parser.Parser().parse(open(control), headersonly=True)["Source"]


def main():
    parser = OptionParser("%prog [options] tarball")
    parser.add_option("-u", "--upstream-version", dest="upstream_version",
        help="define upstream version number to use when creating the file",
        metavar="VERSION")
    parser.add_option("-f", "--filter", dest="filter",
        help="use the given filter list", metavar="FILE")
    parser.add_option("-p", "--package", dest="package",
        help="use the given package name", metavar="NAME")
    parser.add_option("-c", "--compression", dest="compression",
        help="use the given compression for the new tarball")
    (options, args) = parser.parse_args()

    if len(args) < 1 or len(args) > 1:
        parser.error("Too few arguments! You may want to use option '--help' for usage first?")
        return

    if not options.upstream_version:
        parser.error("Need an upstream version")
        return

    if not options.filter:
        options.filter = os.path.join(os.path.dirname(__file__), "source.filter")
    if not options.package:
        options.package = get_package_name()

    if os.path.islink(args[0]):
        orig = os.path.realpath(args[0])
        new_file = args[0]
    else:
        orig = args[0]
        compression = options.compression or file_extension(orig)
        new_file = f'{options.package}_{options.upstream_version}.orig.tar.{compression}'
        new_file = os.path.realpath(os.path.join(dirname(orig), new_file))
    print(f'Source: {orig} - Target: {new_file}\n')
    filter_tar(orig, new_file, options.filter)

if __name__ == '__main__':
    main()