コード例 #1
0
ファイル: reader.py プロジェクト: rammstein/0install
def update(interface, source, local = False, iface_cache = None):
	"""Read in information about an interface.
	Deprecated.
	@param interface: the interface object to update
	@type interface: L{model.Interface}
	@param source: the name of the file to read
	@type source: str
	@param local: use file's mtime for last-modified, and uri attribute is ignored
	@type local: bool
	@type iface_cache: L{zeroinstall.injector.iface_cache.IfaceCache} | None
	@return: the new feed (since 0.32)
	@rtype: L{ZeroInstallFeed}
	@raise InvalidInterface: if the source's syntax is incorrect
	@see: L{update_from_cache}, which calls this"""
	assert isinstance(interface, Interface)

	feed = load_feed(source, local)

	if not local:
		if feed.url != interface.uri:
			raise InvalidInterface(_("Incorrect URL used for feed.\n\n"
						"%(feed_url)s is given in the feed, but\n"
						"%(interface_uri)s was requested") %
						{'feed_url': feed.url, 'interface_uri': interface.uri})

	if iface_cache is None:
		import warnings
		warnings.warn("iface_cache should be specified", DeprecationWarning, 2)
		from zeroinstall.injector import policy
		iface_cache = policy.get_deprecated_singleton_config().iface_cache
	iface_cache._feeds[support.unicode(interface.uri)] = feed

	return feed
コード例 #2
0
            def details_cb(sender):
                # The key can be a dbus.String sometimes, so convert to a Python
                # string to be sure we get a match.
                details = {}
                for packagekit_id, d in sender.details.items():
                    details[unicode(packagekit_id)] = d

                for packagekit_id in details:
                    if packagekit_id not in versions:
                        _logger_pk.info(
                            "Unexpected package info for '%s'; was expecting one of %r",
                            packagekit_id, list(versions.keys()))

                for packagekit_id, info in versions.items():
                    if packagekit_id in details:
                        info.update(details[packagekit_id])
                        info['packagekit_id'] = packagekit_id
                        if (info['name'] not in self._candidates
                                or isinstance(self._candidates[info['name']],
                                              tasks.Blocker)):
                            self._candidates[info['name']] = [info]
                        else:
                            self._candidates[info['name']].append(info)
                    else:
                        _logger_pk.info(_('Empty details for %s'),
                                        packagekit_id)
                blocker.trigger()
コード例 #3
0
    def testAbsMain(self):
        p = Driver(requirements=Requirements(command_feed), config=self.config)
        self.config.handler.wait_for_blocker(p.solve_with_downloads())

        old_stdout = sys.stdout
        try:
            sys.stdout = StringIO()
            run.execute_selections(p.solver.selections, [],
                                   main='/runnable/runner',
                                   dry_run=True,
                                   stores=self.config.stores)
        finally:
            sys.stdout = old_stdout

        try:
            old_stdout = sys.stdout
            try:
                sys.stdout = StringIO()
                run.execute_selections(p.solver.selections, [],
                                       main='/runnable/not-there',
                                       dry_run=True,
                                       stores=self.config.stores)
            finally:
                sys.stdout = old_stdout
        except SafeException as ex:
            assert 'not-there' in unicode(ex)
