/[soft]/mga-gnome/trunk/mga-gnome
ViewVC logotype

Contents of /mga-gnome/trunk/mga-gnome

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2944 - (show annotations) (download)
Tue Feb 14 10:38:56 2012 UTC (12 years, 1 month ago) by ovitters
File size: 9323 byte(s)
add option to add dep3 headers to existing patch

1 #!/usr/bin/python
2
3 import os
4 import os.path
5 import sys
6 import re
7 import subprocess
8 import urllib2
9 import urlparse
10 import argparse
11 import errno
12 import tempfile
13 import shutil
14 from sgmllib import SGMLParser
15
16 MEDIA="Core Release Source"
17 URL="http://download.gnome.org/sources/"
18 PKGROOT='~/pkgs'
19
20 def line_input (file):
21 for line in file:
22 if line[-1] == '\n':
23 yield line[:-1]
24 else:
25 yield line
26
27 class urllister(SGMLParser):
28 def reset(self):
29 SGMLParser.reset(self)
30 self.urls = []
31
32 def start_a(self, attrs):
33 href = [v for k, v in attrs if k=='href']
34 if href:
35 self.urls.extend(href)
36
37 class Patch(object):
38 """Do things with patches"""
39
40 re_dep3 = re.compile(r'^(?:#\s*)?(?P<header>[-A-Za-z0-9]+?):\s*(?P<data>.*)$')
41 re_dep3_cont = re.compile(r'^#?\s+(?P<data>.*)$')
42
43 def __init__(self, path, show_path=False):
44 """Path: path to patch (might not exist)"""
45 self.path = path
46 self.show_path = show_path
47
48 def __str__(self):
49 return self.path if self.show_path else os.path.basename(self.path)
50
51 def add_dep3(self):
52 if self.dep3['valid']:
53 return False
54
55 new_headers = (
56 ('Author', self.svn_author),
57 ('Subject', ''),
58 ('Applied-Upstream', ''),
59 ('Forwarded', ''),
60 ('Bug', ''),
61 )
62
63 with tempfile.NamedTemporaryFile(dir=os.path.dirname(self.path), delete=False) as fdst:
64 with open(self.path, "r") as fsrc:
65 # Start with any existing DEP3 headers
66 for i in range(self.dep3['last_nr']):
67 fdst.write(fsrc.read())
68
69 # After that add the DEP3 headers
70 add_line = False
71 for header, data in new_headers:
72 if header in self.dep3['headers']:
73 continue
74
75 # XXX - wrap this at 80 chars
76 add_line = True
77 print >>fdst, "%s: %s" % (header, data)
78
79 if add_line: print >>fdst, ""
80 # Now copy any other data and the patch
81 shutil.copyfileobj(fsrc, fdst)
82
83 fdst.flush()
84 os.rename(fdst.name, self.path)
85
86 #Author: fwang
87 #Subject: Build fix: Fix glib header inclusion
88 #Applied-Upstream: commit:30602
89 #Forwarded: yes
90 #Bug: http://bugzilla.abisource.com/show_bug.cgi?id=13247
91
92 def _read_dep3(self):
93 """This will also parse git headers"""
94 dep3 = {}
95 headers = {}
96
97 last_header = None
98 last_nr = 0
99 nr = 0
100 try:
101 with open(self.path, "r") as f:
102 for line in line_input(f):
103 nr += 1
104 # stop trying to parse when real patch begins
105 if line == '---':
106 break
107
108 r = self.re_dep3.match(line)
109 if r:
110 info = r.groupdict()
111 headers[info['header']] = info['data']
112 last_header = info['header']
113 last_nr = nr
114 continue
115
116 r = self.re_dep3_cont.match(line)
117 if r:
118 info = r.groupdict()
119 if last_header:
120 headers[last_header] = " ".join((headers[last_header], info['data']))
121 last_nr = nr
122 continue
123
124 last_header = None
125 except IOError:
126 pass
127
128 dep3['valid'] = \
129 (('Description' in headers and headers['Description'].strip() != '')
130 or ('Subject' in headers and headers['Subject'].strip() != '')) \
131 and (('Origin' in headers and headers['Origin'].strip() != '') \
132 or ('Author' in headers and headers['Author'].strip() != '') \
133 or ('From' in headers and headers['From'].strip() != ''))
134 dep3['last_nr'] = last_nr
135 dep3['headers'] = headers
136
137 self._dep3 = dep3
138
139 @property
140 def dep3(self):
141 if not hasattr(self, '_dep3'):
142 self._read_dep3()
143
144 return self._dep3
145
146 @property
147 def svn_author(self):
148 if not hasattr(self, '_svn_author'):
149 p = subprocess.Popen(['svn', 'log', '-q', "--", self.path], stdout=subprocess.PIPE, close_fds=True)
150 contents = p.stdout.read().strip("\n").splitlines()
151 ecode = p.wait()
152 if ecode == 0:
153 for line in contents:
154 if ' | ' not in line:
155 continue
156
157 fields = line.split(' | ')
158 if len(fields) >= 3:
159 self._svn_author = fields[1]
160
161 return self._svn_author
162
163 def get_upstream_names():
164 urlopen = urllib2.build_opener()
165
166 good_dir = re.compile('^[-A-Za-z0-9_+.]+/$')
167
168 # Get the files
169 usock = urlopen.open(URL)
170 parser = urllister()
171 parser.feed(usock.read())
172 usock.close()
173 parser.close()
174 files = parser.urls
175
176 tarballs = set([filename.replace('/', '') for filename in files if good_dir.search(filename)])
177
178 return tarballs
179
180 def get_downstream_names():
181 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]*)$')
182
183 p = subprocess.Popen(['urpmf', '--files', '.', "--media", MEDIA], stdout=subprocess.PIPE, close_fds=True)
184 contents = p.stdout.read().strip("\n").splitlines()
185 ecode = p.wait()
186 if ecode != 0:
187 sys.exit(1)
188
189 FILES = {}
190 TARBALLS = {}
191
192 for line in contents:
193 try:
194 srpm, filename = line.split(":")
195 except ValueError:
196 print >>sys.stderr, line
197 continue
198
199 if '.tar' in filename:
200 r = re_file.match(filename)
201 if r:
202 fileinfo = r.groupdict()
203 module = fileinfo['module']
204
205 if module not in TARBALLS:
206 TARBALLS[module] = set()
207 TARBALLS[module].add(srpm)
208
209 if srpm not in FILES:
210 FILES[srpm] = set()
211 FILES[srpm].add(filename)
212
213 return TARBALLS, FILES
214
215 def cmd_co(options, parser):
216 upstream = get_upstream_names()
217 downstream, downstream_files = get_downstream_names()
218
219 cwd = os.path.expanduser(PKGROOT)
220
221 matches = upstream & set(downstream.keys())
222 for module in matches:
223 print module, "\t".join(downstream[module])
224 for package in downstream[module]:
225 subprocess.call(['mgarepo', 'co', package], cwd=cwd)
226
227 def cmd_ls(options, parser):
228 upstream = get_upstream_names()
229 downstream, downstream_files = get_downstream_names()
230
231 matches = upstream & set(downstream.keys())
232 for module in matches:
233 print "\n".join(downstream[module])
234
235 def cmd_patches(options, parser):
236 upstream = get_upstream_names()
237 downstream, downstream_files = get_downstream_names()
238
239 path = os.path.expanduser(PKGROOT)
240
241 import pprint
242
243 matches = upstream & set(downstream.keys())
244 for module in sorted(matches):
245 for srpm in downstream[module]:
246 for filename in downstream_files[srpm]:
247 if '.patch' in filename or '.diff' in filename:
248 p = Patch(os.path.join(path, srpm, "SOURCES", filename), show_path=options.path)
249 print "\t".join((module, srpm, str(p)))
250 if p.dep3['headers']:
251 pprint.pprint(p.dep3['headers'])
252 if p.dep3['valid']:
253 print "VALID"
254
255 def cmd_dep3(options, parser):
256 p = Patch(options.patch)
257 p.add_dep3()
258
259 def main():
260 description = """Mageia GNOME commands."""
261 epilog="""Report bugs to Olav Vitters"""
262 parser = argparse.ArgumentParser(description=description,epilog=epilog)
263
264 # SUBPARSERS
265 subparsers = parser.add_subparsers(title='subcommands')
266 # install
267 subparser = subparsers.add_parser('co', help='checkout all GNOME modules')
268 subparser.set_defaults(
269 func=cmd_co
270 )
271
272 subparser = subparsers.add_parser('packages', help='list all GNOME packages')
273 subparser.set_defaults(
274 func=cmd_ls
275 )
276
277 subparser = subparsers.add_parser('patches', help='list all GNOME patches')
278 subparser.add_argument("-p", "--path", action="store_true", dest="path",
279 help="Show full path to patch")
280 subparser.set_defaults(
281 func=cmd_patches, path=False
282 )
283
284 subparser = subparsers.add_parser('dep3', help='Add dep3 headers')
285 subparser.add_argument("patch", help="Patch")
286 subparser.set_defaults(
287 func=cmd_dep3, path=False
288 )
289
290 if len(sys.argv) == 1:
291 parser.print_help()
292 sys.exit(2)
293
294 options = parser.parse_args()
295
296 try:
297 options.func(options, parser)
298 except KeyboardInterrupt:
299 print('Interrupted')
300 sys.exit(1)
301 except EOFError:
302 print('EOF')
303 sys.exit(1)
304 except IOError, e:
305 if e.errno != errno.EPIPE:
306 raise
307 sys.exit(0)
308
309 if __name__ == "__main__":
310 main()

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.30