OLD | NEW |
1 #!/usr/bin/env python | 1 #!/usr/bin/env python |
2 # coding: utf-8 | 2 # coding: utf-8 |
3 | 3 |
4 # This file is part of the Adblock Plus web scripts, | 4 # This file is part of the Adblock Plus web scripts, |
5 # Copyright (C) 2006-2013 Eyeo GmbH | 5 # Copyright (C) 2006-2013 Eyeo GmbH |
6 # | 6 # |
7 # Adblock Plus is free software: you can redistribute it and/or modify | 7 # Adblock Plus is free software: you can redistribute it and/or modify |
8 # it under the terms of the GNU General Public License version 3 as | 8 # it under the terms of the GNU General Public License version 3 as |
9 # published by the Free Software Foundation. | 9 # published by the Free Software Foundation. |
10 # | 10 # |
11 # Adblock Plus is distributed in the hope that it will be useful, | 11 # Adblock Plus is distributed in the hope that it will be useful, |
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of | 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 # GNU General Public License for more details. | 14 # GNU General Public License for more details. |
15 # | 15 # |
16 # You should have received a copy of the GNU General Public License | 16 # You should have received a copy of the GNU General Public License |
17 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. | 17 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. |
18 | 18 |
19 import sys, os, re, subprocess, urllib2, time, traceback, codecs, hashlib, base6
4 | 19 import sys, os, re, subprocess, urllib2, time, traceback, codecs, hashlib, base6
4 |
20 from getopt import getopt, GetoptError | 20 from getopt import getopt, GetoptError |
21 | 21 |
22 acceptedExtensions = { | 22 accepted_extensions = set([".txt"]) |
23 '.txt': True, | 23 ignore = set(["Apache.txt", "CC-BY-SA.txt", "GPL.txt", "MPL.txt"]) |
24 } | 24 verbatim = set(["COPYING"]) |
25 ignore = { | 25 |
26 'Apache.txt': True, | 26 def combine_subscriptions(sources, target_dir, timeout=30): |
27 'CC-BY-SA.txt': True, | 27 if not os.path.exists(target_dir): |
28 'GPL.txt': True, | 28 os.makedirs(target_dir, 0755) |
29 'MPL.txt': True, | 29 |
30 } | 30 known = set() |
31 verbatim = { | 31 for source_name, source in sources.iteritems(): |
32 'COPYING': True, | 32 for filename in source.list_top_level_files(): |
33 } | 33 if filename in ignore or filename.startswith("."): |
34 | |
35 def combineSubscriptions(sourceDirs, targetDir, timeout=30): | |
36 global acceptedExtensions, ignore, verbatim | |
37 | |
38 if isinstance(sourceDirs, basestring): | |
39 sourceDirs = {'': sourceDirs} | |
40 | |
41 if not os.path.exists(targetDir): | |
42 os.makedirs(targetDir, 0755) | |
43 | |
44 known = {} | |
45 for sourceName, sourceDir in sourceDirs.iteritems(): | |
46 for file in os.listdir(sourceDir): | |
47 if file in ignore or file[0] == '.' or not os.path.isfile(os.path.join(sou
rceDir, file)): | |
48 continue | 34 continue |
49 if file in verbatim: | 35 if filename in verbatim: |
50 processVerbatimFile(sourceDir, targetDir, file) | 36 process_verbatim_file(source, target_dir, filename) |
51 elif not os.path.splitext(file)[1] in acceptedExtensions: | 37 elif not os.path.splitext(filename)[1] in accepted_extensions: |
52 continue | 38 continue |
53 else: | 39 else: |
54 try: | 40 try: |
55 processSubscriptionFile(sourceName, sourceDirs, targetDir, file, timeo
ut) | 41 process_subscription_file(source_name, sources, target_dir, filename,
timeout) |
56 except: | 42 except: |
57 print >>sys.stderr, 'Error processing subscription file "%s"' % file | 43 print >>sys.stderr, 'Error processing subscription file "%s"' % filena
me |
58 traceback.print_exc() | 44 traceback.print_exc() |
59 print >>sys.stderr | 45 print >>sys.stderr |
60 known[os.path.splitext(file)[0] + '.tpl'] = True | 46 known.add(os.path.splitext(filename)[0] + ".tpl") |
61 known[os.path.splitext(file)[0] + '.tpl.gz'] = True | 47 known.add(os.path.splitext(filename)[0] + ".tpl.gz") |
62 known[file] = True | 48 known.add(filename) |
63 known[file + '.gz'] = True | 49 known.add(filename + ".gz") |
64 | 50 |
65 for file in os.listdir(targetDir): | 51 for filename in os.listdir(target_dir): |
66 if file[0] == '.': | 52 if filename.startswith("."): |
67 continue | 53 continue |
68 if not file in known: | 54 if not filename in known: |
69 os.remove(os.path.join(targetDir, file)) | 55 os.remove(os.path.join(target_dir, filename)) |
70 | 56 |
71 def saveFile(filePath, data): | 57 def save_file(path, data): |
72 handle = codecs.open(filePath, 'wb', encoding='utf-8') | 58 handle = codecs.open(path, "wb", encoding="utf-8") |
73 handle.write(data) | 59 handle.write(data) |
74 handle.close() | 60 handle.close() |
75 try: | 61 try: |
76 subprocess.check_output(['7za', 'a', '-tgzip', '-mx=9', '-bd', '-mpass=5', f
ilePath + '.gz', filePath]) | 62 subprocess.check_output(["7za", "a", "-tgzip", "-mx=9", "-bd", "-mpass=5", p
ath + ".gz", path]) |
77 except: | 63 except: |
78 print >>sys.stderr, 'Failed to compress file %s. Please ensure that p7zip is
installed on the system.' % filePath | 64 print >>sys.stderr, "Failed to compress file %s. Please ensure that p7zip is
installed on the system." % path |
79 | 65 |
80 def processVerbatimFile(sourceDir, targetDir, file): | 66 def process_verbatim_file(source, target_dir, filename): |
81 handle = codecs.open(os.path.join(sourceDir, file), 'rb', encoding='utf-8') | 67 save_file(os.path.join(target_dir, filename), source.read_file(filename)) |
82 saveFile(os.path.join(targetDir, file), handle.read()) | 68 |
83 handle.close() | 69 def process_subscription_file(source_name, sources, target_dir, filename, timeou
t): |
84 | 70 source = sources[source_name] |
85 def processSubscriptionFile(sourceName, sourceDirs, targetDir, file, timeout): | 71 lines = source.read_file(filename).splitlines() |
86 sourceDir = sourceDirs[sourceName] | 72 |
87 filePath = os.path.join(sourceDir, file) | 73 header = "" |
88 handle = codecs.open(filePath, 'rb', encoding='utf-8') | |
89 lines = map(lambda l: re.sub(r'[\r\n]', '', l), handle.readlines()) | |
90 handle.close() | |
91 | |
92 header = '' | |
93 if len(lines) > 0: | 74 if len(lines) > 0: |
94 header = lines[0] | 75 header = lines.pop(0) |
95 del lines[0] | 76 if not re.search(r"\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]", header, re.I): |
96 if not re.search(r'\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]', header, re.I): | 77 raise Exception("This is not a valid Adblock Plus subscription file.") |
97 raise Exception('This is not a valid Adblock Plus subscription file.') | 78 |
98 | 79 lines = resolve_includes(source_name, sources, lines, timeout) |
99 lines = resolveIncludes(sourceName, sourceDirs, filePath, lines, timeout) | 80 seen = set(["checksum", "version"]) |
100 seen = set(['checksum', 'version']) | 81 def check_line(line): |
101 def checkLine(line): | 82 if line == "": |
102 if line == '': | |
103 return False | 83 return False |
104 match = re.search(r'^\s*!\s*(Redirect|Homepage|Title|Checksum|Version)\s*:',
line, re.M | re.I) | 84 match = re.search(r"^\s*!\s*(Redirect|Homepage|Title|Checksum|Version)\s*:",
line, re.M | re.I) |
105 if not match: | 85 if not match: |
106 return True | 86 return True |
107 key = match.group(1).lower() | 87 key = match.group(1).lower() |
108 if key in seen: | 88 if key in seen: |
109 return False | 89 return False |
110 seen.add(key) | 90 seen.add(key) |
111 return True | 91 return True |
112 lines = filter(checkLine, lines) | 92 lines = filter(check_line, lines) |
113 | 93 |
114 writeTPL(os.path.join(targetDir, os.path.splitext(file)[0] + '.tpl'), lines) | 94 write_tpl(os.path.join(target_dir, os.path.splitext(filename)[0] + ".tpl"), li
nes) |
115 | 95 |
116 lines.insert(0, '! Version: %s' % time.strftime('%Y%m%d%H%M', time.gmtime())) | 96 lines.insert(0, "! Version: %s" % time.strftime("%Y%m%d%H%M", time.gmtime())) |
117 | 97 |
118 checksum = hashlib.md5() | 98 checksum = hashlib.md5() |
119 checksum.update((header + '\n' + '\n'.join(lines)).encode('utf-8')) | 99 checksum.update("\n".join([header] + lines).encode("utf-8")) |
120 lines.insert(0, '! Checksum: %s' % re.sub(r'=', '', base64.b64encode(checksum.
digest()))) | 100 lines.insert(0, "! Checksum: %s" % base64.b64encode(checksum.digest()).rstrip(
"=")) |
121 lines.insert(0, header) | 101 lines.insert(0, header) |
122 saveFile(os.path.join(targetDir, file), '\n'.join(lines)) | 102 save_file(os.path.join(target_dir, filename), "\n".join(lines)) |
123 | 103 |
124 def resolveIncludes(sourceName, sourceDirs, filePath, lines, timeout, level=0): | 104 def resolve_includes(source_name, sources, lines, timeout, level=0): |
125 if level > 5: | 105 if level > 5: |
126 raise Exception('There are too many nested includes, which is probably the r
esult of a circular reference somewhere.') | 106 raise Exception("There are too many nested includes, which is probably the r
esult of a circular reference somewhere.") |
127 | 107 |
128 result = [] | 108 result = [] |
129 for line in lines: | 109 for line in lines: |
130 match = re.search(r'^\s*%include\s+(.*)%\s*$', line) | 110 match = re.search(r"^\s*%include\s+(.*)%\s*$", line) |
131 if match: | 111 if match: |
132 file = match.group(1) | 112 filename = match.group(1) |
133 newLines = None | 113 newlines = None |
134 if re.match(r'^https?://', file): | 114 if re.match(r"^https?://", filename): |
135 result.append('! *** Fetched from: %s ***' % file) | 115 result.append("! *** Fetched from: %s ***" % filename) |
136 | 116 |
137 for i in range(3): | 117 for i in range(3): |
138 try: | 118 try: |
139 request = urllib2.urlopen(file, None, timeout) | 119 request = urllib2.urlopen(filename, None, timeout) |
| 120 data = request.read() |
140 error = None | 121 error = None |
141 break | 122 break |
142 except urllib2.URLError, e: | 123 except urllib2.URLError, e: |
143 error = e | 124 error = e |
144 time.sleep(5) | 125 time.sleep(5) |
145 if error: | 126 if error: |
146 raise error | 127 raise error |
147 | 128 |
148 # We should really get the charset from the headers rather than assuming | 129 # We should really get the charset from the headers rather than assuming |
149 # that it is UTF-8. However, some of the Google Code mirrors are | 130 # that it is UTF-8. However, some of the Google Code mirrors are |
150 # misconfigured and will return ISO-8859-1 as charset instead of UTF-8. | 131 # misconfigured and will return ISO-8859-1 as charset instead of UTF-8. |
151 newLines = unicode(request.read(), 'utf-8').split('\n') | 132 newlines = data.decode("utf-8").splitlines() |
152 newLines = map(lambda l: re.sub(r'[\r\n]', '', l), newLines) | 133 newlines = filter(lambda l: not re.search(r"^\s*!.*?\bExpires\s*(?::|aft
er)\s*(\d+)\s*(h)?", l, re.M | re.I), newlines) |
153 newLines = filter(lambda l: not re.search(r'^\s*!.*?\bExpires\s*(?::|aft
er)\s*(\d+)\s*(h)?', l, re.M | re.I), newLines) | 134 newlines = filter(lambda l: not re.search(r"^\s*!\s*(Redirect|Homepage|T
itle|Version)\s*:", l, re.M | re.I), newlines) |
154 newLines = filter(lambda l: not re.search(r'^\s*!\s*(Redirect|Homepage|T
itle|Version)\s*:', l, re.M | re.I), newLines) | |
155 else: | 135 else: |
156 result.append('! *** %s ***' % file) | 136 result.append("! *** %s ***" % filename) |
157 | 137 |
158 includeSource = sourceName | 138 include_source = source_name |
159 if file.find(':') >= 0: | 139 if ":" in filename: |
160 includeSource, file = file.split(':', 1) | 140 include_source, filename = filename.split(":", 1) |
161 if not includeSource in sourceDirs: | 141 if not include_source in sources: |
162 raise Exception('Cannot include file from repository "%s", this reposi
tory is unknown' % includeSource) | 142 raise Exception('Cannot include file from repository "%s", this reposi
tory is unknown' % include_source) |
163 | 143 |
164 parentDir = sourceDirs[includeSource] | 144 source = sources[include_source] |
165 includePath = os.path.join(parentDir, file) | 145 newlines = source.read_file(filename).splitlines() |
166 relPath = os.path.relpath(includePath, parentDir) | 146 newlines = resolve_includes(include_source, sources, newlines, timeout,
level + 1) |
167 if len(relPath) == 0 or relPath[0] == '.': | 147 |
168 raise Exception('Invalid include "%s", needs to be an HTTP/HTTPS URL o
r a relative file path' % file) | 148 if len(newlines) and re.search(r"\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]", ne
wlines[0], re.I): |
169 | 149 del newlines[0] |
170 handle = codecs.open(includePath, 'rb', encoding='utf-8') | 150 result.extend(newlines) |
171 newLines = map(lambda l: re.sub(r'[\r\n]', '', l), handle.readlines()) | |
172 newLines = resolveIncludes(includeSource, sourceDirs, includePath, newLi
nes, timeout, level + 1) | |
173 handle.close() | |
174 | |
175 if len(newLines) and re.search(r'\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]', ne
wLines[0], re.I): | |
176 del newLines[0] | |
177 result.extend(newLines) | |
178 else: | 151 else: |
179 if line.find('%timestamp%') >= 0: | 152 if line.find("%timestamp%") >= 0: |
180 if level == 0: | 153 if level == 0: |
181 line = line.replace('%timestamp%', time.strftime('%d %b %Y %H:%M UTC',
time.gmtime())) | 154 line = line.replace("%timestamp%", time.strftime("%d %b %Y %H:%M UTC",
time.gmtime())) |
182 else: | 155 else: |
183 line = '' | 156 line = "" |
184 result.append(line) | 157 result.append(line) |
185 return result | 158 return result |
186 | 159 |
187 def writeTPL(filePath, lines): | 160 def write_tpl(path, lines): |
188 result = [] | 161 result = [] |
189 result.append('msFilterList') | 162 result.append("msFilterList") |
190 for line in lines: | 163 for line in lines: |
191 if re.search(r'^!', line): | 164 if re.search(r"^\s*!", line): |
192 # This is a comment. Handle "Expires" comment in a special way, keep the r
est. | 165 # This is a comment. Handle "Expires" comment in a special way, keep the r
est. |
193 match = re.search(r'\bExpires\s*(?::|after)\s*(\d+)\s*(h)?', line, re.I) | 166 match = re.search(r"\bExpires\s*(?::|after)\s*(\d+)\s*(h)?", line, re.I) |
194 if match: | 167 if match: |
195 interval = int(match.group(1)) | 168 interval = int(match.group(1)) |
196 if match.group(2): | 169 if match.group(2): |
197 interval = int(interval / 24) | 170 interval = int(interval / 24) |
198 result.append(': Expires=%i' % interval) | 171 result.append(": Expires=%i" % interval) |
199 else: | 172 else: |
200 result.append(re.sub(r'!', '#', re.sub(r'--!$', '--#', line))) | 173 result.append(re.sub(r"^\s*!", "#", re.sub(r"--!$", "--#", line))) |
201 elif line.find('#') >= 0: | 174 elif line.find("#") >= 0: |
202 # Element hiding rules are not supported in MSIE, drop them | 175 # Element hiding rules are not supported in MSIE, drop them |
203 pass | 176 pass |
204 else: | 177 else: |
205 # We have a blocking or exception rule, try to convert it | 178 # We have a blocking or exception rule, try to convert it |
206 origLine = line | 179 origline = line |
207 | 180 |
208 isException = False | 181 is_exception = False |
209 if line[0:2] == '@@': | 182 if line.startswith("@@"): |
210 isException = True | 183 is_exception = True |
211 line = line[2:] | 184 line = line[2:] |
212 | 185 |
213 hasUnsupportedOptions = False | 186 has_unsupported = False |
214 requiresScript = False | 187 requires_script = False |
215 match = re.search(r'^(.*?)\$(.*)', line) | 188 match = re.search(r"^(.*?)\$(.*)", line) |
216 if match: | 189 if match: |
217 # This rule has options, check whether any of them are important | 190 # This rule has options, check whether any of them are important |
218 line = match.group(1) | 191 line = match.group(1) |
219 options = match.group(2).replace('_', '-').lower().split(',') | 192 options = match.group(2).replace("_", "-").lower().split(",") |
220 | 193 |
221 # Remove first-party only exceptions, we will allow an ad server everywh
ere otherwise | 194 # Remove first-party only exceptions, we will allow an ad server everywh
ere otherwise |
222 if isException and '~third-party' in options: | 195 if is_exception and "~third-party" in options: |
223 hasUnsupportedOptions = True | 196 has_unsupported = True |
224 | 197 |
225 # A number of options are not supported in MSIE but can be safely ignore
d, remove them | 198 # A number of options are not supported in MSIE but can be safely ignore
d, remove them |
226 options = filter(lambda o: not o in ('', 'third-party', '~third-party',
'match-case', '~match-case', '~other', '~donottrack'), options) | 199 options = filter(lambda o: not o in ("", "third-party", "~third-party",
"match-case", "~match-case", "~other", "~donottrack"), options) |
227 | 200 |
228 # Also ignore domain negation of whitelists | 201 # Also ignore domain negation of whitelists |
229 if isException: | 202 if is_exception: |
230 options = filter(lambda o: not o.startswith('domain=~'), options) | 203 options = filter(lambda o: not o.startswith("domain=~"), options) |
231 | 204 |
232 unsupportedOptions = filter(lambda o: o in ('other', 'elemhide'), option
s) | 205 unsupported = filter(lambda o: o in ("other", "elemhide"), options) |
233 if unsupportedOptions and len(unsupportedOptions) == len(options): | 206 if unsupported and len(unsupported) == len(options): |
234 # The rule only applies to types that are not supported in MSIE | 207 # The rule only applies to types that are not supported in MSIE |
235 hasUnsupportedOptions = True | 208 has_unsupported = True |
236 elif 'donottrack' in options: | 209 elif "donottrack" in options: |
237 # Do-Not-Track rules have to be removed even if $donottrack is combine
d with other options | 210 # Do-Not-Track rules have to be removed even if $donottrack is combine
d with other options |
238 hasUnsupportedOptions = True | 211 has_unsupported = True |
239 elif 'script' in options and len(options) == len(unsupportedOptions) + 1
: | 212 elif "script" in options and len(options) == len(unsupported) + 1: |
240 # Mark rules that only apply to scripts for approximate conversion | 213 # Mark rules that only apply to scripts for approximate conversion |
241 requiresScript = True | 214 requires_script = True |
242 elif len(options) > 0: | 215 elif len(options) > 0: |
243 # The rule has further options that aren't available in TPLs. For | 216 # The rule has further options that aren't available in TPLs. For |
244 # exception rules that aren't specific to a domain we ignore all | 217 # exception rules that aren't specific to a domain we ignore all |
245 # remaining options to avoid potential false positives. Other rules | 218 # remaining options to avoid potential false positives. Other rules |
246 # simply aren't included in the TPL file. | 219 # simply aren't included in the TPL file. |
247 if isException: | 220 if is_exception: |
248 hasUnsupportedOptions = any([o.startswith('domain=') for o in option
s]) | 221 has_unsupported = any([o.startswith("domain=") for o in options]) |
249 else: | 222 else: |
250 hasUnsupportedOptions = True | 223 has_unsupported = True |
251 | 224 |
252 if hasUnsupportedOptions: | 225 if has_unsupported: |
253 # Do not include filters with unsupported options | 226 # Do not include filters with unsupported options |
254 result.append('# ' + origLine) | 227 result.append("# " + origline) |
255 else: | 228 else: |
256 line = line.replace('^', '/') # Assume that separator placeholders mean
slashes | 229 line = line.replace("^", "/") # Assume that separator placeholders mean
slashes |
257 | 230 |
258 # Try to extract domain info | 231 # Try to extract domain info |
259 domain = None | 232 domain = None |
260 match = re.search(r'^(\|\||\|\w+://)([^*:/]+)(:\d+)?(/.*)', line) | 233 match = re.search(r"^(\|\||\|\w+://)([^*:/]+)(:\d+)?(/.*)", line) |
261 if match: | 234 if match: |
262 domain = match.group(2) | 235 domain = match.group(2) |
263 line = match.group(4) | 236 line = match.group(4) |
264 else: | 237 else: |
265 # No domain info, remove anchors at the rule start | 238 # No domain info, remove anchors at the rule start |
266 line = re.sub(r'^\|\|', 'http://', line) | 239 line = re.sub(r"^\|\|", "http://", line) |
267 line = re.sub(r'^\|', '', line) | 240 line = re.sub(r"^\|", "", line) |
268 # Remove anchors at the rule end | 241 # Remove anchors at the rule end |
269 line = re.sub(r'\|$', '', line) | 242 line = re.sub(r"\|$", "", line) |
270 # Remove unnecessary asterisks at the ends of lines | 243 # Remove unnecessary asterisks at the ends of lines |
271 line = re.sub(r'\*$', '', line) | 244 line = re.sub(r"\*$", "", line) |
272 # Emulate $script by appending *.js to the rule | 245 # Emulate $script by appending *.js to the rule |
273 if requiresScript: | 246 if requires_script: |
274 line += '*.js' | 247 line += "*.js" |
275 if line.startswith('/*'): | 248 if line.startswith("/*"): |
276 line = line[2:] | 249 line = line[2:] |
277 if domain: | 250 if domain: |
278 line = '%sd %s %s' % ('+' if isException else '-', domain, line) | 251 line = "%sd %s %s" % ("+" if is_exception else "-", domain, line) |
279 line = re.sub(r'\s+/$', '', line) | 252 line = re.sub(r"\s+/$", "", line) |
280 result.append(line) | 253 result.append(line) |
281 elif isException: | 254 elif is_exception: |
282 # Exception rules without domains are unsupported | 255 # Exception rules without domains are unsupported |
283 result.append('# ' + origLine) | 256 result.append("# " + origline) |
284 else: | 257 else: |
285 result.append('- ' + line) | 258 result.append("- " + line) |
286 saveFile(filePath, '\n'.join(result) + '\n') | 259 save_file(path, "\n".join(result) + "\n") |
| 260 |
| 261 class FileSource: |
| 262 def __init__(self, dir): |
| 263 self._dir = dir |
| 264 if os.path.exists(os.path.join(dir, ".hg")): |
| 265 # This is a Mercurial repository, try updating |
| 266 subprocess.call(["hg", "-q", "-R", dir, "pull", "--update"]) |
| 267 |
| 268 def get_path(self, filename): |
| 269 return os.path.join(self._dir, *filename.split("/")) |
| 270 |
| 271 def read_file(self, filename): |
| 272 path = self.get_path(filename) |
| 273 if os.path.relpath(path, self._dir).startswith("."): |
| 274 raise Exception("Attempt to access a file outside the repository") |
| 275 with codecs.open(path, "rb", encoding="utf-8") as handle: |
| 276 return handle.read() |
| 277 |
| 278 def list_top_level_files(self): |
| 279 for filename in os.listdir(self._dir): |
| 280 path = os.path.join(self._dir, filename) |
| 281 if os.path.isfile(path): |
| 282 yield filename |
287 | 283 |
288 def usage(): | 284 def usage(): |
289 print '''Usage: %s [source_dir] [output_dir] | 285 print """Usage: %s source_name=source_dir ... [output_dir] |
290 | 286 |
291 Options: | 287 Options: |
292 -h --help Print this message and exit | 288 -h --help Print this message and exit |
293 -t seconds --timeout=seconds Timeout when fetching remote subscriptions | 289 -t seconds --timeout=seconds Timeout when fetching remote subscriptions |
294 ''' % os.path.basename(sys.argv[0]) | 290 """ % os.path.basename(sys.argv[0]) |
295 | 291 |
296 if __name__ == '__main__': | 292 if __name__ == "__main__": |
297 try: | 293 try: |
298 opts, args = getopt(sys.argv[1:], 'ht:', ['help', 'timeout=']) | 294 opts, args = getopt(sys.argv[1:], "ht:", ["help", "timeout="]) |
299 except GetoptError, e: | 295 except GetoptError, e: |
300 print str(e) | 296 print str(e) |
301 usage() | 297 usage() |
302 sys.exit(2) | 298 sys.exit(2) |
303 | 299 |
304 sourceDir, targetDir = '.', 'subscriptions' | 300 target_dir = "subscriptions" |
305 if len(args) >= 1: | 301 sources = {} |
306 sourceDir = args[0] | 302 for arg in args: |
307 if len(args) >= 2: | 303 if "=" in arg: |
308 targetDir = args[1] | 304 source_name, source_dir = arg.split("=", 1) |
| 305 sources[source_name] = FileSource(source_dir) |
| 306 else: |
| 307 target_dir = arg |
| 308 if not sources: |
| 309 sources[""] = FileSource(".") |
309 | 310 |
310 timeout = 30 | 311 timeout = 30 |
311 for option, value in opts: | 312 for option, value in opts: |
312 if option in ('-h', '--help'): | 313 if option in ("-h", "--help"): |
313 usage() | 314 usage() |
314 sys.exit() | 315 sys.exit() |
315 elif option in ('-t', '--timeout'): | 316 elif option in ("-t", "--timeout"): |
316 timeout = int(value) | 317 timeout = int(value) |
317 | 318 |
318 if os.path.exists(os.path.join(sourceDir, '.hg')): | 319 combine_subscriptions(sources, target_dir, timeout) |
319 # Our source is a Mercurial repository, try updating | |
320 subprocess.check_call(['hg', '-q', '-R', sourceDir, 'pull', '--update']) | |
321 | |
322 combineSubscriptions(sourceDir, targetDir, timeout) | |
OLD | NEW |