Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / native_client / pnacl / driver / shelltools.py
1 #!/usr/bin/python
2 # Copyright (c) 2012 The Native Client Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 from driver_log import Log
7
8 import types
9
10 ######################################################################
11 #
12 # Shell Utilities
13 #
14 ######################################################################
15
16 class shell(object):
17
18   @staticmethod
19   def unescape(s):
20     w = shell.split(s)
21     if len(w) == 0:
22       return ''
23     if len(w) == 1:
24       return w[0]
25     # String was not properly escaped in the first place?
26     assert(False)
27
28   # TODO(pdox): Simplify this function by moving more of it into unescape
29   @staticmethod
30   def split(s):
31     """Split a shell-style string up into a list of distinct arguments.
32     For example: split('cmd -arg1 -arg2="a b c"')
33     Returns ['cmd', '-arg1', '-arg2=a b c']
34     """
35     assert(isinstance(s, types.StringTypes))
36     out = []
37     inspace = True
38     inquote = False
39     buf = ''
40
41     i = 0
42     while i < len(s):
43       if s[i] == '"':
44         inspace = False
45         inquote = not inquote
46       elif s[i] == ' ' and not inquote:
47         if not inspace:
48           out.append(buf)
49           buf = ''
50         inspace = True
51       elif s[i] == '\\':
52         if not i+1 < len(s):
53           Log.Fatal('Unterminated \\ escape sequence')
54         inspace = False
55         i += 1
56         buf += s[i]
57       else:
58         inspace = False
59         buf += s[i]
60       i += 1
61     if inquote:
62       Log.Fatal('Unterminated quote')
63     if not inspace:
64       out.append(buf)
65     return out
66
67   @staticmethod
68   def join(args):
69     """Turn a list into a shell-style string For example:
70        shell.join([ 'a', 'b', 'c d e' ]) = 'a b "c d e"'
71     """
72     return ' '.join([ shell.escape(a) for a in args ])
73
74   @staticmethod
75   def escape(s):
76     """Shell-escape special characters in a string
77        Surround with quotes if necessary
78     """
79     s = s.replace('\\', '\\\\')
80     s = s.replace('"', '\\"')
81     if ' ' in s:
82       s = '"' + s + '"'
83     return s