Update year to 2009 in various places
[zeroinstall/zeroinstall-rsl.git] / zeroinstall / alias.py
blob3136811b50d7a445b5e3753c729feec9cf9e3d5c
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 _template = '''#!/bin/sh
10 if [ "$*" = "--versions" ]; then
11 exec 0launch -gd '%s' "$@"
12 else
13 exec 0launch %s '%s' "$@"
15 '''
17 class NotAnAliasScript(Exception):
18 pass
20 def parse_script(pathname):
21 """Extract the URI and main values from a 0alias script.
22 @param pathname: the script to be examined
23 @return: a tuple containing the URI and the main (or None if not set)
24 @rtype: (str, str | None)
25 @raise NotAnAliasScript: if we can't parse the script
26 """
27 stream = file(pathname)
28 template_header = _template[:_template.index("-gd '")]
29 actual_header = stream.read(len(template_header))
30 if template_header != actual_header:
31 raise NotAnAliasScript("'%s' does not look like a script created by 0alias" % pathname)
32 rest = stream.read() # If it's a 0alias script, it should be quite short!
33 line = rest.split('\n')[2]
34 split = line.rfind("' '")
35 if split != -1:
36 # We have a --main
37 uri = line[split + 3:].split("'")[0]
38 main = line[:split].split("'", 1)[1].replace("'\\''", "'")
39 else:
40 main = None
41 uri = line.split("'",2)[1]
43 return (uri, main)
45 def write_script(stream, interface_uri, main = None):
46 """Write a shell script to stream that will launch the given program.
47 @param stream: the stream to write to
48 @param interface_uri: the program to launch
49 @param main: the --main argument to pass to 0launch, if any"""
50 assert "'" not in interface_uri
51 assert "\\" not in interface_uri
53 if main is not None:
54 main_arg = "--main '%s'" % main.replace("'", "'\\''")
55 else:
56 main_arg = ""
58 stream.write(_template % (interface_uri, main_arg, interface_uri))