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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Sofian Brabez <sbz@FreeBSD.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#
# $FreeBSD$
#
# MAINTAINER= sbz@FreeBSD.org
import argparse
import re
import sys
import urllib2
"""
FreeBSD getpatch handles Gnats and Bugzilla patch attachments
"""
class GetPatch(object):
def __init__(self, pr, category='ports'):
self.pr = pr
self.category = category
self.patchs = list()
self.url = str()
self.patch = str()
self.output_stdout = False
def fetch(self, *largs, **kwargs):
raise NotImplementedError()
def write(self, filename, data):
if filename.endswith(('.patch', '.txt')):
filename = filename[:filename.rindex('.')]+'.diff'
f=open(filename, 'w')
f.write(data)
f.close()
self.out("[+] %s created" % filename)
def get(self,only_last=False, output_stdout=False):
self.output_stdout = output_stdout
self.fetch(self.pr, category=self.category)
if len(self.patchs) == 0:
self.out("[-] No patch found")
sys.exit(1)
if only_last:
self.patchs = [self.patchs.pop()]
for patch in self.patchs:
url = patch['url']
p = patch['name']
data = urllib2.urlopen(url).read()
if self.output_stdout:
sys.stdout.write(data)
else:
self.write(p, data)
def out(self, s):
if not self.output_stdout:
print(s)
class GnatsGetPatch(GetPatch):
URL_BASE = 'http://www.freebsd.org/cgi'
URL = '%s/query-pr.cgi?pr=' % URL_BASE
REGEX = r'<b>Download <a href="([^"]*)">([^<]*)</a>'
def __init__(self, pr, category):
GetPatch.__init__(self, pr, category)
def fetch(self, *largs, **kwargs):
category = kwargs['category']
target = ("%s/%s" % (category, self.pr), "%s" % self.pr)[category=='']
self.out("[+] Fetching patch for pr %s" % target)
pattern = re.compile(self.REGEX)
u = urllib2.urlopen(self.URL+'%s' % target)
data = u.read()
if data == None:
self.out("[-] No patch found")
sys.exit(1)
for patchs in re.findall(pattern, data):
self.patchs.append({'url': patchs[0], 'name': patchs[1]})
class BzGetPatch(GetPatch):
URL_BASE='https://bugzilla.freebsd.org'
URL_SHOW = '%s/show_bug.cgi?id=' % URL_BASE
REGEX_URL = r'<a href="([^<]+)">Details</a>'
REGEX = r'<div class="details">([^ ]+) \(text/plain\)'
def __init__(self, pr, category):
GetPatch.__init__(self, pr, category)
def _extract_patchs_url(self, data):
pattern = re.compile(self.REGEX_URL)
return re.findall(pattern, data)
def _extract_patchs_name(self, urls):
names = []
pattern = re.compile(self.REGEX)
for url in urls:
u = urllib2.urlopen('%s/%s' % (self.URL_BASE, url))
data = u.read()
names.append(re.findall(pattern, data)[0])
return names
def fetch(self, *largs, **kwargs):
category = kwargs['category']
self.out("[+] Fetching patch for pr %s/%s" % (category, self.pr))
u = urllib2.urlopen(self.URL_SHOW+'%s' % self.pr)
data = u.read()
if data == None:
self.out("[-] No patch found")
sys.exit(1)
urls = self._extract_patchs_url(data)
nb_urls = len(urls)
names = self._extract_patchs_name(urls)
nb_names = len(names)
urls = ['%s/%s' % (self.URL_BASE, u[:u.find('&')]) for u in urls]
if nb_names == 0 or nb_urls == 0 or nb_names != nb_urls:
self.out("[-] No patch found")
sys.exit(1)
for i in xrange(nb_urls):
self.patchs.append({'url': urls[i], 'name': names[i]})
def main():
parser = argparse.ArgumentParser(
description='Gets patch attachments from a Bug Tracking System'
)
parser.add_argument('pr', metavar='pr', type=str, nargs=1,
help='Pr id number')
parser.add_argument('--mode', type=str, choices=['gnats','bz'],
default='gnats', help='available modes to retrieve patch')
parser.add_argument('--last', action='store_true',
help='only retrieve the latest iteration of a patch')
parser.add_argument('--stdout', action='store_true',
help='dump patch on stdout')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
category = str()
pr = str(args.pr[0])
if '/' in pr and pr is not None:
category, pr = pr.split('/')
Clazz = globals()['%sGetPatch' % args.mode.capitalize()]
gp = Clazz(pr, category)
gp.get(only_last=args.last, output_stdout=args.stdout)
if __name__ == '__main__':
main()
|