コード例 #4
0
	def populate_model(self):
		m = self.model
		m.clear()

		for uri in self.app_list.get_apps():
			itr = m.append()
			m[itr][AppListBox.URI] = uri

			try:
				iface = self.iface_cache.get_interface(uri)
				feed = self.iface_cache.get_feed(uri)
				if feed:
					name = feed.get_name()
					summary = feed.summary or _('No information available')
					summary = summary[:1].capitalize() + summary[1:]
				else:
					name = iface.get_name()
					summary = _('No information available')
				# (GTK3 returns an extra boolean at the start)
				icon_width, icon_height = gtk.icon_size_lookup(gtk.ICON_SIZE_DIALOG)[-2:]
				pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface), icon_width, icon_height)
			except model.InvalidInterface as ex:
				name = uri
				summary = support.unicode(ex)
				pixbuf = None

			m[itr][AppListBox.NAME] = name
			if pixbuf is None:
				pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE, gtk.ICON_SIZE_DIALOG)
			m[itr][AppListBox.ICON] = pixbuf

			m[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (_pango_escape(name), _pango_escape(summary))
コード例 #5
0
ファイル: model.py プロジェクト: michel-slm/0install
	def __unicode__(self):
		if hasattr(SafeException, '__unicode__'):
			# Python >= 2.6
			if self.feed_url:
				return _('%s [%s]') % (SafeException.__unicode__(self), self.feed_url)
			return SafeException.__unicode__(self)
		else:
			return support.unicode(SafeException.__str__(self))
コード例 #6
0
    def testBadMain(self):
        r = Requirements(command_feed)
        r.command = None
        d = Driver(requirements=r, config=self.config)
        self.config.handler.wait_for_blocker(d.solve_with_downloads())

        try:
            run.execute_selections(d.solver.selections, [],
                                   dry_run=True,
                                   stores=self.config.stores)
            assert 0
        except SafeException as ex:
            self.assertEqual("Can't run: no command specified!", unicode(ex))

        try:
            run.execute_selections(d.solver.selections, [],
                                   main='relpath',
                                   dry_run=True,
                                   stores=self.config.stores)
            assert 0
        except SafeException as ex:
            self.assertEqual(
                "Can't use a relative replacement main when there is no original one!",
                unicode(ex))
コード例 #7
0
ファイル: packagekit.py プロジェクト: afb/0install
			def resolve_cb(sender):
				if sender.package:
					_logger_pk.debug(_('Resolved %r'), sender.package)
					for packagekit_id, info in sender.package.items():
						packagekit_id = unicode(packagekit_id)	# Can be a dbus.String sometimes
						parts = packagekit_id.split(';', 3)
						if ':' in parts[3]:
							parts[3] = parts[3].split(':', 1)[0]
							packagekit_id = ';'.join(parts)
						versions[packagekit_id] = info
					tran = _PackageKitTransaction(self.pk, details_cb, error_cb)
					tran.proxy.GetDetails(list(versions.keys()))
				else:
					_logger_pk.info(_('Empty resolve for %s'), package_names)
					blocker.trigger()
コード例 #8
0
ファイル: iface_cache.py プロジェクト: afb/0install
	def get_interface(self, uri):
		"""Get the interface for uri, creating a new one if required.
		New interfaces are initialised from the disk cache, but not from
		the network.
		@param uri: the URI of the interface to find
		@type uri: str
		@rtype: L{model.Interface}"""
		if type(uri) == str:
			uri = unicode(uri)
		assert isinstance(uri, unicode)

		if uri in self._interfaces:
			return self._interfaces[uri]

		logger.debug(_("Initialising new interface object for %s"), uri)
		self._interfaces[uri] = Interface(uri)
		return self._interfaces[uri]
コード例 #9
0
	def testBadMain(self):
		r = Requirements(command_feed)
		r.command = None
		d = Driver(requirements = r, config = self.config)
		self.config.handler.wait_for_blocker(d.solve_with_downloads())

		try:
			run.execute_selections(d.solver.selections, [], dry_run = True, stores = self.config.stores)
			assert 0
		except SafeException as ex:
			self.assertEqual("Can't run: no command specified!", unicode(ex))

		try:
			run.execute_selections(d.solver.selections, [], main = 'relpath', dry_run = True, stores = self.config.stores)
			assert 0
		except SafeException as ex:
			self.assertEqual("Can't use a relative replacement main when there is no original one!", unicode(ex))
コード例 #10
0
 def resolve_cb(sender):
     if sender.package:
         _logger_pk.debug(_('Resolved %r'), sender.package)
         for packagekit_id, info in sender.package.items():
             packagekit_id = unicode(
                 packagekit_id)  # Can be a dbus.String sometimes
             parts = packagekit_id.split(';', 3)
             if ':' in parts[3]:
                 parts[3] = parts[3].split(':', 1)[0]
                 packagekit_id = ';'.join(parts)
             versions[packagekit_id] = info
         tran = _PackageKitTransaction(self.pk, details_cb,
                                       error_cb)
         tran.proxy.GetDetails(list(versions.keys()))
     else:
         _logger_pk.info(_('Empty resolve for %s'), package_names)
         blocker.trigger()
コード例 #11
0
ファイル: alias.py プロジェクト: dabrahams/0install
def write_script(stream, interface_uri, main = None, command = None):
	"""Write a shell script to stream that will launch the given program.
	@param stream: the stream to write to
	@param interface_uri: the program to launch
	@param main: the --main argument to pass to 0launch, if any
	@param command: the --command argument to pass to 0launch, if any"""
	assert "'" not in interface_uri
	assert "\\" not in interface_uri
	assert main is None or command is None, "Can't set --main and --command together"

	if main is not None:
		option = "--main '%s' " % main.replace("'", "'\\''")
	elif command is not None:
		option = "--command '%s' " % command.replace("'", "'\\''")
	else:
		option = ""

	stream.write(support.unicode(_template) % (option, interface_uri))
コード例 #12
0
def write_script(stream, interface_uri, main=None, command=None):
    """Write a shell script to stream that will launch the given program.
	@param stream: the stream to write to
	@param interface_uri: the program to launch
	@param main: the --main argument to pass to 0launch, if any
	@param command: the --command argument to pass to 0launch, if any"""
    assert "'" not in interface_uri
    assert "\\" not in interface_uri
    assert main is None or command is None, "Can't set --main and --command together"

    if main is not None:
        option = "--main '%s' " % main.replace("'", "'\\''")
    elif command is not None:
        option = "--command '%s' " % command.replace("'", "'\\''")
    else:
        option = ""

    stream.write(support.unicode(_template) % (option, interface_uri))
コード例 #13
0
    def get_interface(self, uri):
        """Get the interface for uri, creating a new one if required.
		New interfaces are initialised from the disk cache, but not from
		the network.
		@param uri: the URI of the interface to find
		@type uri: str
		@rtype: L{model.Interface}"""
        if type(uri) == str:
            uri = unicode(uri)
        assert isinstance(uri, unicode)

        if uri in self._interfaces:
            return self._interfaces[uri]

        logger.debug(_("Initialising new interface object for %s"), uri)
        self._interfaces[uri] = Interface(uri)
        reader.update_from_cache(self._interfaces[uri], iface_cache=self)
        return self._interfaces[uri]
コード例 #14
0
ファイル: properties.py プロジェクト: afb/0install
	def set_details(self, details):
		buffer = self.buffer
		heading_style = self.heading_style

		buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())

		iter = buffer.get_start_iter()

		if isinstance(details, Exception):
			buffer.insert(iter, unicode(details))
			return

		for (style, text) in details:
			if style == 'heading':
				buffer.insert_with_tags(iter, text, heading_style)
			elif style == 'link':
				buffer.insert_with_tags(iter, text, self.link_style)
			else:
				buffer.insert(iter, text)
