示例#1
0
    def testFeeds(self):
        iface = model.Interface('http://test/test')
        main_feed = model.ZeroInstallFeed(test_feed, local_path='/Hello')
        self.config.iface_cache._feeds[iface.uri] = main_feed
        iface.stability_policy = model.developer
        main_feed.last_checked = 100
        iface.extra_feeds.append(model.Feed('http://sys-feed', None, False))
        iface.extra_feeds.append(
            model.Feed('http://user-feed', 'Linux-*', True))
        writer.save_interface(iface)
        writer.save_feed(main_feed)

        iface = model.Interface('http://test/test')
        self.assertEquals(None, iface.stability_policy)
        main_feed = model.ZeroInstallFeed(test_feed, local_path='/Hello')
        self.config.iface_cache._feeds[iface.uri] = main_feed
        reader.update_user_overrides(iface)
        reader.update_user_feed_overrides(main_feed)
        self.assertEquals(model.developer, iface.stability_policy)
        self.assertEquals(100, main_feed.last_checked)
        self.assertEquals("[<Feed from http://user-feed>]",
                          str(iface.extra_feeds))

        feed = iface.extra_feeds[0]
        self.assertEquals('http://user-feed', feed.uri)
        self.assertEquals('Linux', feed.os)
        self.assertEquals(None, feed.machine)
示例#2
0
	def testFeeds(self):
		iface = model.Interface('http://test/test')
		main_feed = model.ZeroInstallFeed(test_feed, local_path = '/Hello')
		self.config.iface_cache._feeds[iface.uri] = main_feed
		iface.stability_policy = model.developer
		main_feed.last_checked = 100
		iface.extra_feeds.append(model.Feed('http://sys-feed', None, False))
		iface.extra_feeds.append(model.Feed('http://user-feed', 'Linux-*', True))
		writer.save_interface(iface)
		writer.save_feed(main_feed)

		iface = model.Interface('http://test/test')
		self.assertEqual(None, iface.stability_policy)
		main_feed = model.ZeroInstallFeed(test_feed, local_path = '/Hello')
		self.config.iface_cache._feeds[iface.uri] = main_feed
		reader.update_user_overrides(iface)
		reader.update_user_feed_overrides(main_feed)
		self.assertEqual(model.developer, iface.stability_policy)
		self.assertEqual(100, main_feed.last_checked)
		self.assertEqual("[<Feed from http://user-feed>]", str(iface.extra_feeds))

		feed = iface.extra_feeds[0]
		self.assertEqual('http://user-feed', feed.uri)
		self.assertEqual('Linux', feed.os)
		self.assertEqual(None, feed.machine)
    def ok(feed):
        from zeroinstall.injector import reader
        try:
            feed_targets = policy.get_feed_targets(feed)
            if interface not in feed_targets:
                raise Exception(
                    _("Not a valid feed for '%(uri)s'; this is a feed for:\n%(feed_for)s"
                      ) % {
                          'uri': interface.uri,
                          'feed_for': '\n'.join([f.uri for f in feed_targets])
                      })
            if interface.get_feed(feed):
                dialog.alert(None, _('This feed is already registered.'))
            else:
                interface.extra_feeds.append(
                    Feed(feed, user_override=True, arch=None))

            writer.save_interface(interface)
            chooser.destroy()
            reader.update_from_cache(interface)
            policy.recalculate()
        except Exception, ex:
            dialog.alert(
                None,
                _("Error in feed file '%(feed)s':\n\n%(exception)s") % {
                    'feed': feed,
                    'exception': str(ex)
                })
	def testSitePackages(self):
		# The old system (0install < 1.9):
		# - 0compile stores implementations to ~/.cache, and 
		# - adds to extra_feeds
		#
		# The middle system (0install 1.9..1.12)
		# - 0compile stores implementations to ~/.local/0install.net/site-packages
		#   but using an obsolete escaping scheme, and
		# - modern 0install finds them via extra_feeds
		#
		# The new system (0install >= 1.13):
		# - 0compile stores implementations to ~/.local/0install.net/site-packages, and
		# - 0install finds them automatically

		# For backwards compatibility, 0install >= 1.9:
		# - writes discovered feeds to extra_feeds
		# - skips such entries in extra_feeds when loading

		expected_escape = 'section__prog_5f_1.xml'

		meta_dir = basedir.save_data_path('0install.net', 'site-packages',
						   'http', 'example.com', expected_escape, '1.0', '0install')
		feed = os.path.join(meta_dir, 'feed.xml')
		shutil.copyfile(os.path.join(mydir, 'Local.xml'), feed)

		# Check that we find the feed without us having to register it
		iface = self.config.iface_cache.get_interface('http://example.com/section/prog_1.xml')
		self.assertEqual(1, len(iface.extra_feeds))
		site_feed, = iface.extra_feeds
		self.assertEqual(True, site_feed.site_package)

		# Check that we write it out, so that older 0installs can find it
		writer.save_interface(iface)

		config_file = basedir.load_first_config('0install.net', 'injector',
							'interfaces', 'http:##example.com#section#prog_1.xml')
		with open(config_file, 'rb') as s:
			doc = qdom.parse(s)

		feed_node = None
		for item in doc.childNodes:
			if item.name == 'feed':
				feed_node = item
		self.assertEqual('True', feed_node.getAttribute('is-site-package'))

		# Check we ignore this element
		iface.reset()
		self.assertEqual([], iface.extra_feeds)
		reader.update_user_overrides(iface)
		self.assertEqual([], iface.extra_feeds)

		# Check feeds are automatically removed again
		reader.update_from_cache(iface, iface_cache = self.config.iface_cache)
		self.assertEqual(1, len(iface.extra_feeds))
		shutil.rmtree(basedir.load_first_data('0install.net', 'site-packages',
							'http', 'example.com', expected_escape))

		reader.update_from_cache(iface, iface_cache = self.config.iface_cache)
		self.assertEqual(0, len(iface.extra_feeds))
