Example #1
0
def do_audit(args):
    """audit [DIRECTORY]"""
    if len(args) == 0:
        audit_stores = stores.stores
    else:
        audit_stores = [zerostore.Store(x) for x in args]

    audit_ls = []
    total = 0
    for a in audit_stores:
        if os.path.isdir(a.dir):
            items = sorted(os.listdir(a.dir))
            audit_ls.append((a.dir, items))
            total += len(items)
        elif len(args):
            raise SafeException(_("No such directory '%s'") % a.dir)

    verified = 0
    failures = []
    i = 0
    for root, impls in audit_ls:
        print(_("Scanning %s") % root)
        for required_digest in impls:
            path = os.path.join(root, required_digest)
            try:
                (alg, digest
                 ) = zerostore.parse_algorithm_digest_pair(required_digest)
            except zerostore.BadDigest:
                print(_("Skipping non-implementation directory %s") % path)
                continue
            i += 1
            try:
                msg = _("[%(done)d / %(total)d] Verifying %(digest)s") % {
                    'done': i,
                    'total': total,
                    'digest': required_digest
                }
                print(msg, end='')
                sys.stdout.flush()
                verify(path, required_digest)
                print("\r" + (" " * len(msg)) + "\r", end='')
                verified += 1
            except zerostore.BadDigest as ex:
                print()
                failures.append(path)
                print(str(ex))
                if ex.detail:
                    print()
                    print(ex.detail)
    if failures:
        print('\n' + _("List of corrupted or modified implementations:"))
        for x in failures:
            print(x)
        print()
    print(_("Checked %d items") % i)
    print(_("Successfully verified implementations: %d") % verified)
    print(_("Corrupted or modified implementations: %d") % len(failures))
    if failures:
        sys.exit(1)
Example #2
0
def do_audit(args):
    """audit [DIRECTORY]"""
    if len(args) == 0:
        audit_stores = stores.stores
    else:
        audit_stores = [zerostore.Store(x) for x in args]

    audit_ls = []
    total = 0
    for a in audit_stores:
        if os.path.isdir(a.dir):
            items = sorted(os.listdir(a.dir))
            audit_ls.append((a.dir, items))
            total += len(items)
        elif len(args):
            raise SafeException(_("No such directory '%s'") % a.dir)

    verified = 0
    failures = []
    i = 0
    for root, impls in audit_ls:
        print _("Scanning %s") % root
        for required_digest in impls:
            i += 1
            path = os.path.join(root, required_digest)
            if '=' not in required_digest:
                print _("Skipping non-implementation directory %s") % path
                continue
            try:
                msg = _("[%(done)d / %(total)d] Verifying %(digest)s") % {
                    'done': i,
                    'total': total,
                    'digest': required_digest
                }
                print msg,
                sys.stdout.flush()
                verify(path, required_digest)
                print "\r" + (" " * len(msg)) + "\r",
                verified += 1
            except zerostore.BadDigest, ex:
                print
                failures.append(path)
                print str(ex)
                if ex.detail:
                    print
                    print ex.detail
Example #3
0
def main(command_args, config=None):
    """Act as if 0install was run with the given arguments.
	@arg command_args: array of arguments (e.g. C{sys.argv[1:]})
	@type command_args: [str]
	"""
    _ensure_standard_fds()

    if config is None:
        from zeroinstall.injector.config import load_config
        config = load_config()

    # The first non-option argument is the command name (or "help" if none is found).
    command = None
    for i, arg in enumerate(command_args):
        if not arg.startswith('-'):
            command = arg
            del command_args[i]
            break
        elif arg == '--':
            break

    verbose = False
    try:
        if command is None:
            return _no_command(command_args)

        if command not in valid_commands:
            raise SafeException(
                _("Unknown sub-command '%s': try --help") % command)

        # Configure a parser for the given command
        module_name = command.replace('-', '_')
        cmd = __import__('zeroinstall.cmd.' + module_name, globals(), locals(),
                         [module_name], 0)
        parser = OptionParser(usage=_("usage: %%prog %s [OPTIONS] %s") %
                              (command, cmd.syntax))

        parser.add_option("-c",
                          "--console",
                          help=_("never use GUI"),
                          action='store_false',
                          dest='gui')
        parser.add_option("",
                          "--dry-run",
                          help=_("just print what would be executed"),
                          action='store_true')
        parser.add_option("-g",
                          "--gui",
                          help=_("show graphical policy editor"),
                          action='store_true')
        parser.add_option("-v",
                          "--verbose",
                          help=_("more verbose output"),
                          action='count')
        parser.add_option("",
                          "--with-store",
                          help=_("add an implementation cache"),
                          action='append',
                          metavar='DIR')

        cmd.add_options(parser)
        (options, args) = parser.parse_args(command_args)

        if options.verbose:
            logger = logging.getLogger()
            if options.verbose == 1:
                logger.setLevel(logging.INFO)
            else:
                logger.setLevel(logging.DEBUG)
            import zeroinstall
            logging.info(
                _("Running 0install %(version)s %(args)s; Python %(python_version)s"
                  ), {
                      'version': zeroinstall.version,
                      'args': repr(command_args),
                      'python_version': sys.version
                  })

        if options.with_store:
            from zeroinstall import zerostore
            for x in options.with_store:
                config.stores.stores.append(zerostore.Store(
                    os.path.abspath(x)))
            logging.info(_("Stores search path is now %s"),
                         config.stores.stores)

        config.handler.dry_run = bool(options.dry_run)

        cmd.handle(config, options, args)
    except UsageError:
        parser.print_help()
        sys.exit(1)
    except SafeException as ex:
        if verbose: raise
        try:
            print >> sys.stderr, unicode(ex)
        except:
            print >> sys.stderr, repr(ex)
        sys.exit(1)
    return
