Exemplo n.º 1
0
    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
Exemplo n.º 2
0
    def testDebian(self):
        dpkgdir = os.path.join(os.path.dirname(__file__), 'dpkg')
        host = distro.DebianDistribution(os.path.join(dpkgdir, 'status'))
        host._packagekit = DummyPackageKit()

        factory = self.make_factory(host)
        host.get_package_info('gimp', factory)
        self.assertEqual({}, self.feed.implementations)

        # Initially, we only get information about the installed version...
        host.get_package_info('python-bittorrent', factory)
        self.assertEqual(1, len(self.feed.implementations))

        # Tell distro to fetch information about candidates...
        master_feed = parse_impls(
            """<package-implementation package='python-bittorrent'>
					       <restricts interface='http://python.org/python'>
					         <version not-before='3'/>
					       </restricts>
					     </package-implementation>
					  """)
        h = handler.Handler()
        candidates = host.fetch_candidates(master_feed)
        if candidates:
            h.wait_for_blocker(candidates)
        # Now we see the uninstalled package
        self.feed = host.get_feed(master_feed)
        self.assertEqual(2, len(self.feed.implementations))

        # Check restriction appears for both candidates
        for impl in self.feed.implementations.values():
            self.assertEqual(1, len(impl.requires))
            self.assertEqual("http://python.org/python",
                             impl.requires[0].interface)

        self.assertEqual(2, len(self.feed.implementations))
        bittorrent_installed = self.feed.implementations[
            'package:deb:python-bittorrent:3.4.2-10:*']
        bittorrent_uninstalled = self.feed.implementations[
            'package:deb:python-bittorrent:3.4.2-11.1:*']
        self.assertEqual('3.4.2-10', bittorrent_installed.get_version())
        self.assertTrue(bittorrent_installed.installed)
        self.assertFalse(bittorrent_uninstalled.installed)
        self.assertEqual(None, bittorrent_installed.machine)

        self.feed = model.ZeroInstallFeed(empty_feed, local_path='/empty.xml')
        host.get_package_info('libxcomposite-dev', factory)
        self.assertEqual(1, len(self.feed.implementations))
        libxcomposite = self.feed.implementations[
            'package:deb:libxcomposite-dev:0.3.1-1:i386']
        self.assertEqual('0.3.1-1', libxcomposite.get_version())
        self.assertEqual('i386', libxcomposite.machine)

        # Java is special...
        master_feed = parse_impls(
            """<package-implementation package='openjdk-7-jre'/>""")
        feed = host.get_feed(master_feed)
        self.assertEqual(1, len(feed.implementations))
        self.assertEqual('7.3-2.1.1-3',
                         list(feed.implementations.values())[0].get_version())
Exemplo n.º 3
0
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()
Exemplo n.º 4
0
 def handler(self):
     if not self._handler:
         from zeroinstall.injector import handler
         if os.isatty(1):
             self._handler = handler.ConsoleHandler()
         else:
             self._handler = handler.Handler()
     return self._handler
Exemplo n.º 5
0
	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
Exemplo n.º 6
0
	def testDebian(self):
		dpkgdir = os.path.join(os.path.dirname(__file__), 'dpkg')
		host = distro.DebianDistribution(
				os.path.join(dpkgdir, 'status'),
				os.path.join(dpkgdir, 'pkgcache.bin'))
		host._packagekit = DummyPackageKit()

		factory = self.make_factory(host)
		host.get_package_info('gimp', factory)
		self.assertEquals({}, self.feed.implementations)

		# Initially, we only get information about the installed version...
		host.get_package_info('python-bittorrent', factory)
		self.assertEquals(1, len(self.feed.implementations))

		# Tell distro to fetch information about candidates...
		master_feed = parse_impls("""<package-implementation package='python-bittorrent'/>""")
		h = handler.Handler()
		candidates = host.fetch_candidates(master_feed)
		if candidates:
			h.wait_for_blocker(candidates)
		# Now we see the uninstalled package
		self.feed = model.ZeroInstallFeed(empty_feed, local_path = '/empty.xml')
		host.get_package_info('python-bittorrent', factory)
		self.assertEquals(2, len(self.feed.implementations))

		self.assertEquals(2, len(self.feed.implementations))
		bittorrent_installed = self.feed.implementations['package:deb:python-bittorrent:3.4.2-10:*']
		bittorrent_uninstalled = self.feed.implementations['package:deb:python-bittorrent:3.4.2-11.1:*']
		self.assertEquals('3.4.2-10', bittorrent_installed.get_version())
		self.assertTrue(bittorrent_installed.installed)
		self.assertFalse(bittorrent_uninstalled.installed)
		self.assertEquals(None, bittorrent_installed.machine)

		self.feed = model.ZeroInstallFeed(empty_feed, local_path = '/empty.xml')
		host.get_package_info('libxcomposite-dev', factory)
		self.assertEquals(1, len(self.feed.implementations))
		libxcomposite = self.feed.implementations['package:deb:libxcomposite-dev:0.3.1-1:i386']
		self.assertEquals('0.3.1-1', libxcomposite.get_version())
		self.assertEquals('i386', libxcomposite.machine)