示例#5
0
def _manage_feeds(options, args):
	from zeroinstall.injector import writer
	from zeroinstall.injector.handler import Handler
	from zeroinstall.injector.policy import Policy
	handler = Handler(dry_run = options.dry_run)
	if not args: raise UsageError()
	for x in args:
		print _("Feed '%s':") % x + '\n'
		x = model.canonical_iface_uri(x)
		policy = Policy(x, handler)
		if options.offline:
			policy.network_use = model.network_offline

		feed = iface_cache.get_feed(x)
		if policy.network_use != model.network_offline and policy.is_stale(feed):
			blocker = policy.fetcher.download_and_import_feed(x, iface_cache.iface_cache)
			print _("Downloading feed; please wait...")
			handler.wait_for_blocker(blocker)
			print _("Done")

		interfaces = policy.get_feed_targets(x)
		for i in range(len(interfaces)):
			feed = interfaces[i].get_feed(x)
			if feed:
				print _("%(index)d) Remove as feed for '%(uri)s'") % {'index': i + 1, 'uri': interfaces[i].uri}
			else:
				print _("%(index)d) Add as feed for '%(uri)s'") % {'index': i + 1, 'uri': interfaces[i].uri}
		print
		while True:
			try:
				i = raw_input(_('Enter a number, or CTRL-C to cancel [1]: ')).strip()
			except KeyboardInterrupt:
				print
				raise SafeException(_("Aborted at user request."))
			if i == '':
				i = 1
			else:
				try:
					i = int(i)
				except ValueError:
					i = 0
			if i > 0 and i <= len(interfaces):
				break
			print _("Invalid number. Try again. (1 to %d)") % len(interfaces)
		iface = interfaces[i - 1]
		feed = iface.get_feed(x)
		if feed:
			iface.extra_feeds.remove(feed)
		else:
			iface.extra_feeds.append(model.Feed(x, arch = None, user_override = True))
		writer.save_interface(iface)
		print '\n' + _("Feed list for interface '%s' is now:") % iface.get_name()
		if iface.feeds:
			for f in iface.feeds:
				print "- " + f.uri
		else:
			print _("(no feeds)")
示例#6
0
	def testStoreNothing(self):
		iface = model.Interface('http://test/test')
		writer.save_interface(iface)

		iface = model.Interface('http://test/test')
		self.assertEqual(None, iface.stability_policy)
		reader.update_user_overrides(iface)

		feed = self.config.iface_cache.get_feed(iface.uri)
		self.assertEqual(None, feed)
示例#7
0
    def testStoreNothing(self):
        iface = model.Interface('http://test/test')
        writer.save_interface(iface)

        iface = model.Interface('http://test/test')
        self.assertEquals(None, iface.stability_policy)
        reader.update_user_overrides(iface)

        feed = self.config.iface_cache.get_feed(iface.uri)
        self.assertEquals(None, feed)
 def set_stability_policy(combo):
     i = stability.get_active()
     if i == 0:
         new_stability = None
     else:
         name = stability.get_model()[i][0].lower()
         new_stability = stability_levels[name]
     interface.set_stability_policy(new_stability)
     writer.save_interface(interface)
     policy.recalculate()