Example #4
0
def main(command_args, config=None):
    """Act as if 0launch was run with the given arguments.
	@arg command_args: array of arguments (e.g. C{sys.argv[1:]})
	@type command_args: [str]
	"""
    # Ensure stdin, stdout and stderr FDs exist, to avoid confusion
    for std in (0, 1, 2):
        try:
            os.fstat(std)
        except OSError:
            fd = os.open('/dev/null', os.O_RDONLY)
            if fd != std:
                os.dup2(fd, std)
                os.close(fd)

    parser = OptionParser(
        usage=_("usage: %prog [options] interface [args]\n"
                "       %prog --list [search-term]\n"
                "       %prog --import [signed-interface-files]\n"
                "       %prog --feed [interface]"))
    parser.add_option("",
                      "--before",
                      help=_("choose a version before this"),
                      metavar='VERSION')
    parser.add_option("",
                      "--command",
                      help=_("command to select"),
                      metavar='COMMAND')
    parser.add_option("-c",
                      "--console",
                      help=_("never use GUI"),
                      action='store_false',
                      dest='gui')
    parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
    parser.add_option("-d",
                      "--download-only",
                      help=_("fetch but don't run"),
                      action='store_true')
    parser.add_option("-D",
                      "--dry-run",
                      help=_("just print actions"),
                      action='store_true')
    parser.add_option("-f",
                      "--feed",
                      help=_("add or remove a feed"),
                      action='store_true')
    parser.add_option("",
                      "--get-selections",
                      help=_("write selected versions as XML"),
                      action='store_true',
                      dest='xml')
    parser.add_option("-g",
                      "--gui",
                      help=_("show graphical policy editor"),
                      action='store_true')
    parser.add_option("-i",
                      "--import",
                      help=_("import from files, not from the network"),
                      action='store_true')
    parser.add_option("-l",
                      "--list",
                      help=_("list all known interfaces"),
                      action='store_true')
    parser.add_option("-m", "--main", help=_("name of the file to execute"))
    parser.add_option("",
                      "--message",
                      help=_("message to display when interacting with user"))
    parser.add_option("",
                      "--not-before",
                      help=_("minimum version to choose"),
                      metavar='VERSION')
    parser.add_option("",
                      "--os",
                      help=_("target operation system type"),
                      metavar='OS')
    parser.add_option("-o",
                      "--offline",
                      help=_("try to avoid using the network"),
                      action='store_true')
    parser.add_option("-r",
                      "--refresh",
                      help=_("refresh all used interfaces"),
                      action='store_true')
    parser.add_option("",
                      "--select-only",
                      help=_("only download the feeds"),
                      action='store_true')
    parser.add_option("",
                      "--set-selections",
                      help=_("run versions specified in XML file"),
                      metavar='FILE')
    parser.add_option("",
                      "--show",
                      help=_("show where components are installed"),
                      action='store_true')
    parser.add_option("-s",
                      "--source",
                      help=_("select source code"),
                      action='store_true')
    parser.add_option("-v",
                      "--verbose",
                      help=_("more verbose output"),
                      action='count')
    parser.add_option("-V",
                      "--version",
                      help=_("display version information"),
                      action='store_true')
    parser.add_option("",
                      "--with-store",
                      help=_("add an implementation cache"),
                      action='append',
                      metavar='DIR')
    parser.add_option("-w",
                      "--wrapper",
                      help=_("execute program using a debugger, etc"),
                      metavar='COMMAND')
    parser.disable_interspersed_args()

    (options, args) = parser.parse_args(command_args)

    if options.verbose:
        logger = logging.getLogger()
        if options.verbose == 1:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.DEBUG)
        import zeroinstall
        logging.info(
            _("Running 0launch %(version)s %(args)s; Python %(python_version)s"
              ), {
                  'version': zeroinstall.version,
                  'args': repr(args),
                  'python_version': sys.version
              })

    if options.select_only or options.show:
        options.download_only = True

    if config is None:
        config = load_config()
        config.handler.dry_run = bool(options.dry_run)

    if options.with_store:
        from zeroinstall import zerostore
        for x in options.with_store:
            config.stores.stores.append(zerostore.Store(os.path.abspath(x)))
        logging.info(_("Stores search path is now %s"), config.stores.stores)

    if options.set_selections:
        args = [options.set_selections] + args

    try:
        if options.list:
            from zeroinstall.cmd import list
            list.handle(config, options, args)
        elif options.version:
            import zeroinstall
            print("0launch (zero-install) " + zeroinstall.version)
            print("Copyright (C) 2010 Thomas Leonard")
            print(
                _("This program comes with ABSOLUTELY NO WARRANTY,"
                  "\nto the extent permitted by law."
                  "\nYou may redistribute copies of this program"
                  "\nunder the terms of the GNU Lesser General Public License."
                  "\nFor more information about these matters, see the file named COPYING."
                  ))
        elif getattr(options, 'import'):
            # (import is a keyword)
            cmd = __import__('zeroinstall.cmd.import', globals(), locals(),
                             ["import"], 0)
            cmd.handle(config, options, args)
        elif options.feed:
            from zeroinstall.cmd import add_feed
            add_feed.handle(config, options, args, add_ok=True, remove_ok=True)
        elif options.select_only:
            from zeroinstall.cmd import select
            if not options.show:
                options.quiet = True
            select.handle(config, options, args)
        elif options.download_only or options.xml or options.show:
            from zeroinstall.cmd import download
            download.handle(config, options, args)
        else:
            if len(args) < 1:
                if options.gui:
                    from zeroinstall import helpers
                    return helpers.get_selections_gui(None, [])
                else:
                    raise UsageError()
            else:
                from zeroinstall.cmd import run
                run.handle(config, options, args)
    except NeedDownload as ex:
        # This only happens for dry runs
        print(ex)
    except KeyboardInterrupt:
        logging.info("KeyboardInterrupt")
        sys.exit(1)
    except UsageError:
        parser.print_help()
        sys.exit(1)
    except SafeException as ex:
        if options.verbose: raise
        try:
            print(unicode(ex), file=sys.stderr)
        except:
            print(repr(ex), file=sys.stderr)
        sys.exit(1)
