Ejemplo n.º 1
0
def main(command_args):
	"""Implements the logic of the 0desktop command.
	@param command_args: the command-line arguments"""
	parser = OptionParser(usage=_("usage: %prog [options] [URI]"))
	parser.add_option("-m", "--manage", help=_("manage added applications"), 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')

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

	if options.verbose:
		if options.verbose == 1:
			logger.setLevel(logging.INFO)
		else:
			logger.setLevel(logging.DEBUG)
		hdlr = logging.StreamHandler()
		fmt = logging.Formatter("%(levelname)s:%(message)s")
		hdlr.setFormatter(fmt)
		logger.addHandler(hdlr)

	if options.version:
		import zeroinstall
		print("0desktop (zero-install) " + zeroinstall.version)
		print("Copyright (C) 2013 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 args:
		interface_uri = None
	elif len(args) == 1:
		interface_uri = args[0]
	else:
		parser.print_help()
		sys.exit(1)

	if sys.version_info[0] < 3:
		import pygtk
		pygtk.require('2.0')
	else:
		from zeroinstall.gtkui import pygtkcompat
		pygtkcompat.enable()
		pygtkcompat.enable_gtk(version = '3.0')
	import gtk

	if options.manage:
		from zeroinstall.gtkui.applistbox import AppListBox, AppList
		from zeroinstall.injector.iface_cache import iface_cache
		box = AppListBox(iface_cache, AppList())
	else:
		from zeroinstall.gtkui.addbox import AddBox
		box = AddBox(interface_uri)

	box.window.connect('destroy', gtk.main_quit)
	box.window.show()
	gtk.main()
Ejemplo n.º 2
0
	def testAdd(self):
		out, err = self.run_0install(['add', '--help'])
		assert out.lower().startswith("usage:")

		local_feed = os.path.join(mydir, 'Local.xml')
		local_copy = os.path.join(self.data_home, 'Local.xml')

		os.mkdir(self.data_home)
		shutil.copyfile(local_feed, local_copy)

		self.assertEqual("", self.complete(["add", ""], 2))
		assert 'file\n' in self.complete(["add", "foo"], 3)

		out, err = self.run_0install(['add', 'local-app', local_copy])
		assert not out, out
		assert not err, err

		app = self.config.app_mgr.lookup_app('local-app')

		# Because the unit-tests run very quickly, we have to back-date things
		# a bit...
		def set_mtime(name, t):
			os.utime(name, (t, t))
		set_mtime(local_copy, 100)				# Feed edited at t=100
		set_mtime(os.path.join(app.path, 'last-checked'), 200)	# Added at t=200

		# Can run without using the solver...
		sels = app.get_selections(may_update = True)
		blocker = app.download_selections(sels)
		self.assertEqual(None, blocker)
		self.assertEqual(0, app._get_mtime('last-solve', warn_if_missing = False))

		# But if the feed is modifier, we resolve...
		set_mtime(local_copy, 300)
		blocker = app.download_selections(app.get_selections(may_update = True))
		self.assertEqual(None, blocker)
		self.assertNotEqual(0, app._get_mtime('last-solve', warn_if_missing = False))

		set_mtime(os.path.join(app.path, 'last-solve'), 400)
		blocker = app.download_selections(app.get_selections(may_update = True))
		self.assertEqual(None, blocker)
		self.assertEqual(400, app._get_mtime('last-solve', warn_if_missing = False))

		import logging; logger.setLevel(logging.ERROR)	# Will display a warning
		os.unlink(local_copy)
		app._touch('last-check-attempt')	# Prevent background update
		blocker = app.download_selections(app.get_selections(may_update = True))
		self.assertEqual(None, blocker)
		self.assertNotEqual(400, app._get_mtime('last-solve', warn_if_missing = False))

		# Local feed is updated; now requires a download
		os.unlink(os.path.join(app.path, 'last-check-attempt'))
		hello_feed = os.path.join(mydir, 'Hello.xml')
		set_mtime(os.path.join(app.path, 'last-solve'), 400)
		self.config.iface_cache._interfaces = {}
		self.config.iface_cache._feeds = {}
		shutil.copyfile(hello_feed, local_copy)
		try:
			blocker = app.download_selections(app.get_selections(may_update = True))
			assert 0
		except BackgroundException:
			pass

		# Selections changed, but no download required
		with open(local_copy, 'rt') as stream:
			data = stream.read()
		data = data.replace(' version="1">',
				    ' version="1.1" main="missing">')
		with open(local_copy, 'wt') as stream:
			stream.write(data)
		set_mtime(os.path.join(app.path, 'last-solve'), 400)

		blocker = app.download_selections(app.get_selections(may_update = True))
		self.assertEqual(None, blocker)
Ejemplo n.º 3
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()

	# 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
Ejemplo n.º 4
0
def main(command_args, config = None):
	"""Act as if 0install was run with the given arguments.
	@arg command_args: array of arguments (e.g. C{sys.argv[1:]})
	@type command_args: [str]
	"""
	_ensure_standard_fds()

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

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

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

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

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

		cmd.add_options(parser)
		(options, args) = parser.parse_args(command_args)
		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
Ejemplo n.º 5
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()

	# 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})

		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
Ejemplo n.º 6
0
    def testAdd(self):
        out, err = self.run_0install(['add', '--help'])
        assert out.lower().startswith("usage:")

        local_feed = os.path.join(mydir, 'Local.xml')
        local_copy = os.path.join(self.data_home, 'Local.xml')

        os.mkdir(self.data_home)
        shutil.copyfile(local_feed, local_copy)

        out, err = self.run_0install(['add', 'local-app', local_copy])
        assert not out, out
        assert not err, err

        app = self.config.app_mgr.lookup_app('local-app')

        # Because the unit-tests run very quickly, we have to back-date things
        # a bit...
        def set_mtime(name, t):
            os.utime(name, (t, t))

        set_mtime(local_copy, 100)  # Feed edited at t=100
        set_mtime(os.path.join(app.path, 'last-checked'),
                  200)  # Added at t=200

        # Can run without using the solver...
        sels = app.get_selections(may_update=True)
        blocker = app.download_selections(sels)
        self.assertEqual(None, blocker)
        self.assertEqual(0, app._get_mtime('last-solve',
                                           warn_if_missing=False))

        # But if the feed is modifier, we resolve...
        set_mtime(local_copy, 300)
        blocker = app.download_selections(app.get_selections(may_update=True))
        self.assertEqual(None, blocker)
        self.assertNotEqual(
            0, app._get_mtime('last-solve', warn_if_missing=False))

        set_mtime(os.path.join(app.path, 'last-solve'), 400)
        blocker = app.download_selections(app.get_selections(may_update=True))
        self.assertEqual(None, blocker)
        self.assertEqual(400,
                         app._get_mtime('last-solve', warn_if_missing=False))

        import logging
        logger.setLevel(logging.ERROR)  # Will display a warning
        os.unlink(local_copy)
        app._touch('last-check-attempt')  # Prevent background update
        blocker = app.download_selections(app.get_selections(may_update=True))
        self.assertEqual(None, blocker)
        self.assertNotEqual(
            400, app._get_mtime('last-solve', warn_if_missing=False))

        # Local feed is updated; now requires a download
        os.unlink(os.path.join(app.path, 'last-check-attempt'))
        hello_feed = os.path.join(mydir, 'Hello.xml')
        set_mtime(os.path.join(app.path, 'last-solve'), 400)
        self.config.iface_cache._interfaces = {}
        self.config.iface_cache._feeds = {}
        shutil.copyfile(hello_feed, local_copy)
        try:
            blocker = app.download_selections(
                app.get_selections(may_update=True))
            assert 0
        except BackgroundException:
            pass

        # Selections changed, but no download required
        with open(local_copy, 'rt') as stream:
            data = stream.read()
        data = data.replace(' version="1">', ' version="1.1" main="missing">')
        with open(local_copy, 'wt') as stream:
            stream.write(data)
        set_mtime(os.path.join(app.path, 'last-solve'), 400)

        blocker = app.download_selections(app.get_selections(may_update=True))
        self.assertEqual(None, blocker)