Removed extra space from alias scripts
[zeroinstall.git] / zeroinstall / alias.py
blobf46b59c1f6d58a2387ef202110a9830f1a29437d
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 _old_template = '''#!/bin/sh
12 if [ "$*" = "--versions" ]; then
13 exec 0launch -gd '%s' "$@"
14 else
15 exec 0launch %s '%s' "$@"
17 '''
19 _template = '''#!/bin/sh
20 exec 0launch %s'%s' "$@"
21 '''
23 class NotAnAliasScript(Exception):
24 pass
26 def parse_script(pathname):
27 """Extract the URI and main values from a 0alias script.
28 @param pathname: the script to be examined
29 @return: a tuple containing the URI and the main (or None if not set)
30 @rtype: (str, str | None)
31 @raise NotAnAliasScript: if we can't parse the script
32 """
33 stream = file(pathname)
34 template_header = _template[:_template.index("%s'")]
35 actual_header = stream.read(len(template_header))
36 stream.seek(0)
37 if template_header == actual_header:
38 # If it's a 0alias script, it should be quite short!
39 rest = stream.read()
40 line = rest.split('\n')[1]
41 else:
42 old_template_header = \
43 _old_template[:_old_template.index("-gd '")]
44 actual_header = stream.read(len(old_template_header))
45 if old_template_header != actual_header:
46 raise NotAnAliasScript(_("'%s' does not look like a script created by 0alias") % pathname)
47 rest = stream.read()
48 line = rest.split('\n')[2]
50 split = line.rfind("' '")
51 if split != -1:
52 # We have a --main
53 uri = line[split + 3:].split("'")[0]
54 main = line[:split].split("'", 1)[1].replace("'\\''", "'")
55 else:
56 main = None
57 uri = line.split("'",2)[1]
59 return (uri, main)
61 def write_script(stream, interface_uri, main = None):
62 """Write a shell script to stream that will launch the given program.
63 @param stream: the stream to write to
64 @param interface_uri: the program to launch
65 @param main: the --main argument to pass to 0launch, if any"""
66 assert "'" not in interface_uri
67 assert "\\" not in interface_uri
69 if main is not None:
70 main_arg = "--main '%s' " % main.replace("'", "'\\''")
71 else:
72 main_arg = ""
74 stream.write(_template % (main_arg, interface_uri))