Example #5
0
def run_gui(args):
	parser = OptionParser(usage=_("usage: %prog [options] interface"))
	parser.add_option("", "--before", help=_("choose a version before this"), metavar='VERSION')
	parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
	parser.add_option("-c", "--cache", help=_("show the cache"), action='store_true')
	parser.add_option("-d", "--download-only", help=_("fetch but don't run"), action='store_true')
	parser.add_option("", "--message", help=_("message to display when interacting with user"))
	parser.add_option("", "--not-before", help=_("minimum version to choose"), metavar='VERSION')
	parser.add_option("", "--os", help=_("target operation system type"), metavar='OS')
	parser.add_option("-r", "--refresh", help=_("check for updates of all interfaces"), action='store_true')
	parser.add_option("-s", "--source", help=_("select source code"), action='store_true')
	parser.add_option("", "--systray", help=_("download in the background"), action='store_true')
	parser.add_option("-v", "--verbose", help=_("more verbose output"), action='count')
	parser.add_option("-V", "--version", help=_("display version information"), action='store_true')
	parser.add_option("", "--with-store", help=_("add an implementation cache"), action='append', metavar='DIR')

	parser.disable_interspersed_args()

	(options, args) = parser.parse_args(args)

	if options.verbose:
		import logging
		logger = logging.getLogger()
		if options.verbose == 1:
			logger.setLevel(logging.INFO)
		else:
			logger.setLevel(logging.DEBUG)

	if options.cache:
		# Must fork before importing gtk, or ATK dies
		if os.fork():
			# We exit, so our parent can call waitpid and unblock.
			sys.exit(0)
		# The grandchild continues...

	if options.with_store:
		from zeroinstall import zerostore
		for x in options.with_store:
			iface_cache.stores.stores.append(zerostore.Store(os.path.abspath(x)))

	import gui

	if options.version:
		print "0launch-gui (zero-install) " + gui.version
		print "Copyright (C) 2009 Thomas Leonard"
		print _("This program comes with ABSOLUTELY NO WARRANTY,"
				"\nto the extent permitted by law."
				"\nYou may redistribute copies of this program"
				"\nunder the terms of the GNU Lesser General Public License."
				"\nFor more information about these matters, see the file named COPYING.")
		sys.exit(0)

	import gtk
	if gtk.gdk.get_display() is None:
		print >>sys.stderr, "Failed to connect to display. Aborting."
		sys.exit(1)

	if not hasattr(gtk, 'combo_box_new_text'):
		import combo_compat

	if options.cache:
		import cache
		cache_explorer = cache.CacheExplorer()
		cache_explorer.show()
		cache_explorer.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
		gtk.gdk.flush()
		cache_explorer.populate_model()
		cache_explorer.window.set_cursor(None)
		gtk.main()
		sys.exit(0)

	handler = gui.GUIHandler()

	if len(args) < 1:
		import preferences
		# Once we separate configuration from Policy, this hack can go away
		class DummyPolicy(Policy):
			def recalculate(fetch_stale_interfaces = True):
				pass
			def solve_with_downloads(force = False):
				pass
		box = preferences.show_preferences(DummyPolicy('http://localhost/dummy', handler))
		box.connect('destroy', gtk.main_quit)
		gtk.main()
		sys.exit(0)

	interface_uri = args[0]

	if len(args) > 1:
		parser.print_help()
		sys.exit(1)

	import mainwindow, dialog

	restrictions = []
	if options.before or options.not_before:
		restrictions.append(model.VersionRangeRestriction(model.parse_version(options.before),
								  model.parse_version(options.not_before)))

	widgets = dialog.Template('main')

	policy = Policy(interface_uri, handler, src = bool(options.source))
	policy.target_arch = arch.get_architecture(options.os, options.cpu)
	root_iface = iface_cache.get_interface(interface_uri)
	policy.solver.extra_restrictions[root_iface] = restrictions
	policy.solver.record_details = True

	window = mainwindow.MainWindow(policy, widgets, download_only = bool(options.download_only))
	handler.mainwindow = window

	if options.message:
		window.set_message(options.message)

	root = iface_cache.get_interface(policy.root)
	window.browser.set_root(root)

	window.window.connect('destroy', lambda w: handler.abort_all_downloads())

	if options.systray:
		window.use_systray_icon()

	@tasks.async
	def main():
		force_refresh = bool(options.refresh)
		while True:
			window.refresh_button.set_sensitive(False)
			window.browser.set_update_icons(force_refresh)

			solved = policy.solve_with_downloads(force = force_refresh)

			if not window.systray_icon:
				window.show()
			yield solved
			try:
				window.refresh_button.set_sensitive(True)
				tasks.check(solved)
			except Exception, ex:
				window.report_exception(ex)

			if window.systray_icon and window.systray_icon.get_visible() and \
			   window.systray_icon.is_embedded():
				if policy.ready:
					window.systray_icon.set_tooltip(_('Downloading updates for %s') % root_iface.get_name())
					window.run_button.set_active(True)
				else:
					# Should already be reporting an error, but
					# blink it again just in case
					window.systray_icon.set_blinking(True)

			yield dialog.ButtonClickedBlocker(window.refresh_button)
			force_refresh = True