示例#9
0
		def set_stability_policy(combo, stability = stability):	# (pygtk bug?)
			i = stability.get_active()
			if i == 0:
				new_stability = None
			else:
				name = ['stable', 'testing', 'developer'][i-1]
				new_stability = stability_levels[name]
			interface.set_stability_policy(new_stability)
			writer.save_interface(interface)
			import main
			main.recalculate()
示例#10
0
 def set_stability_policy(combo, stability=stability):  # (pygtk bug?)
     i = stability.get_active()
     if i == 0:
         new_stability = None
     else:
         name = ['stable', 'testing', 'developer'][i - 1]
         new_stability = stability_levels[name]
     interface.set_stability_policy(new_stability)
     writer.save_interface(interface)
     import main
     main.recalculate()
示例#11
0
	def testSitePackages(self):
		# The old system (0install < 1.9):
		# - 0compile stores implementations to ~/.cache, and 
		# - adds to extra_feeds
		# The new system (0install >= 1.9):
		# - 0compile stores implementations to ~/.local/0install.net/site-packages, and
		# - 0install finds them automatically

		# For backwards compatibility, 0install >= 1.9:
		# - writes discovered feeds to extra_feeds
		# - skips such entries in extra_feeds when loading

		meta_dir = basedir.save_data_path('0install.net', 'site-packages',
						   'http:##example.com#prog.xml', '1.0', '0install')
		feed = os.path.join(meta_dir, 'feed.xml')
		shutil.copyfile(os.path.join(mydir, 'Local.xml'), feed)

		# Check that we find the feed without us having to register it
		iface = self.config.iface_cache.get_interface('http://example.com/prog.xml')
		self.assertEqual(1, len(iface.extra_feeds))
		site_feed, = iface.extra_feeds
		self.assertEqual(True, site_feed.site_package)

		# Check that we write it out, so that older 0installs can find it
		writer.save_interface(iface)

		config_file = basedir.load_first_config('0install.net', 'injector',
							'interfaces', 'http:##example.com#prog.xml')
		with open(config_file, 'rb') as s:
			doc = qdom.parse(s)

		feed_node = None
		for item in doc.childNodes:
			if item.name == 'feed':
				feed_node = item
		self.assertEqual('True', feed_node.getAttribute('site-package'))

		# Check we ignore this element
		iface.reset()
		self.assertEqual([], iface.extra_feeds)
		reader.update_user_overrides(iface)
		self.assertEqual([], iface.extra_feeds)

		# Check feeds are automatically removed again
		reader.update_from_cache(iface, iface_cache = self.config.iface_cache)
		self.assertEqual(1, len(iface.extra_feeds))
		shutil.rmtree(basedir.load_first_data('0install.net', 'site-packages',
							'http:##example.com#prog.xml'))

		reader.update_from_cache(iface, iface_cache = self.config.iface_cache)
		self.assertEqual(0, len(iface.extra_feeds))
def handle(config, options, args):
	if len(args) == 2:
		iface = config.iface_cache.get_interface(model.canonical_iface_uri(args[0]))
		feed_url = args[1]

		feed_import = add_feed.find_feed_import(iface, feed_url)
		if not feed_import:
			raise SafeException(_('Interface %(interface)s has no feed %(feed)s') %
						{'interface': iface.uri, 'feed': feed_url})
		iface.extra_feeds.remove(feed_import)
		writer.save_interface(iface)
	elif len(args) == 1:
		add_feed.handle(config, options, args, add_ok = False, remove_ok = True)
	else:
		raise UsageError()
		def remove_feed(button):
			model, iter = self.tv.get_selection().get_selected()
			feed_uri = model[iter][Feeds.URI]
			for x in interface.extra_feeds:
				if x.uri == feed_uri:
					if x.user_override:
						interface.extra_feeds.remove(x)
						writer.save_interface(interface)
						import main
						main.recalculate()
						return
					else:
						dialog.alert(self.get_toplevel(),
							_("Can't remove '%s' as you didn't add it.") % feed_uri)
						return
			raise Exception(_("Missing feed '%s'!") % feed_uri)
示例#14
0
	def ok(feed):
		from zeroinstall.injector import reader
		try:
			feed_targets = policy.get_feed_targets(feed)
			if interface not in feed_targets:
				raise Exception(_("Not a valid feed for '%(uri)s'; this is a feed for:\n%(feed_for)s") %
						{'uri': interface.uri,
						'feed_for': '\n'.join([f.uri for f in feed_targets])})
			if feed in [f.uri for f in interface.extra_feeds]:
				dialog.alert(None, _('This feed is already registered.'))
			else:
				interface.extra_feeds.append(Feed(feed, user_override = True, arch = None))

			writer.save_interface(interface)
			chooser.destroy()
			reader.update_from_cache(interface)
			import main
			main.recalculate()
		except Exception as ex:
			dialog.alert(None, _("Error in feed file '%(feed)s':\n\n%(exception)s") % {'feed': feed, 'exception': str(ex)})
