Added '0install config' sub-command
[zeroinstall.git] / zeroinstall / alias.py
bloba7189abbb393fbb42a2762c83731308d8f661a3b
1 """
2 Support code for 0alias scripts.
3 @since: 0.28
4 """
6 # Copyright (C) 2009, Thomas Leonard
7 # See the README file for details, or visit http://0install.net.
9 from zeroinstall import _
11 _template = '''#!/bin/sh
12 if [ "$*" = "--versions" ]; then
13 exec 0launch -gd '%s' "$@"
14 else
15 exec 0launch %s '%s' "$@"
17 '''
19 class NotAnAliasScript(Exception):
20 pass
22 def parse_script(pathname):
23 """Extract the URI and main values from a 0alias script.
24 @param pathname: the script to be examined
25 @return: a tuple containing the URI and the main (or None if not set)
26 @rtype: (str, str | None)
27 @raise NotAnAliasScript: if we can't parse the script
28 """
29 stream = file(pathname)
30 template_header = _template[:_template.index("-gd '")]
31 actual_header = stream.read(len(template_header))
32 if template_header != actual_header:
33 raise NotAnAliasScript(_("'%s' does not look like a script created by 0alias") % pathname)
34 rest = stream.read() # If it's a 0alias script, it should be quite short!
35 line = rest.split('\n')[2]
36 split = line.rfind("' '")
37 if split != -1:
38 # We have a --main
39 uri = line[split + 3:].split("'")[0]
40 main = line[:split].split("'", 1)[1].replace("'\\''", "'")
41 else:
42 main = None
43 uri = line.split("'",2)[1]
45 return (uri, main)
47 def write_script(stream, interface_uri, main = None):
48 """Write a shell script to stream that will launch the given program.
49 @param stream: the stream to write to
50 @param interface_uri: the program to launch
51 @param main: the --main argument to pass to 0launch, if any"""
52 assert "'" not in interface_uri
53 assert "\\" not in interface_uri
55 if main is not None:
56 main_arg = "--main '%s'" % main.replace("'", "'\\''")
57 else:
58 main_arg = ""
60 stream.write(_template % (interface_uri, main_arg, interface_uri))