Example #6
0
from zeroinstall import zerostore
from zeroinstall.injector.model import network_minimal

from zeroinstall.injector import handler
from zeroinstall.injector import trust

trust_db = trust.TrustDB()

config = load_config()
config.network_use = network_minimal
config.feed_mirror = None

# Reads from ~/.config/0install.net/implementation-dirs - default empty
# Just take default and manually append
stores = zerostore.Stores()
pluginStore = zerostore.Store('/results/plugins/implementations')
stores.stores.append(pluginStore)


class AntiTrustMgr(trust.TrustMgr):
    """
    subclass trust.TrustMgr so we can replace the confim_keys method to accept our keys without input
    """
    def confirm_keys(self, pending):

        assert pending.sigs

        from zeroinstall.injector import gpg
        valid_sigs = [s for s in pending.sigs if isinstance(s, gpg.ValidSig)]
        if not valid_sigs:
Example #7
0
def main(command_args, config=None):
    """Act as if 0install was run with the given arguments.
	@type command_args: [str]
	@type config: L{zeroinstall.injector.config.Config} | None
	@arg command_args: array of arguments (e.g. C{sys.argv[1:]})"""
    _ensure_standard_fds()

    if config is None:
        from zeroinstall.injector.config import load_config
        config = load_config()

    completion = None
    if command_args and command_args[0] == '_complete':
        shell = command_args[1]
        command_args = command_args[3:]
        # command_args[2] == "0install"
        completion = _Completion(config, command_args, shell=shell)

    # The first non-option argument is the command name (or "help" if none is found).
    command = None
    for i, arg in enumerate(command_args):
        if not arg.startswith('-'):
            command = arg
            command_args = command_args[:i] + command_args[i + 1:]
            if completion:
                completion.got_command(command, i)
            break
        elif arg == '--':
            break
    else:
        if completion:
            completion.got_command(None, len(command_args))

    verbose = False
    try:
        # Configure a parser for the given command
        my_name = os.path.basename(sys.argv[0])
        if my_name == '0launch':
            my_name = '0install'  # Hack for --python-fallback
        if command:
            if command not in valid_commands:
                if completion:
                    return
                raise SafeException(
                    _("Unknown sub-command '%s': try --help") % command)

            module_name = command.replace('-', '_')
            cmd = __import__('zeroinstall.cmd.' + module_name, globals(),
                             locals(), [module_name], 0)
            parser = OptionParser(usage=_("usage: %s %s [OPTIONS] %s") %
                                  (my_name, command, cmd.syntax))
        else:
            cmd = NoCommand()
            parser = OptionParser(usage=_(
                "usage: %s COMMAND\n\nTry --help with one of these:%s") %
                                  (my_name, "\n\n0install " +
                                   '\n0install '.join(valid_commands)))

        parser.add_option("-c",
                          "--console",
                          help=_("never use GUI"),
                          action='store_false',
                          dest='gui')
        parser.add_option("",
                          "--dry-run",
                          help=_("just print what would be executed"),
                          action='store_true')
        parser.add_option("-g",
                          "--gui",
                          help=_("show graphical policy editor"),
                          action='store_true')
        parser.add_option("-v",
                          "--verbose",
                          help=_("more verbose output"),
                          action='count')
        parser.add_option("",
                          "--with-store",
                          help=_("add an implementation cache"),
                          action='append',
                          metavar='DIR')

        cmd.add_options(parser)

        if completion:
            completion.complete(parser, cmd)
            return

        (options, args) = parser.parse_args(command_args)
        verbose = options.verbose

        if options.verbose:
            if options.verbose == 1:
                logger.setLevel(logging.INFO)
            else:
                logger.setLevel(logging.DEBUG)
            import zeroinstall
            logger.info(
                _("Running 0install %(version)s %(args)s; Python %(python_version)s"
                  ), {
                      'version': zeroinstall.version,
                      'args': repr(command_args),
                      'python_version': sys.version
                  })

        if options.with_store:
            from zeroinstall import zerostore
            for x in options.with_store:
                config.stores.stores.append(zerostore.Store(
                    os.path.abspath(x)))
            logger.info(_("Stores search path is now %s"),
                        config.stores.stores)

        config.handler.dry_run = bool(options.dry_run)
        if config.handler.dry_run:
            if options.gui is True:
                raise SafeException(_("Can't use --gui with --dry-run"))
            options.gui = False

        cmd.handle(config, options, args)
    except KeyboardInterrupt:
        logger.info("KeyboardInterrupt")
        sys.exit(1)
    except UsageError:
        parser.print_help()
        sys.exit(1)
    except DryRun as ex:
        print(_("[dry-run]"), ex)
    except SafeException as ex:
        if verbose: raise
        try:
            from zeroinstall.support import unicode
            print(unicode(ex), file=sys.stderr)
        except:
            print(repr(ex), file=sys.stderr)
        sys.exit(1)
    return
