def testConfig(self): out, err = self.run_0install(['config', '--help']) assert out.lower().startswith("usage:") assert '--console' in out out, err = self.run_0install(['config']) assert not err, err assert 'full' in out, out assert 'freshness = 0' in out, out assert 'help_with_testing = False' in out, out out, err = self.run_0install(['config', 'help_with_testing']) assert out == 'False\n', out file_config = policy.load_config(handler.Handler()) def get_value(name): old_stdout = sys.stdout sys.stdout = StringIO() try: cmd.config.handle(file_config, None, [name]) cmd_output = sys.stdout.getvalue() finally: sys.stdout = old_stdout return cmd_output assert get_value('freshness') == '30d\n' assert get_value('network_use') == 'full\n' assert get_value('help_with_testing') == 'False\n' cmd.config.handle(file_config, None, ['freshness', '5m']) cmd.config.handle(file_config, None, ['help_with_testing', 'True']) cmd.config.handle(file_config, None, ['network_use', 'minimal']) assert file_config.freshness == 5 * 60 assert file_config.network_use == model.network_minimal assert file_config.help_with_testing == True file_config2 = policy.load_config(handler.Handler()) assert file_config2.freshness == 5 * 60 assert file_config2.network_use == model.network_minimal assert file_config2.help_with_testing == True cmd.config.handle(file_config, None, ['help_with_testing', 'falsE']) assert file_config.help_with_testing == False for period in ['1s', '2d', '3.5m', '4h', '5d']: secs = cmd.config.TimeInterval.parse(period) assert cmd.config.TimeInterval.format(secs) == period
def testConfig(self): out, err = self.run_0install(["config", "--help"]) assert out.lower().startswith("usage:") assert "--console" in out out, err = self.run_0install(["config"]) assert not err, err assert "full" in out, out assert "freshness = 0" in out, out assert "help_with_testing = False" in out, out out, err = self.run_0install(["config", "help_with_testing"]) assert out == "False\n", out file_config = policy.load_config(handler.Handler()) def get_value(name): old_stdout = sys.stdout sys.stdout = StringIO() try: cmd.config.handle(file_config, None, [name]) cmd_output = sys.stdout.getvalue() finally: sys.stdout = old_stdout return cmd_output assert get_value("freshness") == "30d\n" assert get_value("network_use") == "full\n" assert get_value("help_with_testing") == "False\n" cmd.config.handle(file_config, None, ["freshness", "5m"]) cmd.config.handle(file_config, None, ["help_with_testing", "True"]) cmd.config.handle(file_config, None, ["network_use", "minimal"]) assert file_config.freshness == 5 * 60 assert file_config.network_use == model.network_minimal assert file_config.help_with_testing == True file_config2 = policy.load_config(handler.Handler()) assert file_config2.freshness == 5 * 60 assert file_config2.network_use == model.network_minimal assert file_config2.help_with_testing == True cmd.config.handle(file_config, None, ["help_with_testing", "falsE"]) assert file_config.help_with_testing == False for period in ["1s", "2d", "3.5m", "4h", "5d"]: secs = cmd.config.TimeInterval.parse(period) assert cmd.config.TimeInterval.format(secs) == period
def ensure_cached(uri, command = 'run'): """Ensure that an implementation of uri is cached. If not, it downloads one. It uses the GUI if a display is available, or the console otherwise. @param uri: the required interface @type uri: str @return: the selected implementations, or None if the user cancelled @rtype: L{zeroinstall.injector.selections.Selections} """ from zeroinstall.injector import policy, selections, handler config = policy.load_config(handler.Handler()) p = policy.Policy(uri, command = command, config = config) p.freshness = 0 # Don't check for updates if p.need_download() or not p.ready: if os.environ.get('DISPLAY', None): return get_selections_gui(uri, ['--command', command]) else: done = p.solve_and_download_impls() p.handler.wait_for_blocker(done) return selections.Selections(p)
def _check_for_updates(old_policy, verbose): from zeroinstall.injector.policy import load_config, Policy iface_cache = old_policy.config.iface_cache root_iface = iface_cache.get_interface(old_policy.root).get_name() background_config = load_config(BackgroundHandler(root_iface, old_policy.root)) policy = Policy(config = background_config, requirements = old_policy.requirements) info(_("Checking for updates to '%s' in a background process"), root_iface) if verbose: policy.handler.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface, timeout = 1) network_state = policy.handler.get_network_state() if network_state != _NetworkState.NM_STATE_CONNECTED: info(_("Not yet connected to network (status = %d). Sleeping for a bit..."), network_state) import time time.sleep(120) if network_state in (_NetworkState.NM_STATE_DISCONNECTED, _NetworkState.NM_STATE_ASLEEP): info(_("Still not connected to network. Giving up.")) sys.exit(1) else: info(_("NetworkManager says we're on-line. Good!")) policy.freshness = 0 # Don't bother trying to refresh when getting the interface refresh = policy.refresh_all() # (causes confusing log messages) policy.handler.wait_for_blocker(refresh) # We could even download the archives here, but for now just # update the interfaces. if not policy.need_download(): if verbose: policy.handler.notify("Zero Install", _("No updates to download."), timeout = 1) sys.exit(0) if not policy.handler.have_actions_support(): # Can't ask the user to choose, so just notify them # In particular, Ubuntu/Jaunty doesn't support actions policy.handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout = 1) _exec_gui(policy.root, '--refresh', '--systray') sys.exit(1) notification_closed = tasks.Blocker("wait for notification response") def _NotificationClosed(nid, *unused): if nid != our_question: return notification_closed.trigger() def _ActionInvoked(nid, action): if nid != our_question: return if action == 'download': _exec_gui(policy.root) notification_closed.trigger() policy.handler.notification_service.connect_to_signal('NotificationClosed', _NotificationClosed) policy.handler.notification_service.connect_to_signal('ActionInvoked', _ActionInvoked) our_question = policy.handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, actions = ['download', 'Download']) policy.handler.wait_for_blocker(notification_closed)
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 import policy, handler if os.isatty(1): h = handler.ConsoleHandler() else: h = handler.Handler() config = policy.load_config(h) # 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, ex: if verbose: raise try: print >>sys.stderr, unicode(ex) except: print >>sys.stderr, repr(ex) sys.exit(1)
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, 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
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 os.isatty(1): h = handler.ConsoleHandler() else: h = handler.Handler() h.dry_run = bool(options.dry_run) if config is None: config = policy.load_config(h) 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, ex: # This only happens for dry runs print ex