Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / build / android / pylib / flag_changer.py
blob9731fcd9c3bb7a03f7f0dd1912e57fff5c462997
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.
5 import logging
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.
21 """
23 def __init__(self, device, cmdline_file):
24 """Initializes the FlagChanger and records the original arguments.
26 Args:
27 device: A DeviceUtils instance.
28 cmdline_file: Path to the command line file on the device.
29 """
30 # TODO(jbudorick) Remove once telemetry switches over.
31 assert not isinstance(device, pylib.android_commands.AndroidCommands)
32 self._device = device
33 self._cmdline_file = cmdline_file
35 # Save the original flags.
36 try:
37 self._orig_line = self._device.ReadFile(self._cmdline_file).strip()
38 except device_errors.CommandFailedError:
39 self._orig_line = ''
41 # Parse out the flags into a list to facilitate adding and removing flags.
42 self._current_flags = self._TokenizeFlags(self._orig_line)
44 def Get(self):
45 """Returns list of current flags."""
46 return self._current_flags
48 def Set(self, flags):
49 """Replaces all flags on the current command line with the flags given.
51 Args:
52 flags: A list of flags to set, eg. ['--single-process'].
53 """
54 if flags:
55 assert flags[0] != 'chrome'
57 self._current_flags = flags
58 self._UpdateCommandLineFile()
60 def AddFlags(self, flags):
61 """Appends flags to the command line if they aren't already there.
63 Args:
64 flags: A list of flags to add on, eg. ['--single-process'].
65 """
66 if flags:
67 assert flags[0] != 'chrome'
69 # Avoid appending flags that are already present.
70 for flag in flags:
71 if flag not in self._current_flags:
72 self._current_flags.append(flag)
73 self._UpdateCommandLineFile()
75 def RemoveFlags(self, flags):
76 """Removes flags from the command line, if they exist.
78 Args:
79 flags: A list of flags to remove, eg. ['--single-process']. Note that we
80 expect a complete match when removing flags; if you want to remove
81 a switch with a value, you must use the exact string used to add
82 it in the first place.
83 """
84 if flags:
85 assert flags[0] != 'chrome'
87 for flag in flags:
88 if flag in self._current_flags:
89 self._current_flags.remove(flag)
90 self._UpdateCommandLineFile()
92 def Restore(self):
93 """Restores the flags to their original state."""
94 self._current_flags = self._TokenizeFlags(self._orig_line)
95 self._UpdateCommandLineFile()
97 def _UpdateCommandLineFile(self):
98 """Writes out the command line to the file, or removes it if empty."""
99 logging.info('Current flags: %s', self._current_flags)
100 # Root is not required to write to /data/local/tmp/.
101 use_root = '/data/local/tmp/' not in self._cmdline_file
102 if self._current_flags:
103 # The first command line argument doesn't matter as we are not actually
104 # launching the chrome executable using this command line.
105 cmd_line = ' '.join(['_'] + self._current_flags)
106 self._device.WriteFile(
107 self._cmdline_file, cmd_line, as_root=use_root)
108 file_contents = self._device.ReadFile(
109 self._cmdline_file, as_root=use_root).rstrip()
110 assert file_contents == cmd_line, (
111 'Failed to set the command line file at %s' % self._cmdline_file)
112 else:
113 self._device.RunShellCommand('rm ' + self._cmdline_file,
114 as_root=use_root)
115 assert not self._device.FileExists(self._cmdline_file), (
116 'Failed to remove the command line file at %s' % self._cmdline_file)
118 @staticmethod
119 def _TokenizeFlags(line):
120 """Changes the string containing the command line into a list of flags.
122 Follows similar logic to CommandLine.java::tokenizeQuotedArguments:
123 * Flags are split using whitespace, unless the whitespace is within a
124 pair of quotation marks.
125 * Unlike the Java version, we keep the quotation marks around switch
126 values since we need them to re-create the file when new flags are
127 appended.
129 Args:
130 line: A string containing the entire command line. The first token is
131 assumed to be the program name.
133 if not line:
134 return []
136 tokenized_flags = []
137 current_flag = ""
138 within_quotations = False
140 # Move through the string character by character and build up each flag
141 # along the way.
142 for c in line.strip():
143 if c is '"':
144 if len(current_flag) > 0 and current_flag[-1] == '\\':
145 # Last char was a backslash; pop it, and treat this " as a literal.
146 current_flag = current_flag[0:-1] + '"'
147 else:
148 within_quotations = not within_quotations
149 current_flag += c
150 elif not within_quotations and (c is ' ' or c is '\t'):
151 if current_flag is not "":
152 tokenized_flags.append(current_flag)
153 current_flag = ""
154 else:
155 current_flag += c
157 # Tack on the last flag.
158 if not current_flag:
159 if within_quotations:
160 logging.warn('Unterminated quoted argument: ' + line)
161 else:
162 tokenized_flags.append(current_flag)
164 # Return everything but the program name.
165 return tokenized_flags[1:]