aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/roll_deps.py
blob: e255099ec03feddcb9e9c0b4b1c6c6150ad9e9e3 (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
290
291
292
293
294
295
296
297
298
#!/usr/bin/python2

# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Skia's Chromium DEPS roll script.

This script:
- searches through the last N Skia git commits to find out the hash that is
  associated with the SVN revision number.
- creates a new branch in the Chromium tree, modifies the DEPS file to
  point at the given Skia commit, commits, uploads to Rietveld, and
  deletes the local copy of the branch.
- creates a whitespace-only commit and uploads that to to Rietveld.
- returns the Chromium tree to its previous state.

To specify the location of the git executable, set the GIT_EXECUTABLE
environment variable.

Usage:
  %prog -c CHROMIUM_PATH -r REVISION [OPTIONAL_OPTIONS]
"""


import optparse
import os
import re
import shutil
import sys
import tempfile

import fix_pythonpath # pylint: disable=W0611
from common.py.utils import git_utils
from common.py.utils import misc
from common.py.utils import shell_utils


DEFAULT_BOTS_LIST = [
  'android_clang_dbg',
  'android_dbg',
  'android_rel',
  'cros_daisy',
  'linux',
  'linux_asan',
  'linux_chromeos',
  'linux_chromeos_asan',
  'linux_chromium_gn_dbg',
  'linux_gpu',
  'linux_layout',
  'linux_layout_rel',
  'mac',
  'mac_asan',
  'mac_gpu',
  'mac_layout',
  'mac_layout_rel',
  'win',
  'win_gpu',
  'win_layout',
  'win_layout_rel',
]

REGEXP_SKIA_REVISION = (
    r'^  "skia_revision": "(?P<revision>[0-9a-fA-F]{2,40})",$')


class DepsRollConfig(object):
  """Contains configuration options for this module.

  Attributes:
      chromium_path: (string) path to a local chromium git repository.
      save_branches: (boolean) iff false, delete temporary branches.
      verbose: (boolean)  iff false, suppress the output from git-cl.
      skip_cl_upload: (boolean)
      cl_bot_list: (list of strings)
  """

  # pylint: disable=I0011,R0903,R0902
  def __init__(self, options=None):
    if not options:
      options = DepsRollConfig.GetOptionParser()
    # pylint: disable=I0011,E1103
    self.verbose = options.verbose
    self.save_branches = not options.delete_branches
    self.chromium_path = options.chromium_path
    self.skip_cl_upload = options.skip_cl_upload
    # Split and remove empty strigns from the bot list.
    self.cl_bot_list = [bot for bot in options.bots.split(',') if bot]
    self.default_branch_name = 'autogenerated_deps_roll_branch'
    self.reviewers_list = ','.join([
        # 'rmistry@google.com',
        # 'reed@google.com',
        # 'bsalomon@google.com',
        # 'robertphillips@google.com',
        ])
    self.cc_list = ','.join([
        # 'skia-team@google.com',
        ])

  @staticmethod
  def GetOptionParser():
    # pylint: disable=I0011,C0103
    """Returns an optparse.OptionParser object.

    Returns:
        An optparse.OptionParser object.

    Called by the main() function.
    """
    option_parser = optparse.OptionParser(usage=__doc__)
    # Anyone using this script on a regular basis should set the
    # CHROMIUM_CHECKOUT_PATH environment variable.
    option_parser.add_option(
        '-c', '--chromium_path', help='Path to local Chromium Git'
        ' repository checkout, defaults to CHROMIUM_CHECKOUT_PATH'
        ' if that environment variable is set.',
        default=os.environ.get('CHROMIUM_CHECKOUT_PATH'))
    option_parser.add_option(
        '-r', '--revision', default=None,
        help='The Skia Git commit hash.')

    option_parser.add_option(
        '', '--delete_branches', help='Delete the temporary branches',
        action='store_true', dest='delete_branches', default=False)
    option_parser.add_option(
        '', '--verbose', help='Do not suppress the output from `git cl`.',
        action='store_true', dest='verbose', default=False)
    option_parser.add_option(
        '', '--skip_cl_upload', help='Skip the cl upload step; useful'
        ' for testing.',
        action='store_true', default=False)

    default_bots_help = (
        'Comma-separated list of bots, defaults to a list of %d bots.'
        '  To skip `git cl try`, set this to an empty string.'
        % len(DEFAULT_BOTS_LIST))
    default_bots = ','.join(DEFAULT_BOTS_LIST)
    option_parser.add_option(
        '', '--bots', help=default_bots_help, default=default_bots)

    return option_parser


class DepsRollError(Exception):
  """Exceptions specific to this module."""
  pass


def change_skia_deps(revision, depspath):
  """Update the DEPS file.

  Modify the skia_revision entry in the given DEPS file.

  Args:
      revision: (string) Skia commit hash.
      depspath: (string) path to DEPS file.
  """
  temp_file = tempfile.NamedTemporaryFile(delete=False,
                                          prefix='skia_DEPS_ROLL_tmp_')
  try:
    deps_regex_rev = re.compile(REGEXP_SKIA_REVISION)
    deps_regex_rev_repl = '  "skia_revision": "%s",' % revision

    with open(depspath, 'r') as input_stream:
      for line in input_stream:
        line = deps_regex_rev.sub(deps_regex_rev_repl, line)
        temp_file.write(line)
  finally:
    temp_file.close()
  shutil.move(temp_file.name, depspath)


def submit_tries(bots_to_run, dry_run=False):
  """Submit try requests for the current branch on the given bots.

  Args:
      bots_to_run: (list of strings) bots to request.
      dry_run: (bool) whether to actually submit the try request.
  """
  git_try = [
      git_utils.GIT, 'cl', 'try', '-m', 'tryserver.chromium']
  git_try.extend([arg for bot in bots_to_run for arg in ('-b', bot)])

  if dry_run:
    space = '   '
    print 'You should call:'
    print space, git_try
    print
  else:
    shell_utils.run(git_try)


def roll_deps(config, revision):
  """Upload changed DEPS and a whitespace change.

  Given the correct git_hash, create two Reitveld issues.

  Args:
      config: (roll_deps.DepsRollConfig) object containing options.
      revision: (string) Skia Git hash.

  Returns:
      a tuple containing textual description of the two issues.

  Raises:
      OSError: failed to execute git or git-cl.
      subprocess.CalledProcessError: git returned unexpected status.
  """
  with misc.ChDir(config.chromium_path, verbose=config.verbose):
    git_utils.Fetch()
    output = shell_utils.run([git_utils.GIT, 'show', 'origin/master:DEPS'],
                             log_in_real_time=False).rstrip()
    match = re.search(REGEXP_SKIA_REVISION, output, flags=re.MULTILINE)
    old_revision = None
    if match:
      old_revision = match.group('revision')
    assert old_revision

    master_hash = git_utils.FullHash('origin/master').rstrip()

    # master_hash[8] gives each whitespace CL a unique name.
    branch = 'control_%s' % master_hash[:8]
    message = ('whitespace change %s\n\n'
               'Chromium base revision: %s\n\n'
               'This CL was created by Skia\'s roll_deps.py script.\n'
               ) % (master_hash[:8], master_hash[:8])
    with git_utils.GitBranch(branch, message,
                             delete_when_finished=not config.save_branches,
                             upload=not config.skip_cl_upload
                             ) as whitespace_branch:
      branch = git_utils.GetCurrentBranch()
      with open(os.path.join('build', 'whitespace_file.txt'), 'a') as f:
        f.write('\nCONTROL\n')

      control_url = whitespace_branch.commit_and_upload()
      if config.cl_bot_list:
        submit_tries(config.cl_bot_list, dry_run=config.skip_cl_upload)
      whitespace_cl = control_url
      if config.save_branches:
        whitespace_cl += '\n    branch: %s' % branch

    branch = 'roll_%s_%s' % (revision, master_hash[:8])
    message = (
        'roll skia DEPS to %s\n\n'
        'Chromium base revision: %s\n'
        'Old Skia revision: %s\n'
        'New Skia revision: %s\n'
        'Control CL: %s\n\n'
        'This CL was created by Skia\'s roll_deps.py script.\n\n'
        'Bypassing commit queue trybots:\n'
        'NOTRY=true\n'
        % (revision, master_hash[:8],
           old_revision[:8], revision[:8], control_url))
    with git_utils.GitBranch(branch, message,
                             delete_when_finished=not config.save_branches,
                             upload=not config.skip_cl_upload
                             ) as roll_branch:
      change_skia_deps(revision, 'DEPS')
      deps_url = roll_branch.commit_and_upload()
      if config.cl_bot_list:
        submit_tries(config.cl_bot_list, dry_run=config.skip_cl_upload)
      deps_cl = deps_url
      if config.save_branches:
        deps_cl += '\n    branch: %s' % branch

    return deps_cl, whitespace_cl


def main(args):
  """main function; see module-level docstring and GetOptionParser help.

  Args:
      args: sys.argv[1:]-type argument list.
  """
  option_parser = DepsRollConfig.GetOptionParser()
  options = option_parser.parse_args(args)[0]

  if not options.revision:
    option_parser.error('Must specify a revision.')
  if not options.chromium_path:
    option_parser.error('Must specify chromium_path.')
  if not os.path.isdir(options.chromium_path):
    option_parser.error('chromium_path must be a directory.')

  config = DepsRollConfig(options)
  shell_utils.VERBOSE = options.verbose
  deps_issue, whitespace_issue = roll_deps(config, options.revision)

  if deps_issue and whitespace_issue:
    print 'DEPS roll:\n    %s\n' % deps_issue
    print 'Whitespace change:\n    %s\n' % whitespace_issue
  else:
    print >> sys.stderr, 'No issues created.'


if __name__ == '__main__':
  main(sys.argv[1:])