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 _
, SafeException
10 from zeroinstall
import support
12 _old_template
= '''#!/bin/sh
13 if [ "$*" = "--versions" ]; then
14 exec 0launch -gd '%s' "$@"
16 exec 0launch %s '%s' "$@"
20 _template
= '''#!/bin/sh
21 exec 0launch %s'%s' "$@"
24 class NotAnAliasScript(SafeException
):
33 # For backwards compatibility
35 return iter([self
.uri
, self
.main
])
37 def parse_script(pathname
):
38 """Extract the URI and main values from a 0alias script.
39 @param pathname: the script to be examined
40 @return: information about the alias script
42 @raise NotAnAliasScript: if we can't parse the script
44 with
open(pathname
, 'rt') as stream
:
45 template_header
= _template
[:_template
.index("%s'")]
46 actual_header
= stream
.read(len(template_header
))
48 if template_header
== actual_header
:
49 # If it's a 0alias script, it should be quite short!
51 line
= rest
.split('\n')[1]
53 old_template_header
= \
54 _old_template
[:_old_template
.index("-gd '")]
55 actual_header
= stream
.read(len(old_template_header
))
56 if old_template_header
!= actual_header
:
57 raise NotAnAliasScript(_("'%s' does not look like a script created by 0alias") % pathname
)
59 line
= rest
.split('\n')[2]
62 split
= line
.rfind("' '")
64 # We have a --main or --command
65 info
.uri
= line
[split
+ 3:].split("'")[0]
66 start
, value
= line
[:split
].split("'", 1)
67 option
= start
.split('--', 1)[1].strip()
68 value
= value
.replace("'\\''", "'")
71 elif option
== 'command':
74 raise NotAnAliasScript("Unknown option '{option}' in alias script".format(option
= option
))
76 info
.uri
= line
.split("'", 2)[1]
80 def write_script(stream
, interface_uri
, main
= None, command
= None):
81 """Write a shell script to stream that will launch the given program.
82 @param stream: the stream to write to
83 @param interface_uri: the program to launch
84 @param main: the --main argument to pass to 0launch, if any
85 @param command: the --command argument to pass to 0launch, if any"""
86 assert "'" not in interface_uri
87 assert "\\" not in interface_uri
88 assert main
is None or command
is None, "Can't set --main and --command together"
91 option
= "--main '%s' " % main
.replace("'", "'\\''")
92 elif command
is not None:
93 option
= "--command '%s' " % command
.replace("'", "'\\''")
97 stream
.write(support
.unicode(_template
) % (option
, interface_uri
))