Example #8
0
def run_gui(args):
    parser = OptionParser(usage=_("usage: %prog [options] interface"))
    parser.add_option("",
                      "--before",
                      help=_("choose a version before this"),
                      metavar='VERSION')
    parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
    parser.add_option("",
                      "--command",
                      help=_("command to select"),
                      metavar='COMMAND')
    parser.add_option("-d",
                      "--download-only",
                      help=_("fetch but don't run"),
                      action='store_true')
    parser.add_option("",
                      "--message",
                      help=_("message to display when interacting with user"))
    parser.add_option("",
                      "--not-before",
                      help=_("minimum version to choose"),
                      metavar='VERSION')
    parser.add_option("",
                      "--os",
                      help=_("target operation system type"),
                      metavar='OS')
    parser.add_option("-r",
                      "--refresh",
                      help=_("check for updates of all interfaces"),
                      action='store_true')
    parser.add_option("",
                      "--select-only",
                      help=_("only download the feeds"),
                      action='store_true')
    parser.add_option("-s",
                      "--source",
                      help=_("select source code"),
                      action='store_true')
    parser.add_option("",
                      "--systray",
                      help=_("download in the background"),
                      action='store_true')
    parser.add_option("-v",
                      "--verbose",
                      help=_("more verbose output"),
                      action='count')
    parser.add_option("-V",
                      "--version",
                      help=_("display version information"),
                      action='store_true')
    parser.add_option("",
                      "--with-store",
                      help=_("add an implementation cache"),
                      action='append',
                      metavar='DIR')

    parser.disable_interspersed_args()

    (options, args) = parser.parse_args(args)

    if options.verbose:
        import logging
        logger = logging.getLogger()
        if options.verbose == 1:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.DEBUG)

    import gui

    if options.version:
        print "0launch-gui (zero-install) " + gui.version
        print "Copyright (C) 2010 Thomas Leonard"
        print _(
            "This program comes with ABSOLUTELY NO WARRANTY,"
            "\nto the extent permitted by law."
            "\nYou may redistribute copies of this program"
            "\nunder the terms of the GNU Lesser General Public License."
            "\nFor more information about these matters, see the file named COPYING."
        )
        sys.exit(0)

    import gtk
    if gtk.gdk.get_display() is None:
        print >> sys.stderr, "Failed to connect to display. Aborting."
        sys.exit(1)

    handler = gui.GUIHandler()

    config = load_config(handler)

    if options.with_store:
        from zeroinstall import zerostore
        for x in options.with_store:
            config.stores.stores.append(zerostore.Store(os.path.abspath(x)))

    if len(args) < 1:
        import preferences
        box = preferences.show_preferences(config)
        box.connect('destroy', gtk.main_quit)
        gtk.main()
        sys.exit(0)

    interface_uri = args[0]

    if len(args) > 1:
        parser.print_help()
        sys.exit(1)

    import mainwindow, dialog

    r = requirements.Requirements(interface_uri)
    r.parse_options(options)

    widgets = dialog.Template('main')

    policy = Policy(config=config, requirements=r)
    root_iface = config.iface_cache.get_interface(interface_uri)
    policy.solver.record_details = True

    window = mainwindow.MainWindow(policy,
                                   widgets,
                                   download_only=bool(options.download_only),
                                   select_only=bool(options.select_only))
    handler.mainwindow = window

    if options.message:
        window.set_message(options.message)

    root = config.iface_cache.get_interface(policy.root)
    window.browser.set_root(root)

    window.window.connect('destroy', lambda w: handler.abort_all_downloads())

    if options.systray:
        window.use_systray_icon()

    @tasks. async
    def main():
        force_refresh = bool(options.refresh)
        while True:
            window.refresh_button.set_sensitive(False)
            window.browser.set_update_icons(force_refresh)

            solved = policy.solve_with_downloads(force=force_refresh,
                                                 update_local=True)

            if not window.systray_icon:
                window.show()
            yield solved
            try:
                window.refresh_button.set_sensitive(True)
                window.browser.highlight_problems()
                tasks.check(solved)
            except Exception as ex:
                window.report_exception(ex)

            if window.systray_icon and window.systray_icon.get_visible() and \
               window.systray_icon.is_embedded():
                if policy.ready:
                    window.systray_icon.set_tooltip(
                        _('Downloading updates for %s') %
                        root_iface.get_name())
                    window.run_button.set_active(True)
                else:
                    # Should already be reporting an error, but
                    # blink it again just in case
                    window.systray_icon.set_blinking(True)

            refresh_clicked = dialog.ButtonClickedBlocker(
                window.refresh_button)
            yield refresh_clicked, _recalculate

            if refresh_clicked.happened:
                force_refresh = True

    tasks.wait_for_blocker(main())
