~debfx/+junk/kubuntu-automation

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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/python

import argparse
import glob
import os
from launchpadlib.launchpad import Launchpad
import re
import subprocess
import sys
import tempfile
import urllib

parser = argparse.ArgumentParser(description="Upload new KDE SC version to the PPA.")
parser.add_argument("-d", "--dist", required=True, help="Distribution name")
parser.add_argument("-v", "--version", required=True, help="Upstream version")
parser.add_argument("-m", "--message", required=True, help="Changelog and commit message")
parser.add_argument("-p", "--packages", help="Override the list packages to upload (comma separated)")
parser.add_argument("-t", "--tmpdir", help="Temprary dir where the packages are prepared")
parser.add_argument("--sru", action="store_true", help="Do a Stable Release Upload")

args = parser.parse_args()

release = args.dist
version = args.version
changelogEntry = args.message
sru = args.sru

def readAllFromFile(filename):
    f = open(filename, "r")
    result = f.read()
    f.close()
    return result

def firstLineMatch(expression, lines):
    for line in lines:
        match = expression.search(line)
        if match:
            return line

    return False

def sanitizeBranch(package):
    archiveChangelog = extractDebianFile(package, "debian/changelog")
    if archiveChangelog == True:
        print "=== " + package + " is not in the archive"
        return True
    elif not archiveChangelog:
        return False
    bzrChangelog = readAllFromFile("debian/changelog")
    if not bzrChangelog:
        return False

    archiveChangelog = archiveChangelog.splitlines()
    bzrChangelog = bzrChangelog.splitlines()

    archiveTopline = firstLineMatch(topline, archiveChangelog)
    archiveEndline = firstLineMatch(endline, archiveChangelog)

    if archiveTopline not in bzrChangelog or archiveEndline not in bzrChangelog:
        return False

    return True

def extractDebianFile(package, extractfile):
    try:
        source = archive.getPublishedSources(distro_series=series, exact_match=True, pocket="Release", source_name=package)[0]
    except IndexError:
        return True

    pkgFiles = []
    sourceUrls = source.sourceFileUrls()
    for plainUrl in sourceUrls:
        url = urllib.unquote(plainUrl)
        # fetch non-orig tarball files
        match = re.search(r'/([^/]*(?:\.diff\.gz|\.debian\.tar\.[a-z0-9]+|\.dsc))$', url)
        if match:
            localfile = match.group(1)
            if localfile[-4:] == ".dsc":
                dscfile = localfile
            pkgFiles.append(localfile)
            urllib.urlretrieve(plainUrl, localfile)

    if len(pkgFiles) < 2:
        return False

    pDscExtract = subprocess.Popen(["dscextract", dscfile, extractfile], stdout=subprocess.PIPE)
    data = pDscExtract.communicate()[0]
    if pDscExtract.returncode != 0:
        return False

    for filename in pkgFiles:
        os.remove(filename)

    return data

def upstreamName(package):
    if package == "kde4libs":
        return "kdelibs"
    else:
        return package

if not sru:
    launchpad = Launchpad.login_anonymously("kubuntu-initial-upload", "production")
    ubuntu = launchpad.distributions["ubuntu"]
    archive = ubuntu.main_archive
    series = ubuntu.current_series

    topline = re.compile(r'^(\w%(name_chars)s*) \(([^\(\) \t]+)\)'
                         '((\s+%(name_chars)s+)+)\;'
                         % {'name_chars': '[-+0-9a-z.]'},
                         re.IGNORECASE)
    endline = re.compile('^ -- (.*) <(.*)>(  ?)((\w+\,\s*)?\d{1,2}\s+\w+\s+'
                         '\d{4}\s+\d{1,2}:\d\d:\d\d\s+[-+]\d{4}(\s+\([^\\\(\)]\))?\s*)$')

versionParts = version.split(".")
lastDigit = int(versionParts[-1])

if lastDigit >= 80:
    stability = "unstable"
else:
    stability = "stable"

if args.packages:
    packages = args.packages.split(",")
else:
    f = open("kdesc-packages-" + release + ".txt", "r")
    packages = f.readlines()
    f.close()

    packages = map(lambda line: line.strip("\r\n\t "), packages)
    packages = filter(lambda line: line and not line.startswith("#"), packages)

    # move libraries to the front
    packages.sort(key=lambda package: package.find("lib") != -1 and "_" + package or package)

if args.tmpdir:
    basedir = os.path.abspath(args.tmpdir)
else:
    basedir = tempfile.mkdtemp()
uploaddir = basedir + "/upload"

