summaryrefslogtreecommitdiffstats
path: root/tools/telemetry/refactor
blob: e8c144bfb474ed279358bace89a84df6c6c9f669 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#! /usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import cStringIO
import imp
import inspect
import os
import re
import sys

from telemetry.core import command_line
from telemetry.util import path


# All folders dependent on Telemetry, found using a code search.
BASE_DIRS = (
  path.GetTelemetryDir(),
  os.path.join(path.GetChromiumSrcDir(), 'chrome', 'test', 'telemetry'),
  os.path.join(path.GetChromiumSrcDir(), 'content', 'test', 'gpu'),
  os.path.join(path.GetChromiumSrcDir(), 'tools', 'bisect-manual-test.py'),
  os.path.join(path.GetChromiumSrcDir(), 'tools', 'chrome_proxy'),
  os.path.join(path.GetChromiumSrcDir(), 'tools', 'perf'),
  os.path.join(path.GetChromiumSrcDir(),
               'tools', 'profile_chrome', 'perf_controller.py'),
  os.path.join(path.GetChromiumSrcDir(), 'tools', 'run-bisect-manual-test.py'),
  os.path.join(path.GetChromiumSrcDir(),
               'third_party', 'skia', 'tools', 'skp', 'page_sets'),
  os.path.join(path.GetChromiumSrcDir(), 'third_party', 'trace-viewer'),
)


def SortImportGroups(module_path):
  """Sort each group of imports in the given Python module.

  A group is a collection of adjacent import statements, with no non-import
  lines in between. Groups are sorted according to the Google Python Style
  Guide: "lexicographically, ignoring case, according to each module's full
  package path."
  """
  _TransformImportGroups(module_path, _SortImportGroup)


def _SortImportGroup(import_group):
  def _ImportComparator(import1, import2):
    _, root1, module1, _, _ = import1
    _, root2, module2, _, _ = import2
    full_module1 = (root1 + '.' + module1 if root1 else module1).lower()
    full_module2 = (root2 + '.' + module2 if root2 else module2).lower()
    return cmp(full_module1, full_module2)
  return sorted(import_group, cmp=_ImportComparator)


def _TransformImportGroups(module_path, transformation):
  """Apply a transformation to each group of imports in the given module.

  An import is a tuple of (indent, root, module, alias, suffix),
  serialized as <indent>from <root> import <module> as <alias><suffix>.

  Args:
    module_path: The module to apply transformations on.
    transformation: A function that takes in an import group and returns a
        modified import group. An import group is a list of import tuples.

  Returns:
    True iff the module was modified, and False otherwise.
  """
  def _WriteImports(output_stream, import_group):
    for indent, root, module, alias, suffix in transformation(import_group):
      output_stream.write(indent)
      if root:
        output_stream.write('from ')
        output_stream.write(root)
        output_stream.write(' ')
      output_stream.write('import ')
      output_stream.write(module)
      if alias:
        output_stream.write(' as ')
        output_stream.write(alias)
      output_stream.write(suffix)
      output_stream.write('\n')

  # Read the file so we can diff it later to determine if we made any changes.
  with open(module_path, 'r') as module_file:
    original_file = module_file.read()

  # Locate imports using regex, group them, and transform each one.
  # This regex produces a tuple of (indent, root, module, alias, suffix).
  regex = (r'(\s*)(?:from ((?:[a-z0-9_]+\.)*[a-z0-9_]+) )?'
      r'import ((?:[a-z0-9_]+\.)*[A-Za-z0-9_]+)(?: as ([A-Za-z0-9_]+))?(.*)')
  pattern = re.compile(regex)

  updated_file = cStringIO.StringIO()
  with open(module_path, 'r') as module_file:
    import_group = []
    for line in module_file:
      import_match = pattern.match(line)
      if import_match:
        import_group.append(list(import_match.groups()))
        continue

      if not import_group:
        updated_file.write(line)
        continue

      _WriteImports(updated_file, import_group)
      import_group = []

      updated_file.write(line)

  if import_group:
    _WriteImports(updated_file, import_group)
    import_group = []

  if original_file == updated_file.getvalue():
    return False

  with open(module_path, 'w') as module_file:
    module_file.write(updated_file.getvalue())
  return True


def _ListFiles(base_directory, should_include_dir, should_include_file):
  matching_files = []
  for root, dirs, files in os.walk(base_directory):
    dirs[:] = [dir_name for dir_name in dirs if should_include_dir(dir_name)]
    matching_files += [os.path.join(root, file_name)
                       for file_name in files if should_include_file(file_name)]
  return sorted(matching_files)


