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.
7 import pylib.android_commands
8 import pylib.device.device_utils
11 class FlagChanger(object):
12 """Changes the flags Chrome runs with.
14 There are two different use cases for this file:
15 * Flags are permanently set by calling Set().
16 * Flags can be temporarily set for a particular set of unit tests. These
17 tests should call Restore() to revert the flags to their original state
18 once the tests have completed.
21 def __init__(self, device, cmdline_file):
22 """Initializes the FlagChanger and records the original arguments.
25 device: A DeviceUtils instance.
26 cmdline_file: Path to the command line file on the device.
28 # TODO(jbudorick) Remove once telemetry switches over.
29 if isinstance(device, pylib.android_commands.AndroidCommands):
30 device = pylib.device.device_utils.DeviceUtils(device)
32 self._cmdline_file = cmdline_file
34 # Save the original flags.
35 self._orig_line = self._device.old_interface.GetFileContents(
38 self._orig_line = self._orig_line[0].strip()
40 # Parse out the flags into a list to facilitate adding and removing flags.
41 self._current_flags = self._TokenizeFlags(self._orig_line)
44 """Returns list of current flags."""
45 return self._current_flags
48 """Replaces all flags on the current command line with the flags given.
51 flags: A list of flags to set, eg. ['--single-process'].
54 assert flags[0] != 'chrome'
56 self._current_flags = flags
57 self._UpdateCommandLineFile()
59 def AddFlags(self, flags):
60 """Appends flags to the command line if they aren't already there.
63 flags: A list of flags to add on, eg. ['--single-process'].
66 assert flags[0] != 'chrome'
68 # Avoid appending flags that are already present.
70 if flag not in self._current_flags:
71 self._current_flags.append(flag)
72 self._UpdateCommandLineFile()
74 def RemoveFlags(self, flags):
75 """Removes flags from the command line, if they exist.
78 flags: A list of flags to remove, eg. ['--single-process']. Note that we
79 expect a complete match when removing flags; if you want to remove
80 a switch with a value, you must use the exact string used to add
81 it in the first place.
84 assert flags[0] != 'chrome'
87 if flag in self._current_flags:
88 self._current_flags.remove(flag)
89 self._UpdateCommandLineFile()
92 """Restores the flags to their original state."""
93 self._current_flags = self._TokenizeFlags(self._orig_line)
94 self._UpdateCommandLineFile()
96 def _UpdateCommandLineFile(self):
97 """Writes out the command line to the file, or removes it if empty."""
98 logging.info('Current flags: %s', self._current_flags)
99 # Root is not required to write to /data/local/tmp/.
100 use_root = '/data/local/tmp/' not in self._cmdline_file
101 if self._current_flags:
102 # The first command line argument doesn't matter as we are not actually
103 # launching the chrome executable using this command line.
104 cmd_line = ' '.join(['_'] + self._current_flags)
106 self._device.old_interface.SetProtectedFileContents(
107 self._cmdline_file, cmd_line)
108 file_contents = self._device.old_interface.GetProtectedFileContents(
111 self._device.old_interface.SetFileContents(self._cmdline_file, cmd_line)
112 file_contents = self._device.old_interface.GetFileContents(
114 assert len(file_contents) == 1 and file_contents[0] == cmd_line, (
115 'Failed to set the command line file at %s' % self._cmdline_file)
118 self._device.old_interface.RunShellCommandWithSU(
119 'rm ' + self._cmdline_file)
121 self._device.old_interface.RunShellCommand('rm ' + self._cmdline_file)
123 not self._device.old_interface.FileExistsOnDevice(
124 self._cmdline_file)), (
125 'Failed to remove the command line file at %s' % self._cmdline_file)
128 def _TokenizeFlags(line):
129 """Changes the string containing the command line into a list of flags.
131 Follows similar logic to CommandLine.java::tokenizeQuotedArguments:
132 * Flags are split using whitespace, unless the whitespace is within a
133 pair of quotation marks.
134 * Unlike the Java version, we keep the quotation marks around switch
135 values since we need them to re-create the file when new flags are
139 line: A string containing the entire command line. The first token is
140 assumed to be the program name.
147 within_quotations = False
149 # Move through the string character by character and build up each flag
151 for c in line.strip():
153 if len(current_flag) > 0 and current_flag[-1] == '\\':
154 # Last char was a backslash; pop it, and treat this " as a literal.
155 current_flag = current_flag[0:-1] + '"'
157 within_quotations = not within_quotations
159 elif not within_quotations and (c is ' ' or c is '\t'):
160 if current_flag is not "":
161 tokenized_flags.append(current_flag)
166 # Tack on the last flag.
168 if within_quotations:
169 logging.warn('Unterminated quoted argument: ' + line)
171 tokenized_flags.append(current_flag)
173 # Return everything but the program name.
174 return tokenized_flags[1:]