def add_remote_feed(policy, parent, interface):
    try:
        d = gtk.MessageDialog(
            parent, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL,
            _('Enter the URL of the new source of implementations of this interface:'
              ))
        d.add_button(gtk.STOCK_ADD, gtk.RESPONSE_OK)
        d.set_default_response(gtk.RESPONSE_OK)
        entry = gtk.Entry()

        align = gtk.VBox(False, 0)
        align.set_border_width(4)
        align.add(entry)
        d.vbox.pack_start(align)
        entry.set_activates_default(True)

        entry.set_text('')

        d.vbox.show_all()

        error_label = gtk.Label('')
        error_label.set_padding(4, 4)
        align.pack_start(error_label)

        d.show()

        def error(message):
            if message:
                error_label.set_text(message)
                error_label.show()
            else:
                error_label.hide()

        while True:
            got_response = DialogResponse(d)
            yield got_response
            tasks.check(got_response)
            resp = got_response.response

            error(None)
            if resp == gtk.RESPONSE_OK:
                try:
                    url = entry.get_text()
                    if not url:
                        raise zeroinstall.SafeException(_('Enter a URL'))
                    fetch = policy.fetcher.download_and_import_feed(
                        url, iface_cache)
                    if fetch:
                        d.set_sensitive(False)
                        yield fetch
                        d.set_sensitive(True)
                        tasks.check(fetch)

                        iface = iface_cache.get_interface(url)

                        d.set_sensitive(True)
                        if not iface.name:
                            error(_('Failed to read interface'))
                            return
                        if not iface.feed_for:
                            error(
                                _("Feed '%(feed)s' is not a feed for '%(feed_for)s'."
                                  ) % {
                                      'feed': iface.get_name(),
                                      'feed_for': interface.get_name()
                                  })
                        elif interface.uri not in iface.feed_for:
                            error(
                                _("This is not a feed for '%(uri)s'.\nOnly for:\n%(feed_for)s"
                                  ) % {
                                      'uri': interface.uri,
                                      'feed_for': '\n'.join(iface.feed_for)
                                  })
                        elif iface.uri in [f.uri for f in interface.feeds]:
                            error(
                                _("Feed from '%s' has already been added!") %
                                iface.uri)
                        else:
                            interface.extra_feeds.append(
                                Feed(iface.uri, arch=None, user_override=True))
                            writer.save_interface(interface)
                            d.destroy()
                            policy.recalculate()
                except zeroinstall.SafeException, ex:
                    error(str(ex))
            else:
                d.destroy()
                return
    except Exception, ex:
        import traceback
        traceback.print_exc()
        policy.handler.report_error(ex)
