2 Support code for 0alias scripts.
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' "$@"
15 exec 0launch %s '%s' "$@"
19 class NotAnAliasScript(Exception):
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
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("' '")
39 uri
= line
[split
+ 3:].split("'")[0]
40 main
= line
[:split
].split("'", 1)[1].replace("'\\''", "'")
43 uri
= line
.split("'",2)[1]
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
56 main_arg
= "--main '%s'" % main
.replace("'", "'\\''")
60 stream
.write(_template
% (interface_uri
, main_arg
, interface_uri
))