コード例 #15
0
	def testAbsMain(self):
		p = Driver(requirements = Requirements(command_feed), config = self.config)
		self.config.handler.wait_for_blocker(p.solve_with_downloads())

		old_stdout = sys.stdout
		try:
			sys.stdout = StringIO()
			run.execute_selections(p.solver.selections, [], main = '/runnable/runner', dry_run = True, stores = self.config.stores)
		finally:
			sys.stdout = old_stdout

		try:
			old_stdout = sys.stdout
			try:
				sys.stdout = StringIO()
				run.execute_selections(p.solver.selections, [], main = '/runnable/not-there', dry_run = True, stores = self.config.stores)
			finally:
				sys.stdout = old_stdout
		except SafeException as ex:
			assert 'not-there' in unicode(ex)
コード例 #16
0
ファイル: packagekit.py プロジェクト: afb/0install
			def details_cb(sender):
				# The key can be a dbus.String sometimes, so convert to a Python
				# string to be sure we get a match.
				details = {}
				for packagekit_id, d in sender.details.items():
					details[unicode(packagekit_id)] = d

				for packagekit_id in details:
					if packagekit_id not in versions:
						_logger_pk.info("Unexpected package info for '%s'; was expecting one of %r", packagekit_id, list(versions.keys()))

				for packagekit_id, info in versions.items():
					if packagekit_id in details:
						info.update(details[packagekit_id])
						info['packagekit_id'] = packagekit_id
						if (info['name'] not in self._candidates or
						    isinstance(self._candidates[info['name']], tasks.Blocker)):
							self._candidates[info['name']] = [info]
						else:
							self._candidates[info['name']].append(info)
					else:
						_logger_pk.info(_('Empty details for %s'), packagekit_id)
				blocker.trigger()