示例#16
0
	def compile_and_register(self, sels, forced_iface_uri = None):
		"""If forced_iface_uri, register as an implementation of this interface,
		ignoring the any <feed-for>, etc."""

		buildenv = BuildEnv(need_config = False)
		buildenv.config.set('compile', 'interface', sels.interface)
		buildenv.config.set('compile', 'selections', 'selections.xml')
		
		# Download any required packages now, so we can use the GUI to request confirmation, etc
		download_missing = sels.download_missing(self.config, include_packages = True)
		if download_missing:
			yield download_missing
			tasks.check(download_missing)

		tmpdir = tempfile.mkdtemp(prefix = '0compile-')
		try:
			os.chdir(tmpdir)

			# Write configuration for build...

			buildenv.save()

			sel_file = open('selections.xml', 'w')
			try:
				doc = sels.toDOM()
				doc.writexml(sel_file)
				sel_file.write('\n')
			finally:
				sel_file.close()

			# Do the build...

			build = self.spawn_build(buildenv.iface_name)
			if build:
				yield build
				tasks.check(build)

			# Register the result...
			dom = minidom.parse(buildenv.local_iface_file)

			feed_for_elem, = dom.getElementsByTagNameNS(namespaces.XMLNS_IFACE, 'feed-for')
			claimed_iface = feed_for_elem.getAttribute('interface')

			if forced_iface_uri is not None:
				if forced_iface_uri != claimed_iface:
					self.note("WARNING: registering as feed for {forced}, though feed claims to be for {claimed}".format(
						forced = forced_iface_uri,
						claimed = claimed_iface))
			else:
				forced_iface_uri = claimed_iface		# (the top-level interface being built)

			version = sels.selections[sels.interface].version

			site_package_versions_dir = basedir.save_data_path('0install.net', 'site-packages',
						*model.escape_interface_uri(forced_iface_uri))
			leaf =  '%s-%s' % (version, uname[4])
			site_package_dir = os.path.join(site_package_versions_dir, leaf)
			self.note("Storing build in %s" % site_package_dir)

			# 1. Copy new version in under a temporary name. Names starting with '.' are ignored by 0install.
			tmp_distdir = os.path.join(site_package_versions_dir, '.new-' + leaf)
			shutil.copytree(buildenv.distdir, tmp_distdir, symlinks = True)

			# 2. Rename the previous build to .old-VERSION (deleting that if it already existed)
			if os.path.exists(site_package_dir):
				self.note("(moving previous build out of the way)")
				previous_build_dir = os.path.join(site_package_versions_dir, '.old-' + leaf)
				if os.path.exists(previous_build_dir):
					shutil.rmtree(previous_build_dir)
				os.rename(site_package_dir, previous_build_dir)
			else:
				previous_build_dir = None

			# 3. Rename the new version immediately after renaming away the old one to minimise time when there's
			# no version.
			os.rename(tmp_distdir, site_package_dir)

			# 4. Delete the old version.
			if previous_build_dir:
				self.note("(deleting previous build)")
				shutil.rmtree(previous_build_dir)

			local_feed = os.path.join(site_package_dir, '0install', 'feed.xml')
			assert os.path.exists(local_feed), "Feed %s not found!" % local_feed

			# Reload - our 0install will detect the new feed automatically
			iface = self.config.iface_cache.get_interface(forced_iface_uri)
			reader.update_from_cache(iface, iface_cache = self.config.iface_cache)
			self.config.iface_cache.get_feed(local_feed, force = True)

			# Write it out - 0install will add the feed so that older 0install versions can find it
			writer.save_interface(iface)
		except:
			self.note("\nBuild failed: leaving build directory %s for inspection...\n" % tmpdir)
			raise
		else:
			# Can't delete current directory on Windows, so move to parent first
			os.chdir(os.path.join(tmpdir, os.path.pardir))

			ro_rmtree(tmpdir)
示例#17
0
    def compile_and_register(self, sels, forced_iface_uri=None):
        """If forced_iface_uri, register as an implementation of this interface,
		ignoring the any <feed-for>, etc."""

        buildenv = BuildEnv(need_config=False)
        buildenv.config.set('compile', 'interface', sels.interface)
        buildenv.config.set('compile', 'selections', 'selections.xml')

        # Download any required packages now, so we can use the GUI to request confirmation, etc
        download_missing = sels.download_missing(self.config,
                                                 include_packages=True)
        if download_missing:
            yield download_missing
            tasks.check(download_missing)

        tmpdir = tempfile.mkdtemp(prefix='0compile-')
        try:
            os.chdir(tmpdir)

            # Write configuration for build...

            buildenv.save()

            sel_file = open('selections.xml', 'w')
            try:
                doc = sels.toDOM()
                doc.writexml(sel_file)
                sel_file.write('\n')
            finally:
                sel_file.close()

            # Do the build...

            build = self.spawn_build(buildenv.iface_name)
            if build:
                yield build
                tasks.check(build)

            # Register the result...
            dom = minidom.parse(buildenv.local_iface_file)

            feed_for_elem, = dom.getElementsByTagNameNS(
                namespaces.XMLNS_IFACE, 'feed-for')
            claimed_iface = feed_for_elem.getAttribute('interface')

            if forced_iface_uri is not None:
                if forced_iface_uri != claimed_iface:
                    self.note(
                        "WARNING: registering as feed for {forced}, though feed claims to be for {claimed}"
                        .format(forced=forced_iface_uri,
                                claimed=claimed_iface))
            else:
                forced_iface_uri = claimed_iface  # (the top-level interface being built)

            version = sels.selections[sels.interface].version

            site_package_versions_dir = basedir.save_data_path(
                '0install.net', 'site-packages',
                *model.escape_interface_uri(forced_iface_uri))
            leaf = '%s-%s' % (version, build_target_machine_type)
            site_package_dir = os.path.join(site_package_versions_dir, leaf)
            self.note("Storing build in %s" % site_package_dir)

            # 1. Copy new version in under a temporary name. Names starting with '.' are ignored by 0install.
            tmp_distdir = os.path.join(site_package_versions_dir,
                                       '.new-' + leaf)
            shutil.copytree(buildenv.distdir, tmp_distdir, symlinks=True)

            # 2. Rename the previous build to .old-VERSION (deleting that if it already existed)
            if os.path.exists(site_package_dir):
                self.note("(moving previous build out of the way)")
                previous_build_dir = os.path.join(site_package_versions_dir,
                                                  '.old-' + leaf)
                if os.path.exists(previous_build_dir):
                    shutil.rmtree(previous_build_dir)
                os.rename(site_package_dir, previous_build_dir)
            else:
                previous_build_dir = None

            # 3. Rename the new version immediately after renaming away the old one to minimise time when there's
            # no version.
            os.rename(tmp_distdir, site_package_dir)

            # 4. Delete the old version.
            if previous_build_dir:
                self.note("(deleting previous build)")
                shutil.rmtree(previous_build_dir)

            local_feed = os.path.join(site_package_dir, '0install', 'feed.xml')
            assert os.path.exists(
                local_feed), "Feed %s not found!" % local_feed

            # Reload - our 0install will detect the new feed automatically
            iface = self.config.iface_cache.get_interface(forced_iface_uri)
            reader.update_from_cache(iface,
                                     iface_cache=self.config.iface_cache)
            self.config.iface_cache.get_feed(local_feed, force=True)

            # Write it out - 0install will add the feed so that older 0install versions can find it
            writer.save_interface(iface)

            seen_key = (forced_iface_uri, sels.selections[sels.interface].id)
            assert seen_key not in self.seen, seen_key
            self.seen[seen_key] = site_package_dir
        except:
            self.note(
                "\nBuild failed: leaving build directory %s for inspection...\n"
                % tmpdir)
            raise
        else:
            # Can't delete current directory on Windows, so move to parent first
            os.chdir(os.path.join(tmpdir, os.path.pardir))

            ro_rmtree(tmpdir)
