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
10 from pylib
.device
import device_errors
13 class FlagChanger(object):
14 """Changes the flags Chrome runs with.
16 There are two different use cases for this file:
17 * Flags are permanently set by calling Set().
18 * Flags can be temporarily set for a particular set of unit tests. These
19 tests should call Restore() to revert the flags to their original state
20 once the tests have completed.
23 def __init__(self
, device
, cmdline_file
):
24 """Initializes the FlagChanger and records the original arguments.
27 device: A DeviceUtils instance.
28 cmdline_file: Path to the command line file on the device.
30 # TODO(jbudorick) Remove once telemetry switches over.
31 if isinstance(device
, pylib
.android_commands
.AndroidCommands
):
32 device
= pylib
.device
.device_utils
.DeviceUtils(device
)
34 self
._cmdline
_file
= cmdline_file
36 # Save the original flags.
38 self
._orig
_line
= self
._device
.ReadFile(self
._cmdline
_file
).strip()
39 except device_errors
.CommandFailedError
:
42 # Parse out the flags into a list to facilitate adding and removing flags.
43 self
._current
_flags
= self
._TokenizeFlags
(self
._orig
_line
)
46 """Returns list of current flags."""
47 return self
._current
_flags
50 """Replaces all flags on the current command line with the flags given.
53 flags: A list of flags to set, eg. ['--single-process'].
56 assert flags
[0] != 'chrome'
58 self
._current
_flags
= flags
59 self
._UpdateCommandLineFile
()
61 def AddFlags(self
, flags
):
62 """Appends flags to the command line if they aren't already there.
65 flags: A list of flags to add on, eg. ['--single-process'].
68 assert flags
[0] != 'chrome'
70 # Avoid appending flags that are already present.
72 if flag
not in self
._current
_flags
:
73 self
._current
_flags
.append(flag
)
74 self
._UpdateCommandLineFile
()
76 def RemoveFlags(self
, flags
):
77 """Removes flags from the command line, if they exist.
80 flags: A list of flags to remove, eg. ['--single-process']. Note that we
81 expect a complete match when removing flags; if you want to remove
82 a switch with a value, you must use the exact string used to add
83 it in the first place.
86 assert flags
[0] != 'chrome'
89 if flag
in self
._current
_flags
:
90 self
._current
_flags
.remove(flag
)
91 self
._UpdateCommandLineFile
()
94 """Restores the flags to their original state."""
95 self
._current
_flags
= self
._TokenizeFlags
(self
._orig
_line
)
96 self
._UpdateCommandLineFile
()
98 def _UpdateCommandLineFile(self
):
99 """Writes out the command line to the file, or removes it if empty."""
100 logging
.info('Current flags: %s', self
._current
_flags
)
101 # Root is not required to write to /data/local/tmp/.
102 use_root
= '/data/local/tmp/' not in self
._cmdline
_file
103 if self
._current
_flags
:
104 # The first command line argument doesn't matter as we are not actually
105 # launching the chrome executable using this command line.
106 cmd_line
= ' '.join(['_'] + self
._current
_flags
)
107 self
._device
.WriteFile(
108 self
._cmdline
_file
, cmd_line
, as_root
=use_root
)
109 file_contents
= self
._device
.ReadFile(
110 self
._cmdline
_file
, as_root
=use_root
).rstrip()
111 assert file_contents
== cmd_line
, (
112 'Failed to set the command line file at %s' % self
._cmdline
_file
)
114 self
._device
.RunShellCommand('rm ' + self
._cmdline
_file
,
116 assert not self
._device
.FileExists(self
._cmdline
_file
), (
117 'Failed to remove the command line file at %s' % self
._cmdline
_file
)
120 def _TokenizeFlags(line
):
121 """Changes the string containing the command line into a list of flags.
123 Follows similar logic to CommandLine.java::tokenizeQuotedArguments:
124 * Flags are split using whitespace, unless the whitespace is within a
125 pair of quotation marks.
126 * Unlike the Java version, we keep the quotation marks around switch
127 values since we need them to re-create the file when new flags are
131 line: A string containing the entire command line. The first token is
132 assumed to be the program name.
139 within_quotations
= False
141 # Move through the string character by character and build up each flag
143 for c
in line
.strip():
145 if len(current_flag
) > 0 and current_flag
[-1] == '\\':
146 # Last char was a backslash; pop it, and treat this " as a literal.
147 current_flag
= current_flag
[0:-1] + '"'
149 within_quotations
= not within_quotations
151 elif not within_quotations
and (c
is ' ' or c
is '\t'):
152 if current_flag
is not "":
153 tokenized_flags
.append(current_flag
)
158 # Tack on the last flag.
160 if within_quotations
:
161 logging
.warn('Unterminated quoted argument: ' + line
)
163 tokenized_flags
.append(current_flag
)
165 # Return everything but the program name.
166 return tokenized_flags
[1:]