コード例 #17
0
ファイル: applistbox.py プロジェクト: rammstein/0install
    def populate_model(self):
        m = self.model
        m.clear()

        for uri in self.app_list.get_apps():
            itr = m.append()
            m[itr][AppListBox.URI] = uri

            try:
                iface = self.iface_cache.get_interface(uri)
                feed = self.iface_cache.get_feed(uri)
                if feed:
                    name = feed.get_name()
                    summary = feed.summary or _('No information available')
                    summary = summary[:1].capitalize() + summary[1:]
                else:
                    name = iface.get_name()
                    summary = _('No information available')
                # (GTK3 returns an extra boolean at the start)
                icon_width, icon_height = gtk.icon_size_lookup(
                    gtk.ICON_SIZE_DIALOG)[-2:]
                pixbuf = icon.load_icon(self.iface_cache.get_icon_path(iface),
                                        icon_width, icon_height)
            except model.InvalidInterface as ex:
                name = uri
                summary = support.unicode(ex)
                pixbuf = None

            m[itr][AppListBox.NAME] = name
            if pixbuf is None:
                pixbuf = self.window.render_icon(gtk.STOCK_EXECUTE,
                                                 gtk.ICON_SIZE_DIALOG)
            m[itr][AppListBox.ICON] = pixbuf

            m[itr][AppListBox.MARKUP] = '<b>%s</b>\n<i>%s</i>' % (
                _pango_escape(name), _pango_escape(summary))
