1 |
#!/usr/bin/python -u |
2 |
|
3 |
# A lot of the code comes from ftpadmin, see |
4 |
# http://git.gnome.org/browse/sysadmin-bin/tree/ftpadmin |
5 |
# Written by Olav Vitters |
6 |
|
7 |
# basic modules: |
8 |
import os |
9 |
import os.path |
10 |
import sys |
11 |
import re |
12 |
import subprocess |
13 |
|
14 |
# command line parsing, error handling: |
15 |
import argparse |
16 |
import errno |
17 |
|
18 |
# overwriting files by moving them (safer): |
19 |
import tempfile |
20 |
import shutil |
21 |
|
22 |
# version comparison: |
23 |
import rpm |
24 |
|
25 |
# opening tarballs: |
26 |
import tarfile |
27 |
import gzip |
28 |
import bz2 |
29 |
import lzma # pyliblzma |
30 |
|
31 |
# getting links from HTML document: |
32 |
from sgmllib import SGMLParser |
33 |
import urllib2 |
34 |
import urlparse |
35 |
|
36 |
# for checking hashes |
37 |
import hashlib |
38 |
|
39 |
# for parsing ftp-release-list emails |
40 |
import email |
41 |
from email.mime.text import MIMEText |
42 |
|
43 |
# to be able to sleep for a while |
44 |
import time |
45 |
|
46 |
# version freeze |
47 |
import datetime |
48 |
|
49 |
# packages --sort |
50 |
import itertools |
51 |
|
52 |
# check-latest |
53 |
import requests |
54 |
|
55 |
SLEEP_INITIAL=180 |
56 |
SLEEP_REPEAT=30 |
57 |
SLEEP_TIMES=30 |
58 |
|
59 |
re_majmin = re.compile(r'^([0-9]+\.[0-9]+).*') |
60 |
re_version = re.compile(r'([-.]|\d+|[^-.\d]+)') |
61 |
|
62 |
def version_cmp(a, b): |
63 |
"""Compares two versions |
64 |
|
65 |
Returns |
66 |
-1 if a < b |
67 |
0 if a == b |
68 |
1 if a > b |
69 |
""" |
70 |
|
71 |
return rpm.labelCompare(('1', a, '1'), ('1', b, '1')) |
72 |
|
73 |
def get_latest_version(versions, max_version=None): |
74 |
"""Gets the latest version number |
75 |
|
76 |
if max_version is specified, gets the latest version number before |
77 |
max_version""" |
78 |
latest = None |
79 |
for version in versions: |
80 |
if ( latest is None or version_cmp(version, latest) > 0 ) \ |
81 |
and ( max_version is None or version_cmp(version, max_version) < 0 ): |
82 |
latest = version |
83 |
return latest |
84 |
|
85 |
MAJOR_VERSIONS = { |
86 |
'NetworkManager': set(('0.9',)), |
87 |
'networkmanager': set(('0.9',)), |
88 |
'networkmanager-applet': set(('0.9',)), |
89 |
'networkmanager-openconnect': set(('0.9',)), |
90 |
'networkmanager-openvpn': set(('0.9',)), |
91 |
'networkmanager-pptp': set(('0.9',)), |
92 |
'networkmanager-vpnc': set(('0.9',)) |
93 |
} |
94 |
|
95 |
def get_majmin(version, module=None): |
96 |
nrs = version.split('.') |
97 |
|
98 |
if module and module in MAJOR_VERSIONS: |
99 |
module_versions = [version.split(".") for version in MAJOR_VERSIONS[module]] |
100 |
|
101 |
nrstest = nrs[:] |
102 |
|
103 |
while len(nrstest) >= 2: |
104 |
if nrstest in module_versions: |
105 |
return (".".join(nrs[:len(nrstest)]), nrs[len(nrstest)]) |
106 |
|
107 |
nrstest.pop() |
108 |
|
109 |
return (nrs[0], nrs[1]) |
110 |
|
111 |
|
112 |
def get_safe_max_version(version): |
113 |
if not re_majmin.match(version): |
114 |
return None |
115 |
|
116 |
majmin_nr = map(long, re_majmin.sub(r'\1', version).split('.')) |
117 |
|
118 |
if majmin_nr[1] % 2 == 0: |
119 |
return "%d.%d" % (majmin_nr[0], majmin_nr[1] + 1) |
120 |
else: |
121 |
return "%d.%d" % (majmin_nr[0], majmin_nr[1] + 2) |
122 |
|
123 |
def judge_version_increase(version_old, version_new, module=None): |
124 |
"""Judge quality of version increase: |
125 |
|
126 |
Returns a tuple containing judgement and message |
127 |
|
128 |
Judgement: |
129 |
Less than 0: Error |
130 |
0 to 4: Better not |
131 |
5+: Ok""" |
132 |
versions = (version_old, version_new) |
133 |
|
134 |
# First do a basic version comparison to ensure version_new is actually newer |
135 |
compare = version_cmp(version_new, version_old) |
136 |
|
137 |
if compare == 0: |
138 |
# 1.0.0 -> 1.0.1 |
139 |
return (-2, "Already at version %s!" % (version_old)) |
140 |
|
141 |
if compare != 1: |
142 |
# 1.0.1 -> 1.0.0 |
143 |
return (-3, "Version %s is older than current version %s!" % (version_new, version_old)) |
144 |
|
145 |
# Version is newer, but we don't want to see if it follows the GNOME versioning scheme |
146 |
majmins = [get_majmin(ver, module) for ver in versions if re_majmin.match(ver) is not None] |
147 |
|
148 |
if len(majmins) == 1: |
149 |
return (-1, "Version number scheme changes: %s" % (", ".join(versions))) |
150 |
|
151 |
if len(majmins) == 0: |
152 |
return (0, "Unsupported version numbers: %s" % (", ".join(versions))) |
153 |
|
154 |
# Follows GNOME versioning scheme |
155 |
# Meaning: x.y.z |
156 |
# x = major |
157 |
# y = minor : even if stable |
158 |
# z = micro |
159 |
|
160 |
# Major+minor the same? Then go ahead and upgrade! |
161 |
if majmins[0] == majmins[1]: |
162 |
# Majmin of both versions are the same, looks good! |
163 |
# 1.1.x -> 1.1.x or 1.0.x -> 1.0.x |
164 |
return (10, None) |
165 |
|
166 |
# Check/ensure major version number is the same |
167 |
if majmins[0][0] != majmins[1][0]: |
168 |
# 1.0.x -> 2.0.x |
169 |
return (1, "Major version number increase") |
170 |
|
171 |
# Minor indicates stable/unstable |
172 |
devstate = (long(majmins[0][1]) % 2 == 0, long(majmins[1][1]) % 2 == 0) |
173 |
|
174 |
# Upgrading to unstable is weird |
175 |
if not devstate[1]: |
176 |
if devstate[0]: |
177 |
# 1.2.x -> 1.3.x |
178 |
return (1, "Stable to unstable increase") |
179 |
|
180 |
# 1.3.x -> 1.5.x |
181 |
return (4, "Unstable to unstable version increase") |
182 |
|
183 |
# Unstable => stable is always ok |
184 |
if not devstate[0]: |
185 |
# 1.1.x -> 1.2.x |
186 |
return (5, "Unstable to stable") |
187 |
|
188 |
# Can only be increase of minors from one stable to the next |
189 |
# 1.0.x -> 1.2.x |
190 |
return (6, "Stable version increase") |
191 |
|
192 |
def line_input (file): |
193 |
for line in file: |
194 |
if line[-1] == '\n': |
195 |
yield line[:-1] |
196 |
else: |
197 |
yield line |
198 |
|
199 |
def call_editor(filename): |
200 |
"""Return a sequence of possible editor binaries for the current platform""" |
201 |
|
202 |
editors = [] |
203 |
|
204 |
for varname in 'VISUAL', 'EDITOR': |
205 |
if varname in os.environ: |
206 |
editors.append(os.environ[varname]) |
207 |
|
208 |
editors.extend(('/usr/bin/editor', 'vi', 'pico', 'nano', 'joe')) |
209 |
|
210 |
for editor in editors: |
211 |
try: |
212 |
ret = subprocess.call([editor, filename]) |
213 |
except OSError, e: |
214 |
if e.errno == 2: |
215 |
continue |
216 |
raise |
217 |
|
218 |
if ret == 127: |
219 |
continue |
220 |
|
221 |
return True |
222 |
|
223 |
class urllister(SGMLParser): |
224 |
def reset(self): |
225 |
SGMLParser.reset(self) |
226 |
self.urls = [] |
227 |
|
228 |
def start_a(self, attrs): |
229 |
href = [v for k, v in attrs if k=='href'] |
230 |
if href: |
231 |
self.urls.extend(href) |
232 |
|
233 |
class XzTarFile(tarfile.TarFile): |
234 |
|
235 |
OPEN_METH = tarfile.TarFile.OPEN_METH.copy() |
236 |
OPEN_METH["xz"] = "xzopen" |
237 |
|
238 |
@classmethod |
239 |
def xzopen(cls, name, mode="r", fileobj=None, **kwargs): |
240 |
"""Open gzip compressed tar archive name for reading or writing. |
241 |
Appending is not allowed. |
242 |
""" |
243 |
if len(mode) > 1 or mode not in "rw": |
244 |
raise ValueError("mode must be 'r' or 'w'") |
245 |
|
246 |
if fileobj is not None: |
247 |
fileobj = _LMZAProxy(fileobj, mode) |
248 |
else: |
249 |
fileobj = lzma.LZMAFile(name, mode) |
250 |
|
251 |
try: |
252 |
# lzma doesn't immediately return an error |
253 |
# try and read a bit of data to determine if it is a valid xz file |
254 |
fileobj.read(_LZMAProxy.blocksize) |
255 |
fileobj.seek(0) |
256 |
t = cls.taropen(name, mode, fileobj, **kwargs) |
257 |
except IOError: |
258 |
raise tarfile.ReadError("not a xz file") |
259 |
except lzma.error: |
260 |
raise tarfile.ReadError("not a xz file") |
261 |
t._extfileobj = False |
262 |
return t |
263 |
|
264 |
if not hasattr(tarfile.TarFile, 'xzopen'): |
265 |
tarfile.open = XzTarFile.open |
266 |
|
267 |
def is_valid_hash(path, algo, hexdigest): |
268 |
if algo not in hashlib.algorithms: |
269 |
raise ValueError("Unknown hash algorithm: %s" % algo) |
270 |
|
271 |
local_hash = getattr(hashlib, algo)() |
272 |
|
273 |
with open(path, 'rb') as fp: |
274 |
data = fp.read(32768) |
275 |
while data: |
276 |
local_hash.update(data) |
277 |
data = fp.read(32768) |
278 |
|
279 |
return local_hash.hexdigest() == hexdigest |
280 |
|
281 |
class SpecFile(object): |
282 |
re_update_version = re.compile(r'^(?P<pre>Version:\s*)(?P<version>.+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE) |
283 |
re_update_release = re.compile(r'^(?P<pre>Release:\s*)(?P<release>%mkrel \d+)(?P<post>\s*)$', re.MULTILINE + re.IGNORECASE) |
284 |
|
285 |
def __init__(self, path, module=None): |
286 |
self.path = path |
287 |
self.cwd = os.path.dirname(path) |
288 |
self.module = module |
289 |
|
290 |
@property |
291 |
def version(self): |
292 |
return subprocess.check_output(["rpm", "--specfile", self.path, "--queryformat", "%{VERSION}\n"]).splitlines()[0] |
293 |
@property |
294 |
def sources(self): |
295 |
ts = rpm.ts() |
296 |
spec = ts.parseSpec(self.path) |
297 |
srclist = spec.sources if isinstance(spec.sources, (list, tuple)) \ |
298 |
else spec.sources() |
299 |
return dict((os.path.basename(name), name) for name, no, flags in srclist) |
300 |
|
301 |
def update(self, version, force=False): |
302 |
"""Update specfile (increase version)""" |
303 |
cur_version = self.version |
304 |
|
305 |
(judgement, msg) = judge_version_increase(cur_version, version) |
306 |
|
307 |
if judgement < 0: |
308 |
print >>sys.stderr, "ERROR: %s!" % (msg) |
309 |
return False |
310 |
|
311 |
if judgement < 5: |
312 |
print "WARNING: %s!" % (msg) |
313 |
if not force: return False |
314 |
|
315 |
# XXX - os.path.join is hackish |
316 |
svn_diff_output = subprocess.check_output(["svn", "diff", os.path.join(self.path, '..')]) |
317 |
if svn_diff_output != '': |
318 |
print svn_diff_output |
319 |
print >>sys.stderr, "ERROR: Package has uncommitted changes!" |
320 |
if not force: |
321 |
return False |
322 |
|
323 |
# Forcing package submission: revert changes |
324 |
try: |
325 |
print >>sys.stderr, "WARNING: Force used; reverting svn changes" |
326 |
subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')]) |
327 |
except subprocess.CalledProcessError: |
328 |
return False |
329 |
|
330 |
with open(self.path, "rw") as f: |
331 |
data = f.read() |
332 |
|
333 |
if data.count("%subrel") != 0: |
334 |
print >>sys.stderr, "ERROR: %subrel found; don't know what to do!" |
335 |
return False |
336 |
|
337 |
if data.count("%mkrel") != 1: |
338 |
print >>sys.stderr, "ERROR: Multiple %mkrel found; don't know what to do!" |
339 |
return False |
340 |
|
341 |
data, nr = self.re_update_version.subn(r'\g<pre>%s\g<post>' % version, data, 1) |
342 |
if nr != 1: |
343 |
print >>sys.stderr, "ERROR: Could not increase version!" |
344 |
return False |
345 |
|
346 |
data, nr = self.re_update_release.subn(r'\g<pre>%mkrel 1\g<post>', data, 1) |
347 |
if nr != 1: |
348 |
print >>sys.stderr, "ERROR: Could not reset release!" |
349 |
return False |
350 |
|
351 |
# Overwrite file with new version number |
352 |
write_file(self.path, data) |
353 |
|
354 |
|
355 |
# Verify that RPM also agrees that version number has changed |
356 |
if self.version != version: |
357 |
print "ERROR: Increased version to %s, but RPM doesn't agree!?!" % version |
358 |
return False |
359 |
|
360 |
|
361 |
# Try to download the new tarball various times and wait between attempts |
362 |
tries = 0 |
363 |
while tries < SLEEP_TIMES: |
364 |
tries += 1 |
365 |
if tries > 1: time.sleep(SLEEP_REPEAT * 2 ** (tries // 10)) |
366 |
try: |
367 |
# Download new tarball |
368 |
subprocess.check_call(['mgarepo', 'sync', '-d'], cwd=self.cwd) |
369 |
# success, so exit loop |
370 |
break |
371 |
except subprocess.CalledProcessError, e: |
372 |
# mgarepo sync returns 1 if the tarball cannot be downloaded |
373 |
if e.returncode != 1: |
374 |
subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')]) |
375 |
return False |
376 |
else: |
377 |
# failed to download tarball |
378 |
subprocess.check_call(["svn", "revert", "-R", os.path.join(self.path, '..')]) |
379 |
return False |
380 |
|
381 |
|
382 |
try: |
383 |
# Check patches still apply |
384 |
subprocess.check_call(['bm', '-p', '--nodeps'], cwd=self.cwd) |
385 |
except subprocess.CalledProcessError: |
386 |
logfile = os.path.join(os.path.dirname(self.path), 'log.%s' % os.path.splitext(os.path.basename(self.path))[0]) |
387 |
if os.path.exists(logfile): |
388 |
subprocess.call(['tail', '-n', '15', logfile]) |
389 |
return False |
390 |
|
391 |
return True |
392 |
|
393 |
class Patch(object): |
394 |
"""Do things with patches""" |
395 |
|
396 |
re_dep3 = re.compile(r'^(?:#\s*)?(?P<header>[-A-Za-z0-9]+?):\s*(?P<data>.*)$') |
397 |
re_dep3_cont = re.compile(r'^#?\s+(?P<data>.*)$') |
398 |
|
399 |
def __init__(self, path, show_path=False): |
400 |
"""Path: path to patch (might not exist)""" |
401 |
self.path = path |
402 |
self.show_path = show_path |
403 |
|
404 |
def __str__(self): |
405 |
return self.path if self.show_path else os.path.basename(self.path) |
406 |
|
407 |
def add_dep3(self): |
408 |
"""Add DEP-3 headers to a patch file""" |
409 |
if self.dep3['valid']: |
410 |
return False |
411 |
|
412 |
new_headers = ( |
413 |
('Author', self.svn_author), |
414 |
('Subject', ''), |
415 |
('Applied-Upstream', ''), |
416 |
('Forwarded', ''), |
417 |
('Bug', ''), |
418 |
) |
419 |
|
420 |
with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False) as fdst: |
421 |
with open(self.path, "r") as fsrc: |
422 |
# Start with any existing DEP3 headers |
423 |
for i in range(self.dep3['last_nr']): |
424 |
fdst.write(fsrc.read()) |
425 |
|
426 |
# After that add the DEP3 headers |
427 |
add_line = False |
428 |
for header, data in new_headers: |
429 |
if header in self.dep3['headers']: |
430 |
continue |
431 |
|
432 |
# XXX - wrap this at 80 chars |
433 |
add_line = True |
434 |
print >>fdst, "%s: %s" % (header, "" if data is None else data) |
435 |
|
436 |
if add_line: print >>fdst, "" |
437 |
# Now copy any other data and the patch |
438 |
shutil.copyfileobj(fsrc, fdst) |
439 |
|
440 |
fdst.flush() |
441 |
os.rename(fdst.name, self.path) |
442 |
|
443 |
call_editor(self.path) |
444 |
|
445 |
#Author: fwang |
446 |
#Subject: Build fix: Fix glib header inclusion |
447 |
#Applied-Upstream: commit:30602 |
448 |
#Forwarded: yes |
449 |
#Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247 |
450 |
|
451 |
def _read_dep3(self): |
452 |
"""Read DEP-3 headers from an existing patch file |
453 |
|
454 |
This will also parse git headers""" |
455 |
dep3 = {} |
456 |
headers = {} |
457 |
|
458 |
last_header = None |
459 |
last_nr = 0 |
460 |
nr = 0 |
461 |
try: |
462 |
with open(self.path, "r") as f: |
463 |
for line in line_input(f): |
464 |
nr += 1 |
465 |
# stop trying to parse when real patch begins |
466 |
if line == '---': |
467 |
break |
468 |
|
469 |
r = self.re_dep3.match(line) |
470 |
if r: |
471 |
info = r.groupdict() |
472 |
|
473 |
# Avoid matching URLS |
474 |
if info['data'].startswith('//') and info['header'].lower () == info['header']: |
475 |
continue |
476 |
|
477 |
headers[info['header']] = info['data'] |
478 |
last_header = info['header'] |
479 |
last_nr = nr |
480 |
continue |
481 |
|
482 |
r = self.re_dep3_cont.match(line) |
483 |
if r: |
484 |
info = r.groupdict() |
485 |
if last_header: |
486 |
headers[last_header] = " ".join((headers[last_header], info['data'])) |
487 |
last_nr = nr |
488 |
continue |
489 |
|
490 |
last_header = None |
491 |
except IOError: |
492 |
pass |
493 |
|
494 |
dep3['valid'] = \ |
495 |
(('Description' in headers and headers['Description'].strip() != '') |
496 |
or ('Subject' in headers and headers['Subject'].strip() != '')) \ |
497 |
and (('Origin' in headers and headers['Origin'].strip() != '') \ |
498 |
or ('Author' in headers and headers['Author'].strip() != '') \ |
499 |
or ('From' in headers and headers['From'].strip() != '')) |
500 |
dep3['last_nr'] = last_nr |
501 |
dep3['headers'] = headers |
502 |
|
503 |
self._dep3 = dep3 |
504 |
|
505 |
@property |
506 |
def dep3(self): |
507 |
if not hasattr(self, '_dep3'): |
508 |
self._read_dep3() |
509 |
|
510 |
return self._dep3 |
511 |
|
512 |
@property |
513 |
def svn_author(self): |
514 |
if not hasattr(self, '_svn_author'): |
515 |
try: |
516 |
contents = subprocess.check_output(['svn', 'log', '-q', "--", self.path], close_fds=True).strip("\n").splitlines() |
517 |
|
518 |
for line in contents: |
519 |
if ' | ' not in line: |
520 |
continue |
521 |
|
522 |
fields = line.split(' | ') |
523 |
if len(fields) >= 3: |
524 |
self._svn_author = fields[1] |
525 |
except subprocess.CalledProcessError: |
526 |
pass |
527 |
|
528 |
if not hasattr(self, '_svn_author'): |
529 |
return None |
530 |
|
531 |
return self._svn_author |
532 |
|
533 |
|
534 |
class Upstream(object): |
535 |
|
536 |
URL="http://download.gnome.org/sources/" |
537 |
limit = None |
538 |
_cache_versions = {} |
539 |
|
540 |
def __init__(self): |
541 |
urlopen = urllib2.build_opener() |
542 |
|
543 |
good_dir = re.compile('^[-A-Za-z0-9_+.]+/$') |
544 |
|
545 |
# Get the files |
546 |
usock = urlopen.open(self.URL) |
547 |
parser = urllister() |
548 |
parser.feed(usock.read()) |
549 |
usock.close() |
550 |
parser.close() |
551 |
files = parser.urls |
552 |
|
553 |
tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)]) |
554 |
if self.limit is not None: |
555 |
tarballs.intersection_update(self.limit) |
556 |
|
557 |
self.names = tarballs |
558 |
|
559 |
@classmethod |
560 |
def versions(cls, module): |
561 |
# XXX - ugly |
562 |
if module not in cls._cache_versions: |
563 |
versions = None |
564 |
|
565 |
url = '%s%s/cache.json' % (cls.URL, module) |
566 |
r = requests.get(url) |
567 |
j = r.json |
568 |
if j is not None and len(j) > 2 and module in j[2]: |
569 |
versions = j[2][module] |
570 |
|
571 |
cls._cache_versions[module] = versions |
572 |
|
573 |
return cls._cache_versions[module] |
574 |
|
575 |
class Downstream(object): |
576 |
re_file = re.compile(r'^(?P<module>.*?)[_-](?:(?P<oldversion>([0-9]+[\.])*[0-9]+)-)?(?P<version>([0-9]+[\.\-])*[0-9]+)\.(?P<format>(?:tar\.|diff\.)?[a-z][a-z0-9]*)$') |
577 |
|
578 |
MEDIA="Core Release Source" |
579 |
PKGROOT='~/pkgs' |
580 |
DISTRO=None |
581 |
|
582 |
def __init__(self): |
583 |
contents = subprocess.check_output(['urpmf', '--qf', '%name|%version|%files', '.', "--media", self.MEDIA], close_fds=True).strip("\n").splitlines() |
584 |
|
585 |
FILES = {} |
586 |
TARBALLS = {} |
587 |
|
588 |
for line in contents: |
589 |
try: |
590 |
srpm, version, filename = line.split("|") |
591 |
except ValueError: |
592 |
print >>sys.stderr, line |
593 |
continue |
594 |
|
595 |
if '.tar' in filename: |
596 |
r = self.re_file.match(filename) |
597 |
if r: |
598 |
fileinfo = r.groupdict() |
599 |
module = fileinfo['module'] |
600 |
|
601 |
if module not in TARBALLS: |
602 |
TARBALLS[module] = {} |
603 |
|
604 |
if srpm in TARBALLS[module]: |
605 |
# srpm seen before, check if version is newer |
606 |
if version_cmp(TARBALLS[module][srpm], version) == 1: |
607 |
TARBALLS[module][srpm] = version |
608 |
else: |
609 |
TARBALLS[module][srpm] = version |
610 |
|
611 |
if srpm not in FILES: |
612 |
FILES[srpm] = set() |
613 |
FILES[srpm].add(filename) |
614 |
|
615 |
self.tarballs = TARBALLS |
616 |
self.files = FILES |
617 |
|
618 |
@classmethod |
619 |
def co(cls, package, cwd=None): |
620 |
if cwd is None: |
621 |
cwd = os.path.expanduser(cls.PKGROOT) |
622 |
|
623 |
cmd = ['mgarepo', 'co'] |
624 |
if cls.DISTRO: |
625 |
cmd.extend(('-d', cls.DISTRO)) |
626 |
cmd.append(package) |
627 |
return subprocess.check_call(cmd, cwd=cwd) |
628 |
|
629 |
def get_downstream_from_upstream(self, upstream, version): |
630 |
if upstream not in self.tarballs: |
631 |
raise ValueError("No packages for upstream name: %s" % upstream) |
632 |
|
633 |
if len(self.tarballs[upstream]) == 1: |
634 |
return self.tarballs[upstream].keys() |
635 |
|
636 |
# Directories packages are located in |
637 |
root = os.path.expanduser(self.PKGROOT) |
638 |
|
639 |
packages = {} |
640 |
for package in self.tarballs[upstream].keys(): |
641 |
cwd = os.path.join(root, package) |
642 |
|
643 |
# Checkout package to ensure the checkout reflects the latest changes |
644 |
try: |
645 |
self.co(package, cwd=root) |
646 |
except subprocess.CalledProcessError: |
647 |
raise ValueError("Multiple packages found and cannot checkout %s" % package) |
648 |
|
649 |
# Determine version from spec file |
650 |
try: |
651 |
packages[package] = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=upstream).version |
652 |
except subprocess.CalledProcessError: |
653 |
raise ValueError("Multiple packages found and cannot determine version of %s" % package) |
654 |
|
655 |
# Return all packages reflecting the current version |
656 |
matches = [package for package in packages if packages[package] == version] |
657 |
if len(matches): |
658 |
return matches |
659 |
|
660 |
# Return all packages reflecting the version before the current version |
661 |
latest_version = get_latest_version(packages.values(), max_version=version) |
662 |
matches = [package for package in packages if packages[package] == latest_version] |
663 |
if len(matches): |
664 |
return matches |
665 |
|
666 |
# Give up |
667 |
raise ValueError("Multiple packages found and cannot determine package for version %s" % version) |
668 |
|
669 |
def write_file(path, data): |
670 |
with tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False) as fdst: |
671 |
fdst.write(data) |
672 |
fdst.flush() |
673 |
os.rename(fdst.name, path) |
674 |
|
675 |
def cmd_co(options, parser): |
676 |
for package, module, package_version, spec_version, downstream_files in sorted(join_streams()): |
677 |
print "%s => %s" % (module, package) |
678 |
try: |
679 |
Downstream.co(package) |
680 |
except subprocess.CalledProcessError: |
681 |
pass |
682 |
|
683 |
def join_streams(show_version=False, only_diff_version=False): |
684 |
root = os.path.expanduser(Downstream.PKGROOT) |
685 |
|
686 |
upstream = Upstream().names |
687 |
downstream = Downstream() |
688 |
|
689 |
matches = upstream & set(downstream.tarballs.keys()) |
690 |
for module in matches: |
691 |
for package in downstream.tarballs[module].keys(): |
692 |
package_version = downstream.tarballs[module][package] |
693 |
spec_version = None |
694 |
if show_version or only_diff_version: |
695 |
cwd = os.path.join(root, package) |
696 |
try: |
697 |
spec_version = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=module).version |
698 |
except subprocess.CalledProcessError: |
699 |
spec_version = 'N/A' |
700 |
|
701 |
if only_diff_version and package_version == spec_version: |
702 |
continue |
703 |
|
704 |
yield (package, module, package_version, spec_version, downstream.files[package]) |
705 |
|
706 |
def cmd_group_owner(options, parser): |
707 |
groups = set(options.group) |
708 |
|
709 |
output = [pkg.split("\t") for pkg in subprocess.check_output(["urpmf", "-F|", "--qf", "%group\t%name\t%sourcerpm\t%version\t%release", "."]).splitlines()] |
710 |
if not output: return |
711 |
|
712 |
# Filter by groups |
713 |
output = [pkg for pkg in output if pkg[0] in groups] |
714 |
if not output: return |
715 |
|
716 |
packages = {} |
717 |
for group, name, sourcerpm, version, release in output: |
718 |
if group not in packages: |
719 |
packages[group] = {} |
720 |
|
721 |
source = sourcerpm if sourcerpm else name |
722 |
end = ".src.rpm" |
723 |
if source.endswith(end): source = source[:len(source) - len(end)] |
724 |
end = "-%s-%s" %(version, release) |
725 |
if source.endswith(end): source = source[:len(source) - len(end)] |
726 |
|
727 |
if source not in packages[group]: packages[group][source] = set() |
728 |
|
729 |
packages[group][source].add(name) |
730 |
|
731 |
|
732 |
maints = dict([line.rpartition(" ")[::2] for line in subprocess.check_output(["mgarepo", "maintdb", "get"]).splitlines()]) |
733 |
|
734 |
def get_output(source, maints, packages): |
735 |
for source in packages.keys(): |
736 |
maint = maints.get(source, "?") |
737 |
|
738 |
yield "\t".join((maint, source, ",".join(sorted(packages[source])))) |
739 |
|
740 |
first = True |
741 |
for group in packages.keys(): |
742 |
if first: |
743 |
first = False |
744 |
else: |
745 |
print "" |
746 |
print "" |
747 |
print group |
748 |
print "" |
749 |
|
750 |
for line in sorted(get_output(source, maints, packages[group])): |
751 |
print line |
752 |
|
753 |
def cmd_ls(options, parser): |
754 |
streams = join_streams(show_version=options.show_version, only_diff_version=options.diff) |
755 |
if options.sort: |
756 |
SORT=dict(zip(options.sort.read().splitlines(), itertools.count())) |
757 |
|
758 |
streams = sorted(streams, key=lambda a: (SORT.get(a[1], 9999), a[0])) |
759 |
else: |
760 |
streams = sorted(streams) |
761 |
|
762 |
for package, module, package_version, spec_version, downstream_files in streams: |
763 |
sys.stdout.write(package) |
764 |
if options.upstream: sys.stdout.write("\t%s" % module) |
765 |
if options.show_version: sys.stdout.write("\t%s\t%s" % (spec_version, package_version)) |
766 |
print |
767 |
|
768 |
def cmd_check_latest(options, parser): |
769 |
streams = join_streams(show_version=True) |
770 |
|
771 |
for package, module, package_version, spec_version, downstream_files in streams: |
772 |
upgrade=set() |
773 |
sys.stdout.write(package) |
774 |
sys.stdout.write("\t%s\t%s" % (spec_version, package_version)) |
775 |
|
776 |
safe_max_version = get_safe_max_version(spec_version) |
777 |
|
778 |
versions = Upstream.versions(module) |
779 |
if versions: |
780 |
latest_version = get_latest_version(versions) |
781 |
safe_version = get_latest_version(versions, safe_max_version) |
782 |
|
783 |
cmp_latest = version_cmp(latest_version, spec_version) |
784 |
if cmp_latest < 0: |
785 |
latest_version = 'N/A' |
786 |
upgrade.add('l') |
787 |
elif cmp_latest > 0: |
788 |
upgrade.add('L') |
789 |
|
790 |
cmp_safe = version_cmp(safe_version, spec_version) |
791 |
if cmp_safe < 0: |
792 |
safe_version = 'N/A' |
793 |
upgrade.add('s') |
794 |
elif cmp_safe > 0: |
795 |
upgrade.add('S') |
796 |
|
797 |
sys.stdout.write("\t%s" % latest_version) |
798 |
sys.stdout.write("\t%s" % safe_version) |
799 |
sys.stdout.write("\t%s" % "".join(sorted(upgrade))) |
800 |
|
801 |
print |
802 |
|
803 |
def cmd_patches(options, parser): |
804 |
root = os.path.expanduser(Downstream.PKGROOT) |
805 |
|
806 |
for package, module, package_version, spec_version, downstream_files in sorted(join_streams()): |
807 |
for filename in downstream_files: |
808 |
if '.patch' in filename or '.diff' in filename: |
809 |
|
810 |
p = Patch(os.path.join(root, package, "SOURCES", filename), show_path=options.path) |
811 |
valid = "" |
812 |
forwarded = "" |
813 |
if p.dep3['headers']: |
814 |
forwarded = p.dep3['headers'].get('Forwarded', "no") |
815 |
if p.dep3['valid']: |
816 |
valid="VALID" |
817 |
print "\t".join((module, package, str(p), forwarded, valid)) |
818 |
|
819 |
def cmd_dep3(options, parser): |
820 |
p = Patch(options.patch) |
821 |
p.add_dep3() |
822 |
|
823 |
def cmd_package_new_version(options, parser): |
824 |
# Determine the package name |
825 |
if options.upstream: |
826 |
try: |
827 |
package = Downstream().get_downstream_from_upstream(options.package, options.version)[0] |
828 |
except ValueError, e: |
829 |
print >>sys.stderr, "ERROR: %s" % e |
830 |
sys.exit(1) |
831 |
else: |
832 |
package = options.package |
833 |
|
834 |
# Directories packages are located in |
835 |
root = os.path.expanduser(Downstream.PKGROOT) |
836 |
cwd = os.path.join(root, package) |
837 |
|
838 |
# Checkout package to ensure the checkout reflects the latest changes |
839 |
try: |
840 |
Downstream.co(package, cwd=root) |
841 |
except subprocess.CalledProcessError: |
842 |
sys.exit(1) |
843 |
|
844 |
# SpecFile class handles the actual version+release change |
845 |
# XXX - module should reflect upstream name, this gives it the package name |
846 |
s = SpecFile(os.path.join(cwd, "SPECS", "%s.spec" % package), module=package) |
847 |
print "%s => %s" % (s.version, options.version) |
848 |
if not s.update(options.version, force=options.force): |
849 |
sys.exit(1) |
850 |
|
851 |
# Check hash, if given |
852 |
if options.hexdigest is not None: |
853 |
sources = [name for name, origname in s.sources.iteritems() if '://' in origname] |
854 |
if not len(sources): |
855 |
print >>sys.stderr, "ERROR: Cannot determine source file (for hash check)!" |
856 |
sys.stderr(1) |
857 |
|
858 |
# If there are multiple sources, try to see if there is a preferred name |
859 |
# --> needed for metacity hash check (multiple tarball sources) |
860 |
if len(sources) > 1: |
861 |
preferred_name = '%s-%s.tar.xz' % (package, options.version) |
862 |
if preferred_name in sources: |
863 |
sources = [preferred_name] |
864 |
|
865 |
for filename in sources: |
866 |
path = os.path.join(cwd, "SOURCES", filename) |
867 |
if not is_valid_hash(path, options.algo, options.hexdigest): |
868 |
print >>sys.stderr, "ERROR: Hash file failed check for %s!" % path |
869 |
print >>sys.stderr, "ERROR: Reverting changes!" |
870 |
subprocess.call(['svn', 'revert', '-R', cwd], cwd=cwd) |
871 |
sys.exit(1) |
872 |
|
873 |
try: |
874 |
# If we made it this far, checkin the changes |
875 |
subprocess.check_call(['mgarepo', 'ci', '-m', 'new version %s' % options.version], cwd=cwd) |
876 |
|
877 |
# Submit is optional |
878 |
if options.submit: |
879 |
cmd = ['mgarepo', 'submit'] |
880 |
if Downstream.DISTRO: |
881 |
cmd.extend(('--define', 'section=core/updates_testing', '-t', Downstream.DISTRO)) |
882 |
subprocess.check_call(cmd, cwd=cwd) |
883 |
except subprocess.CalledProcessError: |
884 |
sys.exit(1) |
885 |
|
886 |
def cmd_parse_ftp_release_list(options, parser): |
887 |
def _send_reply_mail(contents, orig_msg, to, packages=[], error=False): |
888 |
"""Send an reply email""" |
889 |
contents.seek(0) |
890 |
msg = MIMEText(contents.read(), _charset='utf-8') |
891 |
|
892 |
if error: |
893 |
# XXX - ugly |
894 |
contents.seek(0) |
895 |
lastline = contents.read().rstrip().splitlines()[-1] |
896 |
# Remove things like "ERROR: " and so on from the last line |
897 |
lastline = re.sub(r'^(?:[^ :]+:\s+)+', '', lastline) |
898 |
# Remove things like " - " (youri output from mgarepo submit) |
899 |
lastline = re.sub(r'^\s+-\s+', '', lastline) |
900 |
subjecterror = " (ERROR: %s)" % lastline if lastline else " (ERROR)" |
901 |
else: |
902 |
subjecterror = "" |
903 |
|
904 |
if packages: |
905 |
subject = "%s %s%s" % (", ".join(packages), orig_msg['X-Module-Version'], subjecterror) |
906 |
else: |
907 |
subject = "Re: %s%s" % (orig_msg['Subject'], subjecterror) |
908 |
|
909 |
msg['Subject'] = subject |
910 |
msg['To'] = to |
911 |
msg["In-Reply-To"] = orig_msg["Message-ID"] |
912 |
msg["References"] = orig_msg["Message-ID"] |
913 |
|
914 |
# Call sendmail program directly so it doesn't matter if the service is running |
915 |
cmd = ['/usr/sbin/sendmail', '-oi', '--'] |
916 |
cmd.extend([to]) |
917 |
p = subprocess.Popen(cmd, stdin=subprocess.PIPE) |
918 |
p.stdin.write(msg.as_string()) |
919 |
p.stdin.flush() |
920 |
p.stdin.close() |
921 |
p.wait() |
922 |
|
923 |
|
924 |
msg = email.email.message_from_file(sys.stdin) |
925 |
|
926 |
if options.mail: |
927 |
stdout = tempfile.TemporaryFile() |
928 |
stderr = stdout |
929 |
else: |
930 |
stdout = sys.stdout |
931 |
stderr = sys.stderr |
932 |
|
933 |
try: |
934 |
module = msg['X-Module-Name'] |
935 |
version = msg['X-Module-Version'] |
936 |
hexdigest = msg['X-Module-SHA256-tar.xz'] |
937 |
except KeyError, e: |
938 |
print >>stderr, "ERROR: %s" % e |
939 |
if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True) |
940 |
sys.exit(1) |
941 |
|
942 |
try: |
943 |
packages = Downstream().get_downstream_from_upstream(module, version) |
944 |
except ValueError, e: |
945 |
print >>stderr, "ERROR: %s" % e |
946 |
if options.mail: _send_reply_mail(stdout, msg, options.mail, error=True) |
947 |
sys.exit(1) |
948 |
|
949 |
if options.wait: |
950 |
# maildrop aborts and will try to deliver after 5min |
951 |
# fork to avoid this |
952 |
if os.fork() != 0: sys.exit(0) |
953 |
# wait SLEEP_INITIAL after the message was sent |
954 |
secs = SLEEP_INITIAL |
955 |
t = email.utils.parsedate_tz(msg['Date']) |
956 |
if t is not None: |
957 |
msg_time = email.utils.mktime_tz(t) |
958 |
secs = SLEEP_INITIAL - (time.time() - msg_time) |
959 |
|
960 |
if secs > 0: time.sleep(secs) |
961 |
|
962 |
error = False |
963 |
for package in packages: |
964 |
cmd = ['mga-gnome', 'increase', '--hash', hexdigest] |
965 |
if options.submit: |
966 |
cmd.append('--submit') |
967 |
if options.force: |
968 |
cmd.append('--force') |
969 |
cmd.extend((package, version)) |
970 |
if subprocess.call(cmd, stdout=stdout, stderr=stderr): |
971 |
error = True |
972 |
|
973 |
if options.mail: _send_reply_mail(stdout, msg, options.mail, packages=packages, error=error) |
974 |
|
975 |
def main(): |
976 |
description = """Mageia GNOME commands.""" |
977 |
epilog="""Report bugs to Olav Vitters""" |
978 |
parser = argparse.ArgumentParser(description=description,epilog=epilog) |
979 |
parser.add_argument("-l", "--limit", type=argparse.FileType('r', 0), |
980 |
dest="limit_upstream", metavar="FILE", |
981 |
help="File containing upstream names") |
982 |
parser.add_argument("-d", "--distro", action="store", dest="distro", |
983 |
help="Distribution release") |
984 |
|
985 |
# SUBPARSERS |
986 |
subparsers = parser.add_subparsers(title='subcommands') |
987 |
# install |
988 |
subparser = subparsers.add_parser('co', help='checkout all GNOME modules') |
989 |
subparser.set_defaults( |
990 |
func=cmd_co |
991 |
) |
992 |
|
993 |
subparser = subparsers.add_parser('packages', help='list all GNOME packages') |
994 |
subparser.add_argument("-m", "--m", action="store_true", dest="upstream", |
995 |
help="Show upstream module") |
996 |
subparser.add_argument( "--version", action="store_true", dest="show_version", |
997 |
help="Show version numbers") |
998 |
subparser.add_argument( "--diff", action="store_true", dest="diff", |
999 |
help="Only show packages with different version") |
1000 |
subparser.add_argument( "--sort", type=argparse.FileType('r', 0), |
1001 |
dest="sort", metavar="FILE", |
1002 |
help="Sort packages according to order in given FILE") |
1003 |
|
1004 |
subparser.set_defaults( |
1005 |
func=cmd_ls, upstream=False, show_version=False, diff=False |
1006 |
) |
1007 |
|
1008 |
subparser = subparsers.add_parser('group-owner', help='list packages by group') |
1009 |
subparser.add_argument('group', metavar="GROUP", nargs='+') |
1010 |
|
1011 |
subparser.set_defaults( |
1012 |
func=cmd_group_owner |
1013 |
) |
1014 |
|
1015 |
subparser = subparsers.add_parser('check-latest', help='check for latest version of packages') |
1016 |
subparser.set_defaults( |
1017 |
func=cmd_check_latest |
1018 |
) |
1019 |
|
1020 |
subparser = subparsers.add_parser('patches', help='list all GNOME patches') |
1021 |
subparser.add_argument("-p", "--path", action="store_true", dest="path", |
1022 |
help="Show full path to patch") |
1023 |
subparser.set_defaults( |
1024 |
func=cmd_patches, path=False |
1025 |
) |
1026 |
|
1027 |
subparser = subparsers.add_parser('dep3', help='Add dep3 headers') |
1028 |
subparser.add_argument("patch", help="Patch") |
1029 |
subparser.set_defaults( |
1030 |
func=cmd_dep3, path=False |
1031 |
) |
1032 |
|
1033 |
subparser = subparsers.add_parser('increase', help='Increase version number') |
1034 |
subparser.add_argument("package", help="Package name") |
1035 |
subparser.add_argument("version", help="Version number") |
1036 |
subparser.add_argument("-f", "--force", action="store_true", dest="force", |
1037 |
help="Override warnings, just do it") |
1038 |
subparser.add_argument("-u", "--upstream", action="store_true", dest="upstream", |
1039 |
help="Package name reflects the upstream name") |
1040 |
subparser.add_argument("-s", "--submit", action="store_true", dest="submit", |
1041 |
help="Commit changes and submit") |
1042 |
subparser.add_argument( "--no-submit", action="store_false", dest="submit", |
1043 |
help="Do not commit changes and submit") |
1044 |
subparser.add_argument("-a", "--algorithm", choices=hashlib.algorithms, dest="algo", |
1045 |
help="Hash algorithm") |
1046 |
subparser.add_argument("--hash", dest="hexdigest", |
1047 |
help="Hexdigest of the hash") |
1048 |
subparser.set_defaults( |
1049 |
func=cmd_package_new_version, submit=argparse.SUPPRESS, upstream=False, hexdigest=None, algo="sha256", |
1050 |
force=False |
1051 |
) |
1052 |
|
1053 |
subparser = subparsers.add_parser('gnome-release-email', help='Submit packages based on GNOME ftp-release-list email') |
1054 |
subparser.add_argument("-m", "--mail", help="Email address to send the progress to") |
1055 |
subparser.add_argument("-w", "--wait", action="store_true", |
1056 |
help="Wait before trying to retrieve the new version") |
1057 |
subparser.add_argument("-s", "--submit", action="store_true", dest="submit", |
1058 |
help="Commit changes and submit") |
1059 |
subparser.add_argument("-f", "--force", action="store_true", |
1060 |
help="Force submission") |
1061 |
subparser.set_defaults( |
1062 |
func=cmd_parse_ftp_release_list, force=False, wait=False |
1063 |
) |
1064 |
|
1065 |
if len(sys.argv) == 1: |
1066 |
parser.print_help() |
1067 |
sys.exit(2) |
1068 |
|
1069 |
options = parser.parse_args() |
1070 |
if options.limit_upstream: |
1071 |
Upstream.limit = set(options.limit_upstream.read().strip("\n").splitlines()) |
1072 |
|
1073 |
if not hasattr(options, 'submit'): |
1074 |
options.submit = not options.distro |
1075 |
|
1076 |
if options.distro: |
1077 |
Downstream.PKGROOT = os.path.join('~/pkgs', options.distro) |
1078 |
Downstream.MEDIA = "Core Release {0} Source,Core {0} Updates Source,Core {0} Updates Testing Source".format(options.distro) |
1079 |
Downstream.DISTRO = options.distro |
1080 |
|
1081 |
try: |
1082 |
options.func(options, parser) |
1083 |
except KeyboardInterrupt: |
1084 |
print('Interrupted') |
1085 |
sys.exit(1) |
1086 |
except EOFError: |
1087 |
print('EOF') |
1088 |
sys.exit(1) |
1089 |
except IOError, e: |
1090 |
if e.errno != errno.EPIPE: |
1091 |
raise |
1092 |
sys.exit(0) |
1093 |
|
1094 |
if __name__ == "__main__": |
1095 |
os.environ['PYTHONUNBUFFERED'] = '1' |
1096 |
main() |