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