コード例 #18
0
ファイル: properties.py プロジェクト: rammstein/0install
    def set_details(self, iface_cache, feed):
        buffer = self.buffer
        heading_style = self.heading_style

        buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())

        iter = buffer.get_start_iter()

        if feed is None:
            buffer.insert(iter, 'Not yet downloaded.')
            return

        if isinstance(feed, Exception):
            buffer.insert(iter, unicode(feed))
            return

        buffer.insert_with_tags(iter, '%s ' % feed.get_name(), heading_style)
        buffer.insert(iter, '(%s)' % feed.summary)

        buffer.insert(iter, '\n%s\n' % feed.url)

        # (converts to local time)
        if feed.last_modified:
            buffer.insert(
                iter, '\n' + _('Last upstream change: %s') %
                self.strtime(feed.last_modified))

        if feed.last_checked:
            buffer.insert(
                iter,
                '\n' + _('Last checked: %s') % self.strtime(feed.last_checked))

        last_check_attempt = iface_cache.get_last_check_attempt(feed.url)
        if last_check_attempt:
            if feed.last_checked and feed.last_checked >= last_check_attempt:
                pass  # Don't bother reporting successful attempts
            else:
                buffer.insert(
                    iter, '\n' +
                    _('Last check attempt: %s (failed or in progress)') %
                    self.strtime(last_check_attempt))

        buffer.insert_with_tags(iter, '\n\n' + _('Description') + '\n',
                                heading_style)

        paragraphs = [
            format_para(p) for p in (feed.description or "-").split('\n\n')
        ]

        buffer.insert(iter, '\n\n'.join(paragraphs))
        buffer.insert(iter, '\n')

        need_gap = True
        for x in feed.get_metadata(namespaces.XMLNS_IFACE, 'homepage'):
            if need_gap:
                buffer.insert(iter, '\n')
                need_gap = False
            buffer.insert(iter, _('Homepage: '))
            buffer.insert_with_tags(iter, '%s\n' % x.content, self.link_style)

        if feed.local_path is None:
            buffer.insert_with_tags(iter, '\n' + _('Signatures') + '\n',
                                    heading_style)
            sigs = iface_cache.get_cached_signatures(feed.url)
            if sigs:
                for sig in sigs:
                    if isinstance(sig, gpg.ValidSig):
                        name = _('<unknown>')
                        details = sig.get_details()
                        for item in details:
                            if item[0] == 'uid' and len(item) > 9:
                                name = item[9]
                                break
                        buffer.insert_with_tags(
                            iter,
                            _('Valid signature by "%(name)s"\n- Dated: %(sig_date)s\n- Fingerprint: %(sig_fingerprint)s\n'
                              ) %
                            {
                                'name':
                                name,
                                'sig_date':
                                time.strftime(
                                    '%c', time.localtime(sig.get_timestamp())),
                                'sig_fingerprint':
                                sig.fingerprint
                            })
                        if not sig.is_trusted():
                            if os.path.isabs(feed.url):
                                buffer.insert_with_tags(
                                    iter,
                                    _('WARNING: This key is not in the trusted list'
                                      ) + '\n')
                            else:
                                buffer.insert_with_tags(
                                    iter,
                                    _('WARNING: This key is not in the trusted list (either you removed it, or '
                                      'you trust one of the other signatures)')
                                    + '\n')
                    else:
                        buffer.insert_with_tags(iter, '%s\n' % sig)
            else:
                buffer.insert_with_tags(
                    iter,
                    _('No signature information (old style feed or out-of-date cache)'
                      ) + '\n')
コード例 #19
0
ファイル: cli.py プロジェクト: michel-slm/0install
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("",
                      "--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()

    # (hack to support double meaning of --version)
    allow_version_expr = any(not arg.startswith('-') for arg in command_args)
    if allow_version_expr:
        parser.add_option(
            "",
            "--version",
            help=_("specify version contraint (e.g. '3' or '3..')"),
            metavar='RANGE')
        parser.add_option(
            "",
            "--version-for",
            help=_("set version constraints for a specific interface"),
            nargs=2,
            metavar='URI RANGE',
            action='append')
    else:
        parser.add_option("-V",
                          "--version",
                          help=_("display version information"),
                          action='store_true')

    (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 and not allow_version_expr:
            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(support.unicode(ex), file=sys.stderr)
        except:
            print(repr(ex), file=sys.stderr)
        sys.exit(1)
コード例 #20
0
ファイル: __init__.py プロジェクト: timdiels/0install
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)
        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)

        cmd.handle(config, options, args)
    except KeyboardInterrupt:
        logger.info("KeyboardInterrupt")
        sys.exit(1)
    except UsageError:
        parser.print_help()
        sys.exit(1)
    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
コード例 #21
0
ファイル: __init__.py プロジェクト: dabrahams/0install
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)
		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)

		cmd.handle(config, options, args)
	except KeyboardInterrupt:
		logger.info("KeyboardInterrupt")
		sys.exit(1)
	except UsageError:
		parser.print_help()
		sys.exit(1)
	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