示例#18
0
def handle(config, options, args, add_ok = True, remove_ok = False):
	"""@type add_ok: bool
	@type remove_ok: bool"""
	if len(args) == 2:
		iface = config.iface_cache.get_interface(model.canonical_iface_uri(args[0]))
		feed_url = model.canonical_iface_uri(args[1])

		feed_import = find_feed_import(iface, feed_url)
		if feed_import:
			raise SafeException(_('Interface %(interface)s already has a feed %(feed)s') %
						{'interface': iface.uri, 'feed': feed_url})
		iface.extra_feeds.append(model.Feed(feed_url, arch = None, user_override = True))
		writer.save_interface(iface)
		return
	elif len(args) != 1: raise UsageError()

	x = args[0]

	print(_("Feed '%s':") % x + '\n')
	x = model.canonical_iface_uri(x)
	if options.offline:
		config.network_use = model.network_offline

	if config.network_use != model.network_offline and config.iface_cache.is_stale(x, config.freshness):
		blocker = config.fetcher.download_and_import_feed(x, config.iface_cache)
		print(_("Downloading feed; please wait..."))
		tasks.wait_for_blocker(blocker)
		print(_("Done"))

	candidate_interfaces = config.iface_cache.get_feed_targets(x)
	assert candidate_interfaces
	interfaces = []
	for i in range(len(candidate_interfaces)):
		iface = candidate_interfaces[i]
		if find_feed_import(iface, x):
			if remove_ok:
				print(_("%(index)d) Remove as feed for '%(uri)s'") % {'index': i + 1, 'uri': iface.uri})
				interfaces.append(iface)
		else:
			if add_ok:
				print(_("%(index)d) Add as feed for '%(uri)s'") % {'index': i + 1, 'uri': iface.uri})
				interfaces.append(iface)
	if not interfaces:
		if remove_ok:
			raise SafeException(_("%(feed)s is not registered as a feed for %(interface)s") %
						{'feed': x, 'interface': candidate_interfaces[0]})
		else:
			raise SafeException(_("%(feed)s already registered as a feed for %(interface)s") %
						{'feed': x, 'interface': candidate_interfaces[0]})
	print()
	while True:
		try:
			i = raw_input(_('Enter a number, or CTRL-C to cancel [1]: ')).strip()
		except KeyboardInterrupt:
			print()
			raise SafeException(_("Aborted at user request."))
		if i == '':
			i = 1
		else:
			try:
				i = int(i)
			except ValueError:
				i = 0
		if i > 0 and i <= len(interfaces):
			break
		print(_("Invalid number. Try again. (1 to %d)") % len(interfaces))
	iface = interfaces[i - 1]
	feed_import = find_feed_import(iface, x)
	if feed_import:
		iface.extra_feeds.remove(feed_import)
	else:
		iface.extra_feeds.append(model.Feed(x, arch = None, user_override = True))
	writer.save_interface(iface)
	print('\n' + _("Feed list for interface '%s' is now:") % iface.get_name())
	if iface.extra_feeds:
		for f in iface.extra_feeds:
			print("- " + f.uri)
	else:
		print(_("(no feeds)"))