os.mkdir(uploaddir)

for package in packages:
    os.mkdir(basedir + "/" + package)
    os.chdir(basedir + "/" + package)

    # fetch orig tarball
    remote = "ftpmaster.kde.org:/home/ftpubuntu/%s/%s/src/%s-%s.tar.xz" % (stability, version, upstreamName(package), version)
    subprocess.check_call(["scp", remote, "."])
    orig = "%s_%s.orig.tar.xz" % (package, version)
    os.rename("%s-%s.tar.xz" % (upstreamName(package), version), orig)

    if sru:
        subprocess.check_call(["tar", "xJf", orig])

        # fetch and extract previous version
        subprocess.check_call(["pull-lp-source", "-d", package, release])

        dscname = glob.glob("%s_*.dsc" % (package,))[0]
        match = re.match(re.escape(package) + r'_([\d\.a-z]+)-', dscname)
        prevVersion = match.group(1)

        subprocess.check_call(["dpkg-source", "-x", "--skip-patches", dscname])
        os.rename("%s-%s/debian" % (package, prevVersion), "./debian")

        p = subprocess.Popen(["diff", "-Nurw", "%s-%s" % (package, prevVersion), "%s-%s" % (package, version)], stdout=subprocess.PIPE)
        diff, _ = p.communicate()
        p = subprocess.Popen(["diffstat", "-l", "-p1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        diffstat, _ = p.communicate(diff)
        if p.returncode != 0:
            raise subprocess.CalledProcessError(p.returncode)
        diffstatLines = diffstat.strip("\r\n\t ").splitlines()
        diffstatLines = filter(lambda line: not line.endswith("/index.cache.bz2"), diffstatLines)

        # we need to upload all packages that in kde-sc-dev-latest Breaks
        # TODO what about bindings?
        if package.startswith("lib") or package == "kde4libs" or package == "kdepimlibs" or package == "kde-workspace" or package == "marble":
            significantChanges = True
        else:
            if not diffstatLines:
                print "==== Skipping %s, same as the previous version" % (package,)
                continue
            significantChanges = False

        for line in diffstatLines:
            if line.endswith(".cpp") or line.endswith(".h"):
                significantChanges = True
                break

        if not significantChanges:
            p = subprocess.Popen(["less"], stdin=subprocess.PIPE)
            p.communicate("Package: %s\n\n=== diffstat ===\n\n%s\n\n=== diff ===\n\n%s" % (package, diffstat, diff))
            sys.stdout.write("Update package [Y/n]? ")
            choice = raw_input().lower()
            if choice not in ("yes", "y", ""):
                continue

        if upstreamName(package) != package:
            os.rename("%s-%s" % (upstreamName(package), version), "%s-%s" % (package, version))
        os.rename("./debian", "%s-%s/debian" % (package, version))
        os.chdir("%s-%s" % (package, version))
    else:
        subprocess.check_call(["bzr", "branch", "bzr+ssh://bazaar.launchpad.net/~kubuntu-packagers/kubuntu-packaging/" + upstreamName(package), "bzr"])
        os.chdir("bzr")

        if not sanitizeBranch(package):
            print "==== Skipping %s, bzr branch has unexpected content" % (package,)
            continue

    control = readAllFromFile("debian/control")
    control = re.sub(r'kde-sc-dev-latest \(>= 4:[\d\.]+\)', "kde-sc-dev-latest (>= 4:%s)" % (version,), control)
    f = open("debian/control", "w")
    f.write(control)
    f.close()

    debianVersion = "0ubuntu"
    if sru:
        debianVersion += "0.1~ppa1"
    else:
        debianVersion += "1"

    if sru:
        changelogRelease = release
    else:
        changelogRelease = "UNRELEASED"
    subprocess.check_call(["dch", "-v", "4:%s-%s" % (version, debianVersion), "-D", changelogRelease, changelogEntry])

    if sru:
        subprocess.check_call(["debuild", "-S", "-nc"])
    else:
        subprocess.check_call(["bzr-buildpackage-ppa", "-d", release, "--", "-nc"])
        subprocess.check_call(["debcommit", "-a"])
        debianVersion += "~ppa1"
        subprocess.check_call(["bzr", "push", ":parent"])

    subprocess.check_call(["dcmd", "cp", "../%s_%s-%s_source.changes" % (package, version, debianVersion), uploaddir])

print "\n\n=== Packages are ready for upload in " + uploaddir

# kate: space-indent on; indent-width 4; replace-tabs on; indent-mode python; remove-trailing-space on;