Example #9
0
def main(command_args):
	"""Act as if 0launch was run with the given arguments.
	@arg command_args: array of arguments (e.g. C{sys.argv[1:]})
	@type command_args: [str]
	"""
	# Ensure stdin, stdout and stderr FDs exist, to avoid confusion
	for std in (0, 1, 2):
		try:
			os.fstat(std)
		except OSError:
			fd = os.open('/dev/null', os.O_RDONLY)
			if fd != std:
				os.dup2(fd, std)
				os.close(fd)

	parser = OptionParser(usage=_("usage: %prog [options] interface [args]\n"
				    "       %prog --list [search-term]\n"
				    "       %prog --import [signed-interface-files]\n"
				    "       %prog --feed [interface]"))
	parser.add_option("", "--before", help=_("choose a version before this"), metavar='VERSION')
	parser.add_option("-c", "--console", help=_("never use GUI"), action='store_false', dest='gui')
	parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
	parser.add_option("-d", "--download-only", help=_("fetch but don't run"), action='store_true')
	parser.add_option("-D", "--dry-run", help=_("just print actions"), action='store_true')
	parser.add_option("-f", "--feed", help=_("add or remove a feed"), action='store_true')
	parser.add_option("", "--get-selections", help=_("write selected versions as XML"), action='store_true')
	parser.add_option("-g", "--gui", help=_("show graphical policy editor"), action='store_true')
	parser.add_option("-i", "--import", help=_("import from files, not from the network"), action='store_true')
	parser.add_option("-l", "--list", help=_("list all known interfaces"), action='store_true')
	parser.add_option("-m", "--main", help=_("name of the file to execute"))
	parser.add_option("", "--message", help=_("message to display when interacting with user"))
	parser.add_option("", "--not-before", help=_("minimum version to choose"), metavar='VERSION')
	parser.add_option("", "--os", help=_("target operation system type"), metavar='OS')
	parser.add_option("-o", "--offline", help=_("try to avoid using the network"), action='store_true')
	parser.add_option("-r", "--refresh", help=_("refresh all used interfaces"), action='store_true')
	parser.add_option("", "--set-selections", help=_("run versions specified in XML file"), metavar='FILE')
	parser.add_option("-s", "--source", help=_("select source code"), action='store_true')
	parser.add_option("", "--systray", help=_("download in the background"), action='store_true')
	parser.add_option("-v", "--verbose", help=_("more verbose output"), action='count')
	parser.add_option("-V", "--version", help=_("display version information"), action='store_true')
	parser.add_option("", "--with-store", help=_("add an implementation cache"), action='append', metavar='DIR')
	parser.add_option("-w", "--wrapper", help=_("execute program using a debugger, etc"), metavar='COMMAND')
	parser.disable_interspersed_args()

	(options, args) = parser.parse_args(command_args)

	if options.verbose:
		logger = logging.getLogger()
		if options.verbose == 1:
			logger.setLevel(logging.INFO)
		else:
			logger.setLevel(logging.DEBUG)
		import zeroinstall
		logging.info(_("Running 0launch %(version)s %(args)s; Python %(python_version)s"), {'version': zeroinstall.version, 'args': repr(args), 'python_version': sys.version})

	if options.with_store:
		from zeroinstall import zerostore
		for x in options.with_store:
			iface_cache.stores.stores.append(zerostore.Store(os.path.abspath(x)))
		logging.info(_("Stores search path is now %s"), iface_cache.stores.stores)

	try:
		if options.list:
			_list_interfaces(args)
		elif options.version:
			import zeroinstall
			print "0launch (zero-install) " + zeroinstall.version
			print "Copyright (C) 2009 Thomas Leonard"
			print _("This program comes with ABSOLUTELY NO WARRANTY,"
					"\nto the extent permitted by law."
					"\nYou may redistribute copies of this program"
					"\nunder the terms of the GNU Lesser General Public License."
					"\nFor more information about these matters, see the file named COPYING.")
		elif options.set_selections:
			from zeroinstall.injector import qdom, run
			sels = selections.Selections(qdom.parse(file(options.set_selections)))
			_download_missing_selections(options, sels)
			if not options.download_only:
				run.execute_selections(sels, args, options.dry_run, options.main, options.wrapper)
		elif getattr(options, 'import'):
			_import_feed(args)
		elif options.feed:
			_manage_feeds(options, args)
		else:
			_normal_mode(options, args)
	except UsageError:
		parser.print_help()
		sys.exit(1)
	except SafeException, ex:
		if options.verbose: raise
		print >>sys.stderr, ex
		sys.exit(1)