コード例 #22
0
ファイル: __init__.py プロジェクト: afb/0install
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
コード例 #23
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
コード例 #24
0
ファイル: cli.py プロジェクト: dsqmoore/0install
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("", "--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()

	# (hack to support double meaning of --version)
	allow_version_expr = any(not arg.startswith('-') for arg in command_args)
	if allow_version_expr:
		parser.add_option("", "--version", help=_("specify version contraint (e.g. '3' or '3..')"), metavar='RANGE')
		parser.add_option("", "--version-for", help=_("set version constraints for a specific interface"),
				nargs=2, metavar='URI RANGE', action='append')
	else:
		parser.add_option("-V", "--version", help=_("display version information"), action='store_true')

	(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 and not allow_version_expr:
			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(support.unicode(ex), file=sys.stderr)
		except:
			print(repr(ex), file=sys.stderr)
		sys.exit(1)
コード例 #25
0
	def set_details(self, iface_cache, feed):
		buffer = self.buffer
		heading_style = self.heading_style

		buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())

		iter = buffer.get_start_iter()

		if feed is None:
			buffer.insert(iter, 'Not yet downloaded.')
			return

		if isinstance(feed, Exception):
			buffer.insert(iter, unicode(feed))
			return

		buffer.insert_with_tags(iter,
			'%s ' % feed.get_name(), heading_style)
		buffer.insert(iter, '(%s)' % feed.summary)

		buffer.insert(iter, '\n%s\n' % feed.url)

		# (converts to local time)
		if feed.last_modified:
			buffer.insert(iter, '\n' + _('Last upstream change: %s') % self.strtime(feed.last_modified))

		if feed.last_checked:
			buffer.insert(iter, '\n' + _('Last checked: %s') % self.strtime(feed.last_checked))

		last_check_attempt = iface_cache.get_last_check_attempt(feed.url)
		if last_check_attempt:
			if feed.last_checked and feed.last_checked >= last_check_attempt:
				pass	# Don't bother reporting successful attempts
			else:
				buffer.insert(iter, '\n' + _('Last check attempt: %s (failed or in progress)') %
						self.strtime(last_check_attempt))

		buffer.insert_with_tags(iter, '\n\n' + _('Description') + '\n', heading_style)

		paragraphs = [format_para(p) for p in (feed.description or "-").split('\n\n')]

		buffer.insert(iter, '\n\n'.join(paragraphs))
		buffer.insert(iter, '\n')

		need_gap = True
		for x in feed.get_metadata(namespaces.XMLNS_IFACE, 'homepage'):
			if need_gap:
				buffer.insert(iter, '\n')
				need_gap = False
			buffer.insert(iter, _('Homepage: '))
			buffer.insert_with_tags(iter, '%s\n' % x.content, self.link_style)

		if feed.local_path is None:
			buffer.insert_with_tags(iter, '\n' + _('Signatures') + '\n', heading_style)
			sigs = iface_cache.get_cached_signatures(feed.url)
			if sigs:
				for sig in sigs:
					if isinstance(sig, gpg.ValidSig):
						name = _('<unknown>')
						details = sig.get_details()
						for item in details:
							if item[0] == 'uid' and len(item) > 9:
								name = item[9]
								break
						buffer.insert_with_tags(iter, _('Valid signature by "%(name)s"\n- Dated: %(sig_date)s\n- Fingerprint: %(sig_fingerprint)s\n') %
								{'name': name, 'sig_date': time.strftime('%c', time.localtime(sig.get_timestamp())), 'sig_fingerprint': sig.fingerprint})
						if not sig.is_trusted():
							if os.path.isabs(feed.url):
								buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list') + '\n')
							else:
								buffer.insert_with_tags(iter, _('WARNING: This key is not in the trusted list (either you removed it, or '
												'you trust one of the other signatures)') + '\n')
					else:
						buffer.insert_with_tags(iter, '%s\n' % sig)
			else:
				buffer.insert_with_tags(iter, _('No signature information (old style feed or out-of-date cache)') + '\n')