Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / build / android / pylib / flag_changer.py
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import logging
6
7
8 class FlagChanger(object):
9   """Changes the flags Chrome runs with.
10
11   There are two different use cases for this file:
12   * Flags are permanently set by calling Set().
13   * Flags can be temporarily set for a particular set of unit tests.  These
14     tests should call Restore() to revert the flags to their original state
15     once the tests have completed.
16   """
17
18   def __init__(self, adb, cmdline_file):
19     """Initializes the FlagChanger and records the original arguments.
20
21     Args:
22       adb: An instance of AndroidCommands.
23       cmdline_file: Path to the command line file on the device.
24     """
25     self._adb = adb
26     self._cmdline_file = cmdline_file
27
28     # Save the original flags.
29     self._orig_line = self._adb.GetFileContents(self._cmdline_file)
30     if self._orig_line:
31       self._orig_line = self._orig_line[0].strip()
32
33     # Parse out the flags into a list to facilitate adding and removing flags.
34     self._current_flags = self._TokenizeFlags(self._orig_line)
35
36   def Get(self):
37     """Returns list of current flags."""
38     return self._current_flags
39
40   def Set(self, flags):
41     """Replaces all flags on the current command line with the flags given.
42
43     Args:
44       flags: A list of flags to set, eg. ['--single-process'].
45     """
46     if flags:
47       assert flags[0] != 'chrome'
48
49     self._current_flags = flags
50     self._UpdateCommandLineFile()
51
52   def AddFlags(self, flags):
53     """Appends flags to the command line if they aren't already there.
54
55     Args:
56       flags: A list of flags to add on, eg. ['--single-process'].
57     """
58     if flags:
59       assert flags[0] != 'chrome'
60
61     # Avoid appending flags that are already present.
62     for flag in flags:
63       if flag not in self._current_flags:
64         self._current_flags.append(flag)
65     self._UpdateCommandLineFile()
66
67   def RemoveFlags(self, flags):
68     """Removes flags from the command line, if they exist.
69
70     Args:
71       flags: A list of flags to remove, eg. ['--single-process'].  Note that we
72              expect a complete match when removing flags; if you want to remove
73              a switch with a value, you must use the exact string used to add
74              it in the first place.
75     """
76     if flags:
77       assert flags[0] != 'chrome'
78
79     for flag in flags:
80       if flag in self._current_flags:
81         self._current_flags.remove(flag)
82     self._UpdateCommandLineFile()
83
84   def Restore(self):
85     """Restores the flags to their original state."""
86     self._current_flags = self._TokenizeFlags(self._orig_line)
87     self._UpdateCommandLineFile()
88
89   def _UpdateCommandLineFile(self):
90     """Writes out the command line to the file, or removes it if empty."""
91     logging.info('Current flags: %s', self._current_flags)
92     # Root is not required to write to /data/local/tmp/.
93     use_root = '/data/local/tmp/' not in self._cmdline_file
94     if self._current_flags:
95       # The first command line argument doesn't matter as we are not actually
96       # launching the chrome executable using this command line.
97       cmd_line = ' '.join(['_'] + self._current_flags)
98       if use_root:
99         self._adb.SetProtectedFileContents(self._cmdline_file, cmd_line)
100         file_contents = self._adb.GetProtectedFileContents(self._cmdline_file)
101       else:
102         self._adb.SetFileContents(self._cmdline_file, cmd_line)
103         file_contents = self._adb.GetFileContents(self._cmdline_file)
104       assert len(file_contents) == 1 and file_contents[0] == cmd_line, (
105           'Failed to set the command line file at %s' % self._cmdline_file)
106     else:
107       if use_root:
108         self._adb.RunShellCommandWithSU('rm ' + self._cmdline_file)
109       else:
110         self._adb.RunShellCommand('rm ' + self._cmdline_file)
111       assert not self._adb.FileExistsOnDevice(self._cmdline_file), (
112           'Failed to remove the command line file at %s' % self._cmdline_file)
113
114   @staticmethod
115   def _TokenizeFlags(line):
116     """Changes the string containing the command line into a list of flags.
117
118     Follows similar logic to CommandLine.java::tokenizeQuotedArguments:
119     * Flags are split using whitespace, unless the whitespace is within a
120       pair of quotation marks.
121     * Unlike the Java version, we keep the quotation marks around switch
122       values since we need them to re-create the file when new flags are
123       appended.
124
125     Args:
126       line: A string containing the entire command line.  The first token is
127             assumed to be the program name.
128     """
129     if not line:
130       return []
131
132     tokenized_flags = []
133     current_flag = ""
134     within_quotations = False
135
136     # Move through the string character by character and build up each flag
137     # along the way.
138     for c in line.strip():
139       if c is '"':
140         if len(current_flag) > 0 and current_flag[-1] == '\\':
141           # Last char was a backslash; pop it, and treat this " as a literal.
142           current_flag = current_flag[0:-1] + '"'
143         else:
144           within_quotations = not within_quotations
145           current_flag += c
146       elif not within_quotations and (c is ' ' or c is '\t'):
147         if current_flag is not "":
148           tokenized_flags.append(current_flag)
149           current_flag = ""
150       else:
151         current_flag += c
152
153     # Tack on the last flag.
154     if not current_flag:
155       if within_quotations:
156         logging.warn('Unterminated quoted argument: ' + line)
157     else:
158       tokenized_flags.append(current_flag)
159
160     # Return everything but the program name.
161     return tokenized_flags[1:]