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