示例#19
0
def handle(config, options, args, add_ok = True, remove_ok = False):
	if not args: raise UsageError()

	def find_feed_import(iface, feed_url):
		for f in iface.extra_feeds:
			if f.uri == feed_url:
				return f
		return None

	for x in args:
		print _("Feed '%s':") % x + '\n'
		x = model.canonical_iface_uri(x)
		policy = Policy(x, config = config)
		if options.offline:
			config.network_use = model.network_offline

		feed = config.iface_cache.get_feed(x)
		if policy.network_use != model.network_offline and policy.is_stale(feed):
			blocker = policy.fetcher.download_and_import_feed(x, config.iface_cache)
			print _("Downloading feed; please wait...")
			config.handler.wait_for_blocker(blocker)
			print _("Done")

		candidate_interfaces = policy.get_feed_targets(x)
		assert candidate_interfaces
		interfaces = []
		for i in range(len(candidate_interfaces)):
			iface = candidate_interfaces[i]
			if find_feed_import(iface, x):
				if remove_ok:
					print _("%(index)d) Remove as feed for '%(uri)s'") % {'index': i + 1, 'uri': iface.uri}
					interfaces.append(iface)
			else:
				if add_ok:
					print _("%(index)d) Add as feed for '%(uri)s'") % {'index': i + 1, 'uri': iface.uri}
					interfaces.append(iface)
		if not interfaces:
			if remove_ok:
				raise SafeException(_("%(feed)s is not registered as a feed for %(interface)s") %
							{'feed': x, 'interface': candidate_interfaces[0]})
			else:
				raise SafeException(_("%(feed)s already registered as a feed for %(interface)s") %
							{'feed': x, 'interface': candidate_interfaces[0]})
		print
		while True:
			try:
				i = raw_input(_('Enter a number, or CTRL-C to cancel [1]: ')).strip()
			except KeyboardInterrupt:
				print
				raise SafeException(_("Aborted at user request."))
			if i == '':
				i = 1
			else:
				try:
					i = int(i)
				except ValueError:
					i = 0
			if i > 0 and i <= len(interfaces):
				break
			print _("Invalid number. Try again. (1 to %d)") % len(interfaces)
		iface = interfaces[i - 1]
		feed_import = find_feed_import(iface, x)
		if feed_import:
			iface.extra_feeds.remove(feed_import)
		else:
			iface.extra_feeds.append(model.Feed(x, arch = None, user_override = True))
		writer.save_interface(iface)
		print '\n' + _("Feed list for interface '%s' is now:") % iface.get_name()
		if iface.extra_feeds:
			for f in iface.extra_feeds:
				print "- " + f.uri
		else:
			print _("(no feeds)")