class Count(command_line.Command):
  """Print the number of public modules."""

  def Run(self, args):
    modules = _ListFiles(path.GetTelemetryDir(),
                         self._IsPublicApiDir, self._IsPublicApiFile)
    print len(modules)
    return 0

  @staticmethod
  def _IsPublicApiDir(dir_name):
    return (dir_name[0] != '.' and dir_name[0] != '_' and
        not dir_name.startswith('internal') and not dir_name == 'third_party')

  @staticmethod
  def _IsPublicApiFile(file_name):
    root, ext = os.path.splitext(file_name)
    return (file_name[0] != '.' and
        not root.endswith('_unittest') and ext == '.py')


class Mv(command_line.Command):
  """Move modules or packages."""

  @classmethod
  def AddCommandLineArgs(cls, parser):
    parser.add_argument('source', nargs='+')
    parser.add_argument('destination')

  @classmethod
  def ProcessCommandLineArgs(cls, parser, args):
    for source in args.source:
      # Ensure source path exists.
      if not os.path.exists(source):
        parser.error('"%s" not found.' % source)

      # Ensure source path is in one of the BASE_DIRS.
      for base_dir in BASE_DIRS:
        if path.IsSubpath(source, base_dir):
          break
      else:
        parser.error('Source path "%s" is not in any of the base dirs.')

    # Ensure destination path exists.
    if not os.path.exists(args.destination):
      parser.error('"%s" not found.' % args.destination)

    # Ensure destination path is in one of the BASE_DIRS.
    for base_dir in BASE_DIRS:
      if path.IsSubpath(args.destination, base_dir):
        break
    else:
      parser.error('Destination path "%s" is not in any of the base dirs.')

    # If there are multiple source paths, ensure destination is a directory.
    if len(args.source) > 1 and not os.path.isdir(args.destination):
      parser.error('Target "%s" is not a directory.' % args.destination)

    # Ensure destination is not in any of the source paths.
    for source in args.source:
      if path.IsSubpath(args.destination, source):
        parser.error('Cannot move "%s" to a subdirectory of itself, "%s".' %
            (source, args.destination))

  def Run(self, args):
    for dest_base_dir in BASE_DIRS:
      if path.IsSubpath(args.destination, dest_base_dir):
        break

    # Get a list of old and new module names for renaming imports.
    moved_modules = {}
    for source in args.source:
      for source_base_dir in BASE_DIRS:
        if path.IsSubpath(source, source_base_dir):
          break

      source_dir = os.path.dirname(os.path.normpath(source))

      if os.path.isdir(source):
        source_files = _ListFiles(source,
                                  self._IsSourceDir, self._IsPythonModule)
      else:
        source_files = (source,)

      for source_file_path in source_files:
        source_rel_path = os.path.relpath(source_file_path, source_base_dir)
        source_module_name = os.path.splitext(
            source_rel_path)[0].replace(os.sep, '.')

        source_tree = os.path.relpath(source_file_path, source_dir)
        dest_path = os.path.join(args.destination, source_tree)
        dest_rel_path = os.path.relpath(dest_path, dest_base_dir)
        dest_module_name = os.path.splitext(
            dest_rel_path)[0].replace(os.sep, '.')

        moved_modules[source_module_name] = dest_module_name

    # Move things!
    if os.path.isdir(args.destination):
      for source in args.source:
        destination_path = os.path.join(
            args.destination, os.path.split(os.path.normpath(source))[1])
        os.rename(source, destination_path)
    else:
      assert len(args.source) == 1
      os.rename(args.source.pop(), args.destination)

    # Update imports!
    def _UpdateImportGroup(import_group):
      modified = False
      for import_line in import_group:
        _, root, module, _, _ = import_line
        full_module = root + '.' + module if root else module

        if full_module not in moved_modules:
          continue

        modified = True

        # Update import line.
        new_root, _, new_module = moved_modules[full_module].rpartition('.')
        import_line[1] = new_root
        import_line[2] = new_module

      if modified:
        return _SortImportGroup(import_group)
      else:
        return import_group

    for base_dir in BASE_DIRS:
      for module_path in _ListFiles(base_dir,
                                    self._IsSourceDir, self._IsPythonModule):
        if not _TransformImportGroups(module_path, _UpdateImportGroup):
          continue

        # TODO(dtu): Update occurrences.

    print moved_modules

    return 0

  @staticmethod
  def _IsSourceDir(dir_name):
    return dir_name[0] != '.' and dir_name != 'third_party'

  @staticmethod
  def _IsPythonModule(file_name):
    _, ext = os.path.splitext(file_name)
    return ext == '.py'


class RefactorCommand(command_line.SubcommandCommand):
  commands = (Count, Mv,)


if __name__ == '__main__':
  sys.exit(RefactorCommand.main())