Example #10
0
def run_gui(args):
    parser = OptionParser(usage=_("usage: %prog [options] interface"))
    parser.add_option("",
                      "--before",
                      help=_("choose a version before this"),
                      metavar='VERSION')
    parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
    parser.add_option("",
                      "--command",
                      help=_("command to select"),
                      metavar='COMMAND')
    parser.add_option("-d",
                      "--download-only",
                      help=_("fetch but don't run"),
                      action='store_true')
    parser.add_option("-g",
                      "--force-gui",
                      help=_("display an error if there's no GUI"),
                      action='store_true')
    parser.add_option("",
                      "--message",
                      help=_("message to display when interacting with user"))
    parser.add_option("",
                      "--not-before",
                      help=_("minimum version to choose"),
                      metavar='VERSION')
    parser.add_option("",
                      "--os",
                      help=_("target operation system type"),
                      metavar='OS')
    parser.add_option("-r",
                      "--refresh",
                      help=_("check for updates of all interfaces"),
                      action='store_true')
    parser.add_option("",
                      "--select-only",
                      help=_("only download the feeds"),
                      action='store_true')
    parser.add_option("-s",
                      "--source",
                      help=_("select source code"),
                      action='store_true')
    parser.add_option("",
                      "--systray",
                      help=_("download in the background"),
                      action='store_true')
    parser.add_option("-v",
                      "--verbose",
                      help=_("more verbose output"),
                      action='count')
    parser.add_option("-V",
                      "--version",
                      help=_("display version information"),
                      action='store_true')
    parser.add_option(
        "",
        "--version-for",
        help=_("set version constraints for a specific interface"),
        nargs=2,
        metavar='URI RANGE',
        action='append')
    parser.add_option("",
                      "--with-store",
                      help=_("add an implementation cache"),
                      action='append',
                      metavar='DIR')

    parser.disable_interspersed_args()

    (options, args) = parser.parse_args(args)

    if options.verbose:
        logger = logging.getLogger()
        if options.verbose == 1:
            logger.setLevel(logging.INFO)
        else:
            logger.setLevel(logging.DEBUG)

    if options.version:
        import gui
        print("0launch-gui (zero-install) " + gui.version)
        print("Copyright (C) 2010 Thomas Leonard")
        print(
            _("This program comes with ABSOLUTELY NO WARRANTY,"
              "\nto the extent permitted by law."
              "\nYou may redistribute copies of this program"
              "\nunder the terms of the GNU Lesser General Public License."
              "\nFor more information about these matters, see the file named COPYING."
              ))
        sys.exit(0)

    def nogui(ex):
        if options.force_gui:
            fn = logging.warn
        else:
            fn = logging.info
            fn("No GUI available", exc_info=ex)
        sys.exit(100)

    with warnings.catch_warnings():
        if not options.force_gui:
            warnings.filterwarnings("ignore")
        if sys.version_info[0] < 3:
            try:
                import pygtk
                pygtk.require('2.0')
            except ImportError as ex:
                nogui(ex)

        import gui

        try:
            if sys.version_info[0] > 2:
                from zeroinstall.gtkui import pygtkcompat
                pygtkcompat.enable()
                pygtkcompat.enable_gtk(version='3.0')
            import gtk
        except (ImportError, ValueError, RuntimeError) as ex:
            nogui(ex)

        if gtk.gdk.get_display() is None:
            try:
                raise SafeException("Failed to connect to display.")
            except SafeException as ex:
                nogui(ex)  # logging needs this as a raised exception

    handler = gui.GUIHandler()

    config = load_config(handler)

    if options.with_store:
        from zeroinstall import zerostore
        for x in options.with_store:
            config.stores.stores.append(zerostore.Store(os.path.abspath(x)))

    if len(args) < 1:

        @tasks. async
        def prefs_main():
            import preferences
            box = preferences.show_preferences(config)
            done = tasks.Blocker('close preferences')
            box.connect('destroy', lambda w: done.trigger())
            yield done

        tasks.wait_for_blocker(prefs_main())
        sys.exit(0)

    interface_uri = args[0]

    if len(args) > 1:
        parser.print_help()
        sys.exit(1)

    import mainwindow, dialog

    r = requirements.Requirements(interface_uri)
    r.parse_options(options)

    widgets = dialog.Template('main')

    driver = Driver(config=config, requirements=r)
    root_iface = config.iface_cache.get_interface(interface_uri)
    driver.solver.record_details = True

    window = mainwindow.MainWindow(driver,
                                   widgets,
                                   download_only=bool(options.download_only),
                                   select_only=bool(options.select_only))
    handler.mainwindow = window

    if options.message:
        window.set_message(options.message)

    root = config.iface_cache.get_interface(r.interface_uri)
    window.browser.set_root(root)

    window.window.connect('destroy', lambda w: handler.abort_all_downloads())

    if options.systray:
        window.use_systray_icon()

    @tasks. async
    def main():
        force_refresh = bool(options.refresh)
        while True:
            window.refresh_button.set_sensitive(False)
            window.browser.set_update_icons(force_refresh)

            solved = driver.solve_with_downloads(force=force_refresh,
                                                 update_local=True)

            if not window.systray_icon:
                window.show()
            yield solved
            try:
                window.refresh_button.set_sensitive(True)
                window.browser.highlight_problems()
                tasks.check(solved)
            except Exception as ex:
                window.report_exception(ex)

            if window.systray_icon and window.systray_icon.get_visible() and \
               window.systray_icon.is_embedded():
                if driver.solver.ready:
                    window.systray_icon.set_tooltip(
                        _('Downloading updates for %s') %
                        root_iface.get_name())
                    window.run_button.set_active(True)
                else:
                    # Should already be reporting an error, but
                    # blink it again just in case
                    window.systray_icon.set_blinking(True)

            refresh_clicked = dialog.ButtonClickedBlocker(
                window.refresh_button)
            yield refresh_clicked, _recalculate

            if refresh_clicked.happened:
                force_refresh = True

    tasks.wait_for_blocker(main())