0launch internally now uses new 0install command code
[zeroinstall/zeroinstall-limyreth.git] / zeroinstall / cmd / select.py
blob201552e28e3eafc2e56eb9c2dccad576d44de1e6
1 """
2 The B{0install select} command-line interface.
3 """
5 # Copyright (C) 2011, Thomas Leonard
6 # See the README file for details, or visit http://0install.net.
8 from optparse import OptionParser
9 import os, sys
10 import logging
12 from zeroinstall import cmd, SafeException, _
13 from zeroinstall.cmd import UsageError
14 from zeroinstall.injector import model, autopolicy, selections, handler
15 from zeroinstall.injector.iface_cache import iface_cache
17 syntax = "URI"
19 def add_generic_select_options(parser):
20 """All options for selecting."""
21 parser.add_option("", "--before", help=_("choose a version before this"), metavar='VERSION')
22 parser.add_option("", "--command", help=_("command to select"), metavar='COMMAND')
23 parser.add_option("", "--cpu", help=_("target CPU type"), metavar='CPU')
24 parser.add_option("", "--message", help=_("message to display when interacting with user"))
25 parser.add_option("", "--not-before", help=_("minimum version to choose"), metavar='VERSION')
26 parser.add_option("-o", "--offline", help=_("try to avoid using the network"), action='store_true')
27 parser.add_option("", "--os", help=_("target operation system type"), metavar='OS')
28 parser.add_option("-r", "--refresh", help=_("refresh all used interfaces"), action='store_true')
29 parser.add_option("-s", "--source", help=_("select source code"), action='store_true')
31 def add_options(parser):
32 """Options for 'select' and 'download' (but not 'run')"""
33 add_generic_select_options(parser)
34 parser.add_option("", "--xml", help=_("write selected versions as XML"), action='store_true')
36 def get_selections(options, iface_uri, select_only, download_only, test_callback):
37 """Get selections for iface_uri, according to the options passed.
38 Will switch to GUI mode if necessary.
39 @param options: options from OptionParser
40 @param iface_uri: canonical URI of the interface
41 @param select_only: return immediately even if the selected versions aren't cached
42 @param download_only: wait for stale feeds, and display GUI button as Download, not Run
43 @return: the selected versions, or None if the user cancels
44 @rtype: L{selections.Selections} | None
45 """
46 root_iface = iface_cache.get_interface(iface_uri)
48 if os.isatty(1):
49 h = handler.ConsoleHandler()
50 else:
51 h = handler.Handler()
52 h.dry_run = bool(options.dry_run)
54 command_name = options.command
55 if command_name is None:
56 command_name = 'run'
57 elif command_name == '':
58 command_name = None
59 policy = autopolicy.AutoPolicy(iface_uri,
60 handler = h,
61 download_only = True, # unused?
62 src = options.source,
63 command = command_name)
65 if options.before or options.not_before:
66 policy.solver.extra_restrictions[root_iface] = [
67 model.VersionRangeRestriction(model.parse_version(options.before),
68 model.parse_version(options.not_before))]
70 if options.os or options.cpu:
71 from zeroinstall.injector import arch
72 policy.target_arch = arch.get_architecture(options.os, options.cpu)
74 if options.offline:
75 policy.network_use = model.network_offline
77 # Note that need_download() triggers a solve
78 if options.refresh or options.gui:
79 # We could run immediately, but the user asked us not to
80 can_run_immediately = False
81 else:
82 if select_only:
83 # --select-only: we only care that we've made a selection, not that we've cached the implementations
84 policy.need_download()
85 can_run_immediately = policy.ready
86 else:
87 can_run_immediately = not policy.need_download()
89 stale_feeds = [feed for feed in policy.solver.feeds_used if
90 not feed.startswith('distribution:') and # Ignore (memory-only) PackageKit feeds
91 policy.is_stale(iface_cache.get_feed(feed))]
93 if download_only and stale_feeds:
94 can_run_immediately = False
96 if can_run_immediately:
97 if stale_feeds:
98 if policy.network_use == model.network_offline:
99 logging.debug(_("No doing background update because we are in off-line mode."))
100 else:
101 # There are feeds we should update, but we can run without them.
102 # Do the update in the background while the program is running.
103 from zeroinstall.injector import background
104 background.spawn_background_update(policy, options.verbose > 0)
105 return policy.solver.selections
107 # If the user didn't say whether to use the GUI, choose for them.
108 if options.gui is None and os.environ.get('DISPLAY', None):
109 options.gui = True
110 # If we need to download anything, we might as well
111 # refresh all the feeds first.
112 options.refresh = True
113 logging.info(_("Switching to GUI mode... (use --console to disable)"))
115 if options.gui:
116 gui_args = []
117 if download_only:
118 # Just changes the button's label
119 gui_args.append('--download-only')
120 if options.refresh:
121 gui_args.append('--refresh')
122 if options.not_before:
123 gui_args.insert(0, options.not_before)
124 gui_args.insert(0, '--not-before')
125 if options.before:
126 gui_args.insert(0, options.before)
127 gui_args.insert(0, '--before')
128 if options.source:
129 gui_args.insert(0, '--source')
130 if options.message:
131 gui_args.insert(0, options.message)
132 gui_args.insert(0, '--message')
133 if options.verbose:
134 gui_args.insert(0, '--verbose')
135 if options.verbose > 1:
136 gui_args.insert(0, '--verbose')
137 if options.cpu:
138 gui_args.insert(0, options.cpu)
139 gui_args.insert(0, '--cpu')
140 if options.os:
141 gui_args.insert(0, options.os)
142 gui_args.insert(0, '--os')
143 if options.with_store:
144 for x in options.with_store:
145 gui_args += ['--with-store', x]
146 if select_only:
147 gui_args.append('--select-only')
148 if command_name is not None:
149 gui_args.append('--command')
150 gui_args.append(command_name)
152 from zeroinstall import helpers
153 sels = helpers.get_selections_gui(iface_uri, gui_args, test_callback)
155 if not sels:
156 return None # Aborted
157 else:
158 # Note: --download-only also makes us stop and download stale feeds first.
159 downloaded = policy.solve_and_download_impls(refresh = options.refresh or download_only or False,
160 select_only = select_only)
161 if downloaded:
162 policy.handler.wait_for_blocker(downloaded)
163 sels = selections.Selections(policy)
165 return sels
167 def handle(options, args):
168 if len(args) != 1:
169 raise UsageError()
170 iface_uri = model.canonical_iface_uri(args[0])
172 sels = get_selections(options, iface_uri,
173 select_only = True, download_only = False, test_callback = None)
174 if not sels:
175 sys.exit(1) # Aborted by user
177 if options.xml:
178 show_xml(sels)
179 else:
180 show_human(sels)
182 def show_xml(sels):
183 doc = sels.toDOM()
184 doc.writexml(sys.stdout)
185 sys.stdout.write('\n')
187 def show_human(sels):
188 from zeroinstall import zerostore
189 done = set() # detect cycles
190 def print_node(uri, command, indent):
191 if uri in done: return
192 done.add(uri)
193 impl = sels.selections.get(uri, None)
194 print indent + "- URI:", uri
195 if impl:
196 print indent + " Version:", impl.version
197 try:
198 if impl.id.startswith('package:'):
199 path = "(" + impl.id + ")"
200 else:
201 path = impl.local_path or iface_cache.stores.lookup_any(impl.digests)
202 except zerostore.NotStored:
203 path = "(not cached)"
204 print indent + " Path:", path
205 indent += " "
206 deps = impl.dependencies
207 if command is not None:
208 deps += sels.commands[command].requires
209 for child in deps:
210 if isinstance(child, model.InterfaceDependency):
211 if child.qdom.name == 'runner':
212 child_command = command + 1
213 else:
214 child_command = None
215 print_node(child.interface, child_command, indent)
216 else:
217 print indent + " No selected version"
220 if sels.commands:
221 print_node(sels.interface, 0, "")
222 else:
223 print_node(sels.interface, None, "")