3 import gzip, os.path, re
5 from os import environ, popen, walk
6 from optparse import OptionParser
9 from xml.sax import ContentHandler, make_parser
10 from xml.sax.handler import feature_external_ges
12 default_books = ['atk', 'gdk', 'gdk-pixbuf', 'glib', 'gio', 'gobject', 'gtk', 'pango']
14 __comment_regex = re.compile(r'/\*.*?\*/', re.DOTALL)
15 __word_regex = re.compile(r'\b[A-Za-z_][A-Za-z0-9_]*\b')
18 def __init__(self, name, folders, version=None):
24 self.__version = version
28 lambda n: os.path.join(f, name, n % name),
29 ['%s.devhelp2', '%s.devhelp2.gz'])
31 lambda n: (os.path.getmtime(n), n),
32 filter(os.path.isfile, catalogs))
37 self.__catalog = catalogs[-1][1]
40 if not self.__catalog:
41 raise IOError, 'No devhelp book found for "%s"' % name
43 def __cmp__(self, other):
44 if isinstance(other, Book):
45 return cmp(self.name, other.name)
50 return '<Book name="%s">' % self.__name
53 timestamp = os.path.getmtime(self.__catalog)
55 if not self.__symbols or timestamp > self.__timestamp:
56 class DevhelpContentHandler(ContentHandler):
57 def __init__(self, book, symbols):
59 self.__symbols = symbols
61 def startElement(self, name, attrs):
63 self.title = attrs.get('title')
67 symbol = Symbol.from_xml(self.__book, attrs)
68 if symbol: self.__symbols[symbol.name] = symbol
71 self.__symbols, self.__timestamp = dict(), timestamp
72 handler = DevhelpContentHandler(self, self.__symbols)
74 parser = make_parser()
75 parser.setFeature(feature_external_ges, False)
76 parser.setContentHandler(handler)
78 if self.__catalog.endswith('.gz'):
79 parser.parse(gzip.open(self.__catalog))
82 parser.parse(open(self.__catalog))
84 self.__title = handler.title
86 def _get_symbols(self):
87 self.parse(); return self.__symbols
89 self.parse(); return self.__title
91 def find_requirements(self):
94 for symbol in self.symbols.values():
95 if not symbol.matches:
98 if symbol.since and symbol.since > self.version:
99 symbol_list = requirements.get(symbol.since, [])
100 requirements[symbol.since] = symbol_list
101 symbol_list.append(symbol)
105 catalog = property(lambda self: self.__catalog)
106 name = property(lambda self: self.__name)
107 version = property(lambda self: self.__version)
109 symbols = property(_get_symbols)
110 title = property(_get_title)
112 class Symbol(object):
113 known_attributes = ('name', 'type', 'link', 'deprecated', 'since')
115 class DeprecationInfo(object):
116 def __init__(self, text):
118 pair = text.split(':', 1)
120 self.__version = Symbol.VersionInfo(pair[0])
121 self.__details = pair[1].strip()
124 self.__version = None
125 self.__details = text.strip()
127 def __cmp__(self, other):
128 if isinstance(other, Symbol.DeprecationInfo):
129 return cmp(self.version, other.version)
131 if isinstance(other, Symbol.VersionInfo):
132 return cmp(self.version, other)
137 if not self.__version:
138 return self.__details and str(self.__details) or 'Deprecated'
141 return 'Since %s: %s' % (self.__version, self.__details)
143 return 'Since %s' % self.__version
145 details = property(lambda self: self.__details)
146 version = property(lambda self: self.__version)
148 class VersionInfo(object):
149 def __init__(self, text):
150 match = re.match(r'^\w*\s*((?:\d+\.)*\d+)', text)
152 self.__numbers = map(int, match.group(1).split('.'))
153 self.__hash = reduce(lambda x, y: x * 1000 + y, reversed(self.__numbers))
154 self.__text = text.strip()
156 def __get_number(self, index):
157 if len(self.__numbers) > index:
158 return self.__numbers[index]
162 def __cmp__(self, other):
163 if isinstance(other, Symbol.VersionInfo):
164 return cmp(self.numbers, other.numbers)
172 return '.'.join(map(str, self.__numbers))
174 major = property(lambda self: self.__get_number(0))
175 minor = property(lambda self: self.__get_number(1))
176 patch = property(lambda self: self.__get_number(2))
177 numbers = property(lambda self: self.__numbers)
178 text = property(lambda self: self.__text)
181 def from_xml(cls, book, attrs):
182 name, type, link, deprecated, since = map(attrs.get, Symbol.known_attributes)
186 if name.endswith('()'):
187 if not type in ('function', 'macro'):
188 type = (name[0].islower() and 'function' or 'macro')
190 name = name[:-2].strip()
192 words = name.split(' ')
195 if words[0] in ('enum', 'struct', 'union'):
196 if not type: type = words[0]
197 name = name[len(words[0]):].strip()
198 elif 'property' == words[-1]:
199 assert('The' == words[0])
200 owner = link.split('#', 1)[1].split('-', 1)[0]
201 type, name = 'property', '%s::%s' % (owner, name.split('"')[1])
202 elif 'signal' == words[-1]:
203 assert('The' == words[0])
204 owner = link.split('#', 1)[1].split('-', 1)[0]
205 type, name = 'signal', '%s:%s' % (owner, name.split('"')[1])
207 if not type: return None
209 if None != deprecated: deprecated = Symbol.DeprecationInfo(deprecated)
210 if since: since = Symbol.VersionInfo(since)
214 'WARNING: Malformed symbol name: "%s" (type=%s) in %s.' % (
215 name, type, book.name))
217 return Symbol(book, name, type, link, deprecated, since)
219 def __init__(self, book, name, type, link=None, deprecated=None, since=None):
224 self.__deprecated = deprecated
230 '<Symbol: %s, type=%s, since=%s, deprecated=%s>' % (
231 self.name, self.type, self.since, self.deprecated))
234 book = property(lambda self: self.__book)
235 name = property(lambda self: self.__name)
236 type = property(lambda self: self.__type)
237 link = property(lambda self: self.__link)
238 deprecated = property(lambda self: self.__deprecated)
239 matches = property(lambda self: self.__matches)
240 since = property(lambda self: self.__since)
243 options = OptionParser(version="@VERSION@")
245 options.add_option('-b', '--book', dest='books',
246 help='name of a devhelp book to consider',
247 default=[], action='append')
248 options.add_option('-d', '--html-dir', metavar='PATH', dest='dirs',
249 help='path of additional folders with devhelp books',
250 default=[], action='append')
251 options.add_option('-s', '--summarize', action='store_true', default=False,
252 help='print only a brief summary', dest='summarize')
253 options.add_option('-u', '--list-unknown', action='store_true', default=False,
254 help='list symbols not found in any book', dest='unknown')
255 options.add_option('-v', '--verbose', action='store_true', default=False,
256 help='print additional information')
258 return options.parse_args()
260 def merge_gnome_path(options):
261 path = environ.get('GNOME2_PATH')
262 path = path and path.split(':') or []
265 'pkg-config --variable=prefix glib-2.0'
266 ).readline().rstrip()
268 path.insert(0, prefix)
269 path = filter(None, [p.strip() for p in path])
272 os.path.join(p, 'share', 'devhelp', 'books'),
273 os.path.join(p, 'share', 'gtk-doc', 'html')]
276 path = reduce(list.__add__, path)
277 path = filter(os.path.isdir, path)
281 def summarize_matches(matches):
283 for filename, lineno, symbol in matches:
284 if not isinstance(symbol, Symbol):
286 print '%s:%d: unknown symbol %s' % (filename, lineno, symbol)
289 since = '%s-%s' % (symbol.book.name, symbol.since)
291 if since not in counts:
293 counts[since][name] = counts[since].get(name, 0) + 1
295 for since, stats in counts.items():
296 counts[since] = list(sorted(stats.items(), key=lambda x: -x[1]))
300 if '__main__' == __name__:
301 options, args = parse_cmdline()
303 merge_gnome_path(options)
305 if not options.books:
306 options.books = default_books
308 def trace(message, *args):
309 if options.verbose: print message % args
311 def parse_book(name):
313 match = re.match(r'^(.*?)(?::(\d+(?:\.\d+)*))?$', name)
314 name, version = match.groups()
315 trace('reading book: %s', name)
317 version = version and Symbol.VersionInfo(version)
318 return name, Book(name, options.dirs, version)
321 print >>stderr, 'WARNING: %s.' % e
323 def scan_source_file(name):
327 contents = __comment_regex.sub('', file(name).read())
333 trace('scanning: %s', name)
334 lines = contents.split('\n')
336 for lineno in range(len(lines)):
337 for word in __word_regex.findall(lines[lineno]):
338 symbol = symbols.get(word)
341 symbol.matches.append((name, lineno, symbol))
343 elif options.unknown and word.find('_') > 0:
344 unknown_symbols.append((name, lineno, word))
347 matches, symbols = dict(), dict()
348 books = dict(filter(None, map(parse_book, set(options.books))))
350 for book in books.values():
351 symbols.update(book.symbols)
354 if os.path.isdir(name):
355 for path, dirs, files in walk(name):
358 scan_source_file(os.path.join(path, f))
361 scan_source_file(name)
365 for book in books.values():
366 requirements = book.find_requirements().items()
370 for symbol in requirements[-1][1]:
371 matches += symbol.matches
374 matches += unknown_symbols
378 if options.summarize:
379 summary = summarize_matches(matches)
380 for since in sorted(summary.keys()):
381 print '%s required for' % since
382 for x in summary[since]:
383 print ' %u %s' % (x[1], x[0])
385 for filename, lineno, symbol in matches:
386 if isinstance(symbol, Symbol):
387 args = filename, lineno, symbol.book.name, symbol.since, symbol.name
388 print '%s:%d: %s-%s required for %s' % args
390 elif options.verbose:
391 print '%s:%d: unknown symbol %s' % (filename, lineno, symbol)
394 unknown = [m[2].split('_')[0].lower() for m in unknown_symbols]
395 unknown = list(set(unknown))
398 print 'unknown prefixes: %s' % ', '.join(unknown)
400 raise SystemExit(matches and 1 or 0)