Skip to content

Instantly share code, notes, and snippets.

@achadwick
Last active February 27, 2017 19:19
Show Gist options
  • Save achadwick/2647305f34fb31169f29 to your computer and use it in GitHub Desktop.
Save achadwick/2647305f34fb31169f29 to your computer and use it in GitHub Desktop.
Python-GI name search tool
#!/usr/bin/env python
# Search for names known to Python GObject-Introspection.
# All rights waived: https://creativecommons.org/publicdomain/zero/1.0/
from __future__ import print_function
import importlib
import os.path
import sys
import re
from optparse import OptionParser
import gi
_USAGE = "usage: %prog [options] ns[.sub.module] [regex...]"
_DESCRIPTION = (
"Imports ns from gi.repository, "
"then searches ns[.sub.module]'s contents "
"for names matching all of the regular expressions. "
"If there are no regexes on the command line, "
"all the target module's contents will be listed."
)
def _process_command_line():
parser = OptionParser(usage=_USAGE, description=_DESCRIPTION)
parser.add_option(
"-i", "--ignore-case",
action="store_true",
help="ignore case when searching",
default=False,
)
parser.add_option(
"-v", "--verbose",
action="store_true",
help="more verbose output",
default=False,
)
parser.add_option(
"-r", "--require-version",
help="require a particular version of ns",
metavar="VERSION",
)
options, args = parser.parse_args(sys.argv)
try:
gimodname = args[1]
patterns = args[2:]
except IndexError:
parser.error(msg="Required argument missing")
parser.exit(status=2)
return (options, gimodname, patterns)
def _main():
opts, gimodname, patterns = _process_command_line()
namespace = gimodname.split(".", 1)[0]
if opts.verbose:
print(
"from gi.repository import {}".format(namespace),
file=sys.stderr,
)
gi_import_name = "gi.repository.{}".format(namespace)
if opts.require_version:
gi.require_version(namespace, opts.require_version)
importlib.import_module(gi_import_name)
flags = 0
if opts.ignore_case:
flags |= re.I
mod = eval("gi.repository.%s" % gimodname)
patterns = [re.compile(p, flags) for p in patterns]
if opts.verbose:
template = "{module}.{item}"
else:
template = "{item}"
for name in dir(mod):
if patterns and not all([re.search(p, name) for p in patterns]):
continue
print(template.format(
module = gimodname,
item = name,
))
if __name__ == "__main__":
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment