def testConfig(self): out, err = self.run_0install(['config', '--help']) assert out.lower().startswith("usage:") assert '--console' in out assert 'network_use' in self.complete(['config'], 2) assert 'full' in self.complete(['config', 'network_use'], 3) assert 'true' in self.complete(['config', 'help_with_testing'], 3) assert 'filter' in self.complete(['config', 'freshness'], 3) self.assertEqual('', self.complete(['config', 'missing'], 3)) self.assertEqual('', self.complete(['config', 'network_use', ''], 4)) 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 = config.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 = config.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 do_autocompile(args): """autocompile [--gui] URI""" parser = OptionParser(usage="usage: %prog autocompile [options]") parser.add_option('', "--gui", help="graphical interface", action='store_true') (options, args2) = parser.parse_args(args) if len(args2) != 1: raise __main__.UsageError() if options.gui: h = GUIHandler() elif os.isatty(1): h = handler.ConsoleHandler() else: h = handler.Handler() config = load_config(handler=h) config._iface_cache = AutocompileCache() iface_uri = model.canonical_iface_uri(args2[0]) if options.gui: compiler = GTKAutoCompiler(config, iface_uri, options) else: compiler = AutoCompiler(config, iface_uri, options) compiler.build()
def ensure_cached(uri, command='run', config=None): """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 if config is None: from zeroinstall.injector.config import load_config config = load_config() 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() tasks.wait_for_blocker(done) return p.solver.selections
def do_autocompile(args): """autocompile [--gui] URI""" parser = OptionParser(usage="usage: %prog autocompile [options]") parser.add_option('', "--gui", help="graphical interface", action='store_true') (options, args2) = parser.parse_args(args) if len(args2) != 1: raise __main__.UsageError() if options.gui: h = GUIHandler() elif os.isatty(1): h = handler.ConsoleHandler() else: h = handler.Handler() config = load_config(handler = h) config._iface_cache = AutocompileCache() iface_uri = model.canonical_iface_uri(args2[0]) if options.gui: compiler = GTKAutoCompiler(config, iface_uri, options) else: compiler = AutoCompiler(config, iface_uri, options) compiler.build()
def __init__(self, root = None, handler = None, src = None, command = -1, config = None, requirements = None): """ @param requirements: Details about the program we want to run @type requirements: L{requirements.Requirements} @param config: The configuration settings to use, or None to load from disk. @type config: L{config.Config} Note: all other arguments are deprecated (since 0launch 0.52) """ if requirements is None: from zeroinstall.injector.requirements import Requirements requirements = Requirements(root) requirements.source = bool(src) # Root impl must be a "src" machine type if command == -1: if src: command = 'compile' else: command = 'run' requirements.command = command else: assert root == src == None assert command == -1 if config is None: config = load_config(handler) else: assert handler is None, "can't pass a handler and a config" self.driver = driver.Driver(config = config, requirements = requirements)
def __init__(self, root=None, handler=None, src=None, command=-1, config=None, requirements=None): """ @param requirements: Details about the program we want to run @type requirements: L{requirements.Requirements} @param config: The configuration settings to use, or None to load from disk. @type config: L{config.Config} Note: all other arguments are deprecated (since 0launch 0.52) """ if requirements is None: from zeroinstall.injector.requirements import Requirements requirements = Requirements(root) requirements.source = bool( src) # Root impl must be a "src" machine type if command == -1: if src: command = 'compile' else: command = 'run' requirements.command = command else: assert root == src == None assert command == -1 if config is None: config = load_config(handler) else: assert handler is None, "can't pass a handler and a config" self.driver = driver.Driver(config=config, requirements=requirements)
def ensure_cached(uri, command = 'run', config = None): """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 if config is None: from zeroinstall.injector.config import load_config config = load_config() 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() tasks.wait_for_blocker(done) return selections.Selections(p)
def action_help(self, uri): from zeroinstall.injector.config import load_config from zeroinstall import helpers c = load_config() sels = helpers.ensure_cached(uri, config = c) if not sels: return impl = sels.selections[uri] assert impl, "Failed to choose an implementation of %s" % uri help_dir = impl.attrs.get('doc-dir') if impl.id.startswith('package:'): assert os.path.isabs(help_dir), "Package doc-dir must be absolute!" path = help_dir else: path = impl.local_path or c.stores.lookup_any(impl.digests) assert path, "Chosen implementation is not cached!" if help_dir: path = os.path.join(path, help_dir) else: main = impl.main if main: # Hack for ROX applications. They should be updated to # set doc-dir. help_dir = os.path.join(path, os.path.dirname(main), 'Help') if os.path.isdir(help_dir): path = help_dir # xdg-open has no "safe" mode, so check we're not "opening" an application. if os.path.exists(os.path.join(path, 'AppRun')): raise Exception(_("Documentation directory '%s' is an AppDir; refusing to open") % path) subprocess.Popen(['xdg-open', path])
def ensure_cached(uri, command = 'run', config = None): """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.driver import Driver if config is None: from zeroinstall.injector.config import load_config config = load_config() from zeroinstall.injector.requirements import Requirements requirements = Requirements(uri) requirements.command = command d = Driver(config, requirements) if d.need_download() or not d.solver.ready: sels = get_selections_gui(uri, ['--command', command], use_gui = None) if sels != DontUseGUI: return sels done = d.solve_and_download_impls() tasks.wait_for_blocker(done) return d.solver.selections
def download_missing_selections(sels): from zeroinstall.support import tasks from zeroinstall.injector.config import load_config config = load_config() blocker = sels.download_missing(config) if blocker: logging.info("Waiting for selected implementations to be downloaded...") tasks.wait_for_blocker(blocker)
def get_selections(self, prompt = False): if self._selections: assert not prompt return self._selections selections_file = self.config.get('compile', 'selections') if selections_file: if prompt: raise SafeException("Selections are fixed by %s" % selections_file) stream = file(selections_file) try: self._selections = selections.Selections(qdom.parse(stream)) finally: stream.close() from zeroinstall.injector import handler from zeroinstall.injector.config import load_config if os.isatty(1): h = handler.ConsoleHandler() else: h = handler.Handler() config = load_config(h) blocker = self._selections.download_missing(config) if blocker: print "Waiting for selected implementations to be downloaded..." h.wait_for_blocker(blocker) else: command = install_prog + ['download', '--source', '--xml'] if prompt and '--console' not in install_prog: if os.name == 'nt': command[0] += '-win' command.append('--gui') command.append(self.interface) child = subprocess.Popen(command, stdout = subprocess.PIPE) try: self._selections = selections.Selections(qdom.parse(child.stdout)) finally: if child.wait(): raise SafeException(' '.join(repr(x) for x in command) + " failed (exit code %d)" % child.returncode) self.root_impl = self._selections.selections[self.interface] self.orig_srcdir = os.path.realpath(lookup(self.root_impl)) self.user_srcdir = None if os.path.isdir('src'): self.user_srcdir = os.path.realpath('src') if self.user_srcdir == self.orig_srcdir or \ self.user_srcdir.startswith(os.path.join(self.orig_srcdir, '')) or \ self.orig_srcdir.startswith(os.path.join(self.user_srcdir, '')): info("Ignoring 'src' directory because it coincides with %s", self.orig_srcdir) self.user_srcdir = None return self._selections
def testRecursive(self): top = os.path.join(my_dir, "top.xml") compile("autocompile", top, expect="No dependencies need compiling... compile cprog itself...") # Dependency was registered against its local path, since that was how we depended on it: run(launch_command, os.path.join(my_dir, "cprog/cprog-command.xml"), expect="Hello from C") # But the top-level feed was registered against its <feed-for>: c = config.load_config() i = c.iface_cache.get_interface("http://example.com/top.xml") self.assertEquals(1, len(i.extra_feeds))
def _check_for_updates(old_policy, verbose): from zeroinstall.injector.policy import Policy from zeroinstall.injector.config import load_config 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) tasks.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) policy.handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout=1) _exec_gui(policy.root, '--refresh', '--systray') sys.exit(1)
def testRecursive(self): top = os.path.join(mydir, 'top.xml') compile( 'autocompile', top, expect="No dependencies need compiling... compile cprog itself...") # Dependency was registered against its local path, since that was how we depended on it: run(zi_command, "run", os.path.join(mydir, 'cprog/cprog-command.xml'), expect='Hello from C') # But the top-level feed was registered against its <feed-for>: c = config.load_config() i = c.iface_cache.get_interface('http://example.com/top.xml') self.assertEquals(1, len(i.extra_feeds))
def _check_for_updates(requirements, verbose): from zeroinstall.injector.driver import Driver from zeroinstall.injector.config import load_config background_handler = BackgroundHandler(requirements.interface_uri, requirements.interface_uri) background_config = load_config(background_handler) root_iface = background_config.iface_cache.get_interface(requirements.interface_uri).get_name() background_handler.title = root_iface driver = Driver(config = background_config, requirements = requirements) info(_("Checking for updates to '%s' in a background process"), root_iface) if verbose: background_handler.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface, timeout = 1) network_state = background_handler.get_network_state() if network_state not in (_NetworkState.NM_STATE_CONNECTED_SITE, _NetworkState.NM_STATE_CONNECTED_GLOBAL): 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!")) background_config.freshness = 0 # Don't bother trying to refresh when getting the interface refresh = driver.solve_with_downloads(force = True) # (causes confusing log messages) tasks.wait_for_blocker(refresh) # We could even download the archives here, but for now just # update the interfaces. if not driver.need_download(): if verbose: background_handler.notify("Zero Install", _("No updates to download."), timeout = 1) sys.exit(0) background_handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout = 1) _exec_gui(requirements.interface_uri, '--refresh', '--systray') sys.exit(1)
def load_feed(source, local = False, selections_ok = False, generate_sizes = False, implementation_id_alg=None, config=None): """Load a feed from a local file. @param source: the name of the file to read @type source: str @param local: this is a local feed @type local: bool @param selections_ok: if it turns out to be a local selections document, return that instead @type selections_ok: bool @param generate_sizes: if True, sizes of archives with missing size attributes will be generated @type generate_sizes: bool @param implementation_id_alg: if specified, missing impl ids will be generated with this alg @type implementation_id_alg: L{Algorithm} @raise InvalidInterface: if the source's syntax is incorrect @return: the new feed @since: 0.48 @see: L{iface_cache.iface_cache}, which uses this to load the feeds""" try: root = qdom.parse(file(source)) except IOError as ex: if ex.errno == 2 and local: raise MissingLocalFeed(_("Feed not found. Perhaps this is a local feed that no longer exists? You can remove it from the list of feeds in that case.")) raise InvalidInterface(_("Can't read file"), ex) except Exception as ex: raise InvalidInterface(_("Invalid XML"), ex) if local: if selections_ok and root.uri == XMLNS_IFACE and root.name == 'selections': from zeroinstall.injector import selections return selections.Selections(root) local_path = source else: local_path = None if implementation_id_alg or generate_sizes: from zeroinstall.injector.config import load_config if config is None: config = load_config() feed = ZeroInstallFeed(root, local_path, None, generate_sizes, implementation_id_alg, config.fetcher, config.stores) else: feed = ZeroInstallFeed(root, local_path) feed.last_modified = int(os.stat(source).st_mtime) return feed
def _check_for_updates(old_policy, verbose): from zeroinstall.injector.policy import Policy from zeroinstall.injector.config import load_config 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) tasks.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) policy.handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout = 1) _exec_gui(policy.root, '--refresh', '--systray') sys.exit(1)
def action_help(self, uri): from zeroinstall.injector.config import load_config from zeroinstall import helpers c = load_config() sels = helpers.ensure_cached(uri, config=c) if not sels: return impl = sels.selections[uri] assert impl, "Failed to choose an implementation of %s" % uri help_dir = impl.attrs.get('doc-dir') if impl.id.startswith('package:'): assert os.path.isabs(help_dir), "Package doc-dir must be absolute!" path = help_dir else: path = impl.local_path or c.stores.lookup_any(impl.digests) assert path, "Chosen implementation is not cached!" if help_dir: path = os.path.join(path, help_dir) else: main = impl.main if main: # Hack for ROX applications. They should be updated to # set doc-dir. help_dir = os.path.join(path, os.path.dirname(main), 'Help') if os.path.isdir(help_dir): path = help_dir # xdg-open has no "safe" mode, so check we're not "opening" an application. if os.path.exists(os.path.join(path, 'AppRun')): raise Exception( _("Documentation directory '%s' is an AppDir; refusing to open" ) % path) subprocess.Popen(['xdg-open', path])
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(os.devnull, 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)
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())
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())
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("", "--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: 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) 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())
def _check_for_updates(requirements, verbose, app): """@type requirements: L{zeroinstall.injector.requirements.Requirements} @type verbose: bool @type app: L{zeroinstall.apps.App}""" if app is not None: old_sels = app.get_selections() from zeroinstall.injector.driver import Driver from zeroinstall.injector.config import load_config background_handler = BackgroundHandler(requirements.interface_uri, requirements.interface_uri) background_config = load_config(background_handler) root_iface = background_config.iface_cache.get_interface( requirements.interface_uri).get_name() background_handler.title = root_iface driver = Driver(config=background_config, requirements=requirements) logger.info(_("Checking for updates to '%s' in a background process"), root_iface) if verbose: background_handler.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface, timeout=1) network_state = background_handler.get_network_state() if network_state not in (_NetworkState.NM_STATE_CONNECTED_SITE, _NetworkState.NM_STATE_CONNECTED_GLOBAL): logger.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): logger.info(_("Still not connected to network. Giving up.")) sys.exit(1) else: logger.info(_("NetworkManager says we're on-line. Good!")) background_config.freshness = 0 # Don't bother trying to refresh when getting the interface refresh = driver.solve_with_downloads( force=True) # (causes confusing log messages) tasks.wait_for_blocker(refresh) if background_handler.need_gui or not driver.solver.ready or driver.get_uncached_implementations( ): if verbose: background_handler.notify( "Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout=1) # Run the GUI if possible... from zeroinstall import helpers gui_args = ['--refresh', '--systray', '--download' ] + requirements.get_as_options() new_sels = helpers.get_selections_gui(requirements.interface_uri, gui_args, use_gui=None) if new_sels is None: sys.exit(0) # Cancelled by user elif new_sels is helpers.DontUseGUI: if not driver.solver.ready: background_handler.notify("Zero Install", _("Can't update '%s'") % root_iface) sys.exit(1) tasks.wait_for_blocker(driver.download_uncached_implementations()) new_sels = driver.solver.selections if app is None: background_handler.notify( "Zero Install", _("{name} updated.").format(name=root_iface), timeout=1) else: if verbose: background_handler.notify("Zero Install", _("No updates to download."), timeout=1) new_sels = driver.solver.selections if app is not None: assert driver.solver.ready from zeroinstall.support import xmltools if not xmltools.nodes_equal(new_sels.toDOM(), old_sels.toDOM()): app.set_selections(new_sels) background_handler.notify( "Zero Install", _("{app} updated.").format(app=app.get_name()), timeout=1) app.set_last_checked() sys.exit(0)
def get_deprecated_singleton_config(): """@rtype: L{zeroinstall.injector.config.Config}""" global _config if _config is None: _config = load_config() return _config
def _check_for_updates(requirements, verbose, app): if app is not None: old_sels = app.get_selections() from zeroinstall.injector.driver import Driver from zeroinstall.injector.config import load_config background_handler = BackgroundHandler(requirements.interface_uri, requirements.interface_uri) background_config = load_config(background_handler) root_iface = background_config.iface_cache.get_interface(requirements.interface_uri).get_name() background_handler.title = root_iface driver = Driver(config = background_config, requirements = requirements) logger.info(_("Checking for updates to '%s' in a background process"), root_iface) if verbose: background_handler.notify("Zero Install", _("Checking for updates to '%s'...") % root_iface, timeout = 1) network_state = background_handler.get_network_state() if network_state not in (_NetworkState.NM_STATE_CONNECTED_SITE, _NetworkState.NM_STATE_CONNECTED_GLOBAL): logger.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): logger.info(_("Still not connected to network. Giving up.")) sys.exit(1) else: logger.info(_("NetworkManager says we're on-line. Good!")) background_config.freshness = 0 # Don't bother trying to refresh when getting the interface refresh = driver.solve_with_downloads(force = True) # (causes confusing log messages) tasks.wait_for_blocker(refresh) if background_handler.need_gui or driver.get_uncached_implementations(): if verbose: background_handler.notify("Zero Install", _("Updates ready to download for '%s'.") % root_iface, timeout = 1) # Run the GUI if possible... from zeroinstall import helpers gui_args = ['--refresh', '--systray', '--download'] + requirements.get_as_options() new_sels = helpers.get_selections_gui(requirements.interface_uri, gui_args, use_gui = None) if new_sels is None: sys.exit(0) # Cancelled by user elif new_sels is helpers.DontUseGUI: tasks.wait_for_blocker(driver.download_uncached_implementations()) new_sels = driver.solver.selections if app is None: background_handler.notify("Zero Install", _("{name} updated.").format(name = root_iface), timeout = 1) else: if verbose: background_handler.notify("Zero Install", _("No updates to download."), timeout = 1) new_sels = driver.solver.selections if app is not None: assert driver.solver.ready from zeroinstall.support import xmltools if not xmltools.nodes_equal(new_sels.toDOM(), old_sels.toDOM()): app.set_selections(new_sels) background_handler.notify("Zero Install", _("{app} updated.").format(app = app.get_name()), timeout = 1) app.set_last_checked() sys.exit(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)
sys.path.insert(0, zidir) feeds_dir = os.path.join(mydir, 'feeds') pypath = os.environ.get('PYTHONPATH') if pypath: pypath = ':' + pypath else: pypath = '' os.environ['PYTHONPATH'] = zidir + pypath from zeroinstall.injector import gpg, trust, qdom, iface_cache, driver, handler, model, namespaces, config, requirements from zeroinstall.support import basedir, find_in_path from zeroinstall import SafeException, zerostore from zeroinstall.gtkui import xdgutils h = handler.Handler() config = config.load_config(handler = h) # During the install we copy this to the local cache copied_0launch_in_cache = None if not os.path.isdir(feeds_dir): print >>sys.stderr, "Directory %s not found." % feeds_dir print >>sys.stderr, "This script should be run from an unpacked setup.sh archive." print >>sys.stderr, "(are you trying to install 0export? you're in the wrong place!)" sys.exit(1) def check_call(*args, **kwargs): exitstatus = subprocess.call(*args, **kwargs) if exitstatus != 0: raise SafeException("Command failed with exit code %d:\n%s" % (exitstatus, ' '.join(args[0])))
from zeroinstall.injector.config import load_config from zeroinstall.support import tasks import sys import os from zeroinstall import helpers 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):
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() # 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:] break elif arg == '--': break verbose = False try: # Configure a parser for the given command my_name = os.path.basename(sys.argv[0]) if my_name == '0install-python-fallback': my_name = '0install' # Hack for python-fallback if command: if command not in valid_commands: 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) (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}) 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
from zeroinstall.support import tasks import sys import os from zeroinstall import helpers 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):
def get_deprecated_singleton_config(): global _config if _config is None: _config = load_config() return _config
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
def open_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: from zeroinstall.gui 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) if not gui_is_available(options.force_gui): sys.exit(100) from zeroinstall.gui import gui handler = gui.GUIHandler() config = load_config(handler) if options.with_store: # TODO: inherit from the main config from zeroinstall import zerostore for x in options.with_store: config.stores.stores.append(zerostore.Store(os.path.abspath(x))) assert len(args) > 0 interface_uri = args[0] if len(args) > 1: parser.print_help() sys.exit(1) from zeroinstall.gui import mainwindow, dialog widgets = dialog.Template('main') root_iface = config.iface_cache.get_interface(interface_uri) finished = tasks.Blocker("GUI finished") def resolve(result): finished.gui_result = result finished.trigger() driver = OCamlDriver(config) window = mainwindow.MainWindow(driver, widgets, download_only = bool(options.download_only), resolve = resolve, select_only = bool(options.select_only)) handler.mainwindow = window if options.message: window.set_message(options.message) window.window.connect('destroy', lambda w: handler.abort_all_downloads()) if options.systray: window.use_systray_icon(root_iface) logger = logging.getLogger() def prepare_for_recalc(force_refresh): window.refresh_button.set_sensitive(False) window.browser.set_update_icons(force_refresh) if not window.systray_icon: window.show() force_refresh = bool(options.refresh) prepare_for_recalc(force_refresh) # Called each time a complete solve_with_downloads is done. @tasks.async def run_gui(reply_holder): window.refresh_button.set_sensitive(True) window.browser.highlight_problems() if window.systray_icon and window.systray_icon.get_visible() and \ window.systray_icon.is_embedded(): if driver.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, finished if finished.happened: reply_holder.append([finished.gui_result]) else: reply_holder.append(["recalculate", refresh_clicked.happened]) prepare_for_recalc(refresh_clicked.happened) return (run_gui, driver)
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
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 KeyboardInterrupt: logging.info("KeyboardInterrupt") sys.exit(1) except UsageError: parser.print_help() sys.exit(1) except SafeException as ex: if verbose: raise try: print(unicode(ex), file=sys.stderr) except: print(repr(ex), file=sys.stderr) sys.exit(1) return