示例#20
0
		def response(box, resp):
			if resp == RESPONSE_SETUP:
				def done_setup():
					self.add_msg('Now use Build to compile the chosen source code.')
				self.run_command((sys.executable, main_path, 'setup'), done_setup)
			elif resp == RESPONSE_BUILD:
				def done_build():
					self.add_msg('\nBuild successful. Now register or publish the build.')
				def build_failed():
					self.add_msg('\nIf the messages displayed above indicate a missing dependency (e.g. no C compiler '
						     "or a library that isn't available through Zero Install) then install it using your "
						     'normal package manager and click on Build again. Note that for libraries you often '
						     'need the -dev version of the package. '
						     '\nOtherwise, please notify the developers of this problem (this will transmit '
						     'the contents of the build/build-failure.log file):')
					end = self.buffer.get_end_iter()
					anchor = self.buffer.create_child_anchor(end)
					align = gtk.Alignment(0.0, 0.0, 1.0, 1.0)
					button = ButtonMixed(gtk.STOCK_YES, 'Notify developers')
					align.add(button)
					align.set_padding(8, 8, 8, 8)
					align.show_all()
					self.tv.add_child_at_anchor(align, anchor)
					self.add_msg('\n')
					def report_bug(button):
						def done_notify():
							self.add_msg("\nReport sent. Thank you! (note: you won't get a reply, as "
								"no contact details were sent; write to the project's mailing "
								"list if you want to discuss the problem)")
						self.run_command((sys.executable, main_path, 'report-bug'), done_notify)
					button.connect('clicked', report_bug)
				buildenv = BuildEnv()
				changes = buildenv.get_build_changes()
				if changes:
					options = get_build_options(box, '\n'.join(changes) + '\n\nIt would be best to do a clean (full) build.')
				else:
					options = []
				if options is not None:
					box.run_command([sys.executable, main_path, 'build'] + options, done_build, build_failed)
			elif resp == RESPONSE_REGISTER:
				buildenv = BuildEnv()

				iface = iface_cache.get_interface(interface)
				reader.update_from_cache(iface)

				# Register using the feed-for, if available
				real_iface = iface
				for uri in iface.feed_for or []:
					real_iface = iface_cache.get_interface(uri)
					self.add_msg("Registering as a feed for %s" % real_iface.uri)
					break
				else:
					if os.path.isabs(iface.uri):
						self.add_msg("Warning: no <feed-for> in local feed %s!" % iface.uri)

				feed = buildenv.local_iface_file
				for f in real_iface.feeds or []:
					if f.uri == feed:
						self.add_msg("Feed '%s' is already registered for interface '%s'!\n" % (feed, real_iface.uri))
						return
				box.buffer.insert_at_cursor("Registering feed '%s'\n" % feed)
				real_iface.extra_feeds.append(model.Feed(feed, arch = None, user_override = True))
				writer.save_interface(real_iface)
				box.buffer.insert_at_cursor("Done. You can now close this window.\n")
			elif resp == RESPONSE_PUBLISH:
				buildenv = BuildEnv()
				box = PublishBox(self, buildenv)
				resp = box.run()
				box.destroy()
				if resp == gtk.RESPONSE_OK:
					def done_publish():
						self.add_msg("\nYou can use '0publish --local' to add this "
							"into the main feed. If you don't have a main feed then this "
							"will create one. See "
							"http://0install.net/injector-packagers.html for more information.")
					self.run_command((sys.executable, main_path,
						'publish', box.archive_dir.get_text()), done_publish)
			elif resp == gtk.RESPONSE_CANCEL or resp == gtk.RESPONSE_DELETE_EVENT:
				if self.kill_child(): return
				self.destroy()
			else:
				self.add_msg('Unknown response: %s' % resp)
示例#21
0
def add_remote_feed(policy, parent, interface):
	try:
		iface_cache = policy.config.iface_cache

		d = gtk.MessageDialog(parent, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CANCEL,
			_('Enter the URL of the new source of implementations of this interface:'))
		d.add_button(gtk.STOCK_ADD, gtk.RESPONSE_OK)
		d.set_default_response(gtk.RESPONSE_OK)
		entry = gtk.Entry()

		align = gtk.VBox(False, 0)
		align.set_border_width(4)
		align.add(entry)
		d.vbox.pack_start(align)
		entry.set_activates_default(True)

		entry.set_text('')

		d.vbox.show_all()

		error_label = gtk.Label('')
		error_label.set_padding(4, 4)
		align.pack_start(error_label)

		d.show()

		def error(message):
			if message:
				error_label.set_text(message)
				error_label.show()
			else:
				error_label.hide()

		while True:
			got_response = DialogResponse(d)
			yield got_response
			tasks.check(got_response)
			resp = got_response.response

			error(None)
			if resp == gtk.RESPONSE_OK:
				try:
					url = entry.get_text()
					if not url:
						raise zeroinstall.SafeException(_('Enter a URL'))
					fetch = policy.fetcher.download_and_import_feed(url, iface_cache)
					if fetch:
						d.set_sensitive(False)
						yield fetch
						d.set_sensitive(True)
						tasks.check(fetch)

						iface = iface_cache.get_interface(url)

						d.set_sensitive(True)
						if not iface.name:
							error(_('Failed to read interface'))
							return
						if not iface.feed_for:
							error(_("Feed '%(feed)s' is not a feed for '%(feed_for)s'.") % {'feed': iface.get_name(), 'feed_for': interface.get_name()})
						elif interface.uri not in iface.feed_for:
							error(_("This is not a feed for '%(uri)s'.\nOnly for:\n%(feed_for)s") %
								{'uri': interface.uri, 'feed_for': '\n'.join(iface.feed_for)})
						elif iface.uri in [f.uri for f in interface.extra_feeds]:
							error(_("Feed from '%s' has already been added!") % iface.uri)
						else:
							interface.extra_feeds.append(Feed(iface.uri, arch = None, user_override = True))
							writer.save_interface(interface)
							d.destroy()
							import main
							main.recalculate()
				except zeroinstall.SafeException as ex:
					error(str(ex))
			else:
				d.destroy()
				return
	except Exception as ex:
		import traceback
		traceback.print_exc()
		policy.handler.report_error(ex)