Exemplo n.º 7
0
def _import_feed(args):
	from zeroinstall.support import tasks
	from zeroinstall.injector import gpg, handler
	from zeroinstall.injector.iface_cache import PendingFeed
	from xml.dom import minidom
	handler = handler.Handler()

	for x in args:
		if not os.path.isfile(x):
			raise SafeException(_("File '%s' does not exist") % x)
		logging.info(_("Importing from file '%s'"), x)
		signed_data = file(x)
		data, sigs = gpg.check_stream(signed_data)
		doc = minidom.parseString(data.read())
		uri = doc.documentElement.getAttribute('uri')
		if not uri:
			raise SafeException(_("Missing 'uri' attribute on root element in '%s'") % x)
		iface = iface_cache.get_interface(uri)
		logging.info(_("Importing information about interface %s"), iface)
		signed_data.seek(0)

		pending = PendingFeed(uri, signed_data)

		def run():
			keys_downloaded = tasks.Task(pending.download_keys(handler), "download keys")
			yield keys_downloaded.finished
			tasks.check(keys_downloaded.finished)
			if not iface_cache.update_interface_if_trusted(iface, pending.sigs, pending.new_xml):
				blocker = handler.confirm_trust_keys(iface, pending.sigs, pending.new_xml)
				if blocker:
					yield blocker
					tasks.check(blocker)
				if not iface_cache.update_interface_if_trusted(iface, pending.sigs, pending.new_xml):
					raise SafeException(_("No signing keys trusted; not importing"))

		task = tasks.Task(run(), "import feed")

		errors = handler.wait_for_blocker(task.finished)
		if errors:
			raise SafeException(_("Errors during download: ") + '\n'.join(errors))
Exemplo n.º 8
0
def _normal_mode(options, args):
	from zeroinstall.injector import handler

	if len(args) < 1:
		if options.gui:
			from zeroinstall import helpers
			return helpers.get_selections_gui(None, [])
		else:
			raise UsageError()

	iface_uri = model.canonical_iface_uri(args[0])
	root_iface = iface_cache.get_interface(iface_uri)

	if os.isatty(1):
		h = handler.ConsoleHandler()
	else:
		h = handler.Handler()
	h.dry_run = bool(options.dry_run)

	policy = autopolicy.AutoPolicy(iface_uri,
				handler = h,
				download_only = bool(options.download_only),
				src = options.source)

	if options.before or options.not_before:
		policy.solver.extra_restrictions[root_iface] = [model.VersionRangeRestriction(model.parse_version(options.before),
									      		      model.parse_version(options.not_before))]

	if options.os or options.cpu:
		from zeroinstall.injector import arch
		policy.target_arch = arch.get_architecture(options.os, options.cpu)

	if options.offline:
		policy.network_use = model.network_offline

	if options.get_selections:
		if len(args) > 1:
			raise SafeException(_("Can't use arguments with --get-selections"))
		if options.main:
			raise SafeException(_("Can't use --main with --get-selections"))

	# Note that need_download() triggers a solve
	if options.refresh or options.gui:
		# We could run immediately, but the user asked us not to
		can_run_immediately = False
	else:
		can_run_immediately = (not policy.need_download()) and policy.ready

		stale_feeds = [feed for feed in policy.solver.feeds_used if policy.is_stale(iface_cache.get_feed(feed))]

		if options.download_only and stale_feeds:
			can_run_immediately = False

	if can_run_immediately:
		if stale_feeds:
			if policy.network_use == model.network_offline:
				logging.debug(_("No doing background update because we are in off-line mode."))
			else:
				# There are feeds we should update, but we can run without them.
				# Do the update in the background while the program is running.
				import background
				background.spawn_background_update(policy, options.verbose > 0)
		if options.get_selections:
			_get_selections(policy)
		else:
			if not options.download_only:
				from zeroinstall.injector import run
				run.execute(policy, args[1:], dry_run = options.dry_run, main = options.main, wrapper = options.wrapper)
			else:
				logging.info(_("Downloads done (download-only mode)"))
			assert options.dry_run or options.download_only
		return

	# If the user didn't say whether to use the GUI, choose for them.
	if options.gui is None and os.environ.get('DISPLAY', None):
		options.gui = True
		# If we need to download anything, we might as well
		# refresh all the interfaces first. Also, this triggers
		# the 'checking for updates' box, which is non-interactive
		# when there are no changes to the selection.
		options.refresh = True
		logging.info(_("Switching to GUI mode... (use --console to disable)"))

	prog_args = args[1:]

	try:
		from zeroinstall.injector import run
		if options.gui:
			gui_args = []
			if options.download_only:
				# Just changes the button's label
				gui_args.append('--download-only')
			if options.refresh:
				gui_args.append('--refresh')
			if options.systray:
				gui_args.append('--systray')
			if options.not_before:
				gui_args.insert(0, options.not_before)
				gui_args.insert(0, '--not-before')
			if options.before:
				gui_args.insert(0, options.before)
				gui_args.insert(0, '--before')
			if options.source:
				gui_args.insert(0, '--source')
			if options.message:
				gui_args.insert(0, options.message)
				gui_args.insert(0, '--message')
			if options.verbose:
				gui_args.insert(0, '--verbose')
				if options.verbose > 1:
					gui_args.insert(0, '--verbose')
			if options.cpu:
				gui_args.insert(0, options.cpu)
				gui_args.insert(0, '--cpu')
			if options.os:
				gui_args.insert(0, options.os)
				gui_args.insert(0, '--os')
			if options.with_store:
				for x in options.with_store:
					gui_args += ['--with-store', x]
			sels = _fork_gui(iface_uri, gui_args, prog_args, options)
			if not sels:
				sys.exit(1)		# Aborted
		else:
			#program_log('download_and_execute ' + iface_uri)
			downloaded = policy.solve_and_download_impls(refresh = bool(options.refresh))
			if downloaded:
				policy.handler.wait_for_blocker(downloaded)
			sels = selections.Selections(policy)

		if options.get_selections:
			doc = sels.toDOM()
			doc.writexml(sys.stdout)
			sys.stdout.write('\n')
		elif not options.download_only:
			run.execute_selections(sels, prog_args, options.dry_run, options.main, options.wrapper)

	except NeedDownload, ex:
		# This only happens for dry runs
		print ex