aboutsummaryrefslogtreecommitdiff
path: root/bootstrap_compiler.py
blob: b00464fc31a5ac40e887ae03634ca389bad11915 (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
#!/usr/bin/python

__author__ = 'shenhan@google.com (Han Shen)'

import optparse
import os
import re
import repo_to_repo
import sys

from utils import command_executer
from utils import logger
from utils import misc

GCC_REPO_PATH='src/third_party/gcc'
CHROMIUMOS_OVERLAY_PATH='src/third_party/chromiumos-overlay'
GCC_EBUILD_PATH='src/third_party/chromiumos-overlay/sys-devel/gcc'

class Bootstrapper(object):
  def __init__(self, chromeos_root, branch=None, gcc_dir=None,
               setup_gcc_ebuild_file_only=False):
    self._chromeos_root = chromeos_root
    self._branch = branch
    self._gcc_dir = gcc_dir
    self._ce = command_executer.GetCommandExecuter()
    self._logger = logger.GetLogger()
    self._gcc_src_dir = None
    self._branch_tree = None
    self._gcc_ebuild_file = None
    self._gcc_ebuild_file_name = None
    self._setup_gcc_ebuild_file_only = setup_gcc_ebuild_file_only

  def SubmitToLocalBranch(self):
    # If "_branch" is set, we just use it.
    if self._branch:
      return True

    # The next few steps creates an internal branch to sync with the gcc dir
    # user provided.
    self._branch = 'internal_testing_branch_no_use'
    chrome_gcc_dir = os.path.join(
      self._chromeos_root, GCC_REPO_PATH)

    # 0. Test to see if git tree is free of local changes.
    if not misc.IsGitTreeClean(chrome_gcc_dir):
      self._logger.LogError(
        'Git repository "{0}" not clean, aborted.'.format(chrome_gcc_dir))
      return False

    # 1. Checkout/create a (new) branch for testing.
    command = 'cd "{0}" && git checkout -B {1} cros/master'.format(
      chrome_gcc_dir, self._branch)
    ret = self._ce.RunCommand(command)
    if ret:
      self._logger.LogError('Failed to create a temp branch for test, aborted.')
      return False

    # 2. Sync sources from user provided gcc dir to chromiumos gcc git.
    local_gcc_repo = repo_to_repo.FileRepo(self._gcc_dir)
    chrome_gcc_repo = repo_to_repo.GitRepo(chrome_gcc_dir, self._branch)
    chrome_gcc_repo._root_dir = chrome_gcc_dir
    # Delete all stuff before start mapping.
    self._ce.RunCommand('cd {0} && rm -rf *'.format(chrome_gcc_dir))
    local_gcc_repo.MapSources(chrome_gcc_repo.GetRoot())

     # 3. Verify sync successfully.
    diff = 'diff -r -x .git -x .svn "{0}" "{1}"'.format(
      self._gcc_dir, chrome_gcc_dir)
    if self._ce.RunCommand(diff):
      self._logger.LogError('Sync not successfully, aborted.')
      return False
    else:
      self._logger.LogOutput('Sync successfully done.')

    # 4. Commit all changes.
    ret = chrome_gcc_repo.CommitLocally(
      'Synced with gcc source tree at - "{0}".'.format(self._gcc_dir))
    if ret:
      self._logger.LogError('Commit to local branch "{0}" failed, aborted.'.
                            format(self._branch))
      return False
    return True

  def CheckoutBranch(self):
    self._gcc_src_dir = os.path.join(self._chromeos_root, GCC_REPO_PATH)
    command = 'cd "{0}" && git checkout {1}'.format(
      self._gcc_src_dir, self._branch)
    if not self._ce.RunCommand(command, print_to_console=True):
      # Get 'TREE' value of this commit
      command = 'cd "{0}" && git cat-file -p {1} ' \
          '| grep -E "^tree [a-f0-9]+$" | cut -d" " -f2'.format(
        self._gcc_src_dir, self._branch)
      ret, stdout, stderr  = self._ce.RunCommand(
        command, return_output=True, print_to_console=False)
      # Pipe operation always has a zero return value. So need to check if
      # stdout is valid.
      if not ret and stdout and \
            re.match('[0-9a-h]{40}', stdout.strip(), re.IGNORECASE):
        self._branch_tree = stdout.strip()
        self._logger.LogOutput('Find tree for branch "{0}" - "{1}"'.format(
            self._branch, self._branch_tree))
        return True
    self._logger.LogError(
      'Failed to checkout "{0}" or failed to get tree value, aborted.'.format(
        self._branch))
    return False

  def FindGccEbuildFile(self):
    # To get the active gcc ebuild file, we need a workable chroot first.
    if not os.path.exists(os.path.join(self._chromeos_root, 'chroot')) and \
          self._ce.RunCommand('cd "{0}" && cros_sdk --create'.format(
        self._chromeos_root)):
      self._logger.LogError(
        ('Failed to instal a initial chroot, aborted.\n'
         'If previous bootstrap failed, do a "cros_sdk --delete" to remove '
         'in-complete chroot.'))
      return False

    rv, stdout, stderr  = self._ce.ChrootRunCommand(self._chromeos_root,
      'equery w sys-devel/gcc', return_output=True, print_to_console=True)
    if rv:
      self._logger.LogError('Failed to execute inside chroot '
                            '"equery w sys-devel/gcc", aborted.')
      return False
    m = re.match('^.*/({0}/(.*\.ebuild))$'.format(GCC_EBUILD_PATH), stdout)
    if not m:
      self._logger.LogError(
        ('Failed to find gcc ebuild file, aborted. '
         'If previous bootstrap failed, do a "cros_sdk --delete" to remove '
         'in-complete chroot.'))
      return False
    self._gcc_ebuild_file = os.path.join(self._chromeos_root, m.group(1))
    self._gcc_ebuild_file_name = m.group(2)
    return True

  def InplaceModifyEbuildFile(self):
    """Using sed to fill properly the values into the following lines -
         CROS_WORKON_COMMIT="..."
         CROS_WORKON_TREE="..."
    """
    command = 'sed -i ' \
        '-e \'s!^CROS_WORKON_COMMIT=".*"$!CROS_WORKON_COMMIT="{0}"!\' ' \
        '-e \'s!^CROS_WORKON_TREE=".*"$!CROS_WORKON_TREE="{1}"!\' {2}'.format(
      self._branch, self._branch_tree, self._gcc_ebuild_file)
    rv = self._ce.RunCommand(command)
    if rv:
      self._logger.LogError(
        'Failed to modify commit and tree value for "{0}"", aborted.'.format(
          self._gcc_ebuild_file))
      return False
    return True

  def DoBootstrapping(self):
    logfile = os.path.join(self._chromeos_root, 'bootstrap.log')
    command = 'cd "{0}" && cros_sdk --delete --bootstrap |& tee "{1}"'. \
        format(self._chromeos_root, logfile)
    rv = self._ce.RunCommand(command, \
                               return_output=False, print_to_console=True)
    if rv:
      self._logger.LogError('Bootstrapping failed, log file - "{0}"\n'.format(
          logfile))
      return False

    self._logger.LogOutput('Bootstrap succeeded.')
    return True

  def Do(self):
    if self.SubmitToLocalBranch() and \
          self.CheckoutBranch() and \
          self.FindGccEbuildFile() and \
          self.InplaceModifyEbuildFile() and \
          (self._setup_gcc_ebuild_file_only or self.DoBootstrapping()):
      ret = True
    else:
      ret = False
    ## Warn that the ebuild file is modified.
    if self._gcc_ebuild_file:
      self._logger.LogWarning(
        ('Gcc ebuild file is (probably) modified, to revert the file - \n'
         'bootstrap_compiler.py --chromeos={0} --reset_gcc_ebuild_file').format(
          self._chromeos_root))

    return ret


def Main(argv):
  parser = optparse.OptionParser()
  parser.add_option('-c', '--chromeos_root', dest='chromeos_root',
                    help=('ChromeOs root dir.'))
  parser.add_option('-b', '--branch', dest='branch',
                    help=('The branch to test against. '
                          'This branch must be a local branch '
                          'inside "src/third_party/gcc". '
                          'Notice, this must not be used with "--gcc".'))
  parser.add_option('-g', '--gcc_dir', dest='gcc_dir',
                    help=('Use a local gcc tree to do bootstrapping. '
                          'Notice, this must not be used with "--branch".'))
  parser.add_option('--fixperm', dest='fixperm',
                    default=False, action='store_true',
                    help=('Fix the (notorious) permission error '
                          'while trying to bootstrap the chroot. '
                          'Note this takes an extra 10-15 minutes '
                          'and is only needed once per chromiumos tree.'))
  parser.add_option('--setup_gcc_ebuild_file_only',
                    dest='setup_gcc_ebuild_file_only',
                    default=False, action='store_true',
                    help=('Setup gcc ebuild file to pick up the '
                          'branch (--branch) or user gcc source (--gcc_dir) '
                          'and exit. Keep chroot as is.'))
  parser.add_option('--reset_gcc_ebuild_file', dest='reset_gcc_ebuild_file',
                    default=False, action='store_true',
                    help=('Reset the modification that is done by this script.'
                          'Note, when this script is running, it will modify '
                          'the active gcc ebuild file. Use this option to '
                          'reset (what this script has done) and exit.'))
  options = parser.parse_args(argv)[0]
  if not options.chromeos_root:
    parser.error('Missing mandatory option "--chromeos".')
    return 1

  options.chromeos_root = os.path.abspath(
    os.path.expanduser(options.chromeos_root))

  if not os.path.isdir(options.chromeos_root):
    logger.GetLogger().LogError(
      '"{0}" does not exist.'.format(options.chromeos_root))
    return 1

  if options.fixperm:
    # Fix perm error before continuing.
    cmd = ('sudo find "{0}" \( -name ".cache" -type d -prune \) -o ' + \
             '\( -name "chroot" -type d -prune \) -o ' + \
             '\( -type f -exec chmod a+r {{}} \; \) -o ' + \
             '\( -type d -exec chmod a+rx {{}} \; \)').format(
      options.chromeos_root)
    logger.GetLogger().LogOutput(
      'Fixing perm issues for chromeos root, this might take some time.')
    command_executer.GetCommandExecuter().RunCommand(cmd)

  if options.reset_gcc_ebuild_file:
    if options.gcc_dir or options.branch:
      logger.GetLogger().LogWarning('Ignoring "--gcc_dir" or "--branch".')
    if options.setup_gcc_ebuild_file_only:
      logger.GetLogger().LogError(
        ('Conflict options "--reset_gcc_ebuild_file" '
         'and "--setup_gcc_ebuild_file_only".'))
      return 1
    # Reset gcc ebuild file and exit.
    rv = misc.GetGitChangesAsList(
      os.path.join(options.chromeos_root,CHROMIUMOS_OVERLAY_PATH),
      path='sys-devel/gcc/gcc-*.ebuild',
      staged=False)
    if rv:
      cmd = 'cd {0} && git checkout --'.format(os.path.join(
          options.chromeos_root, CHROMIUMOS_OVERLAY_PATH))
      for g in rv:
        cmd += ' ' + g
      rv = command_executer.GetCommandExecuter().RunCommand(cmd)
      if rv:
        logger.GetLogger().LogWarning('Failed to reset gcc ebuild file.')
      return rv
    else:
      logger.GetLogger().LogWarning(
        'Did not find any modified gcc ebuild file.')
      return 1

  if options.gcc_dir:
    options.gcc_dir = os.path.abspath(os.path.expanduser(options.gcc_dir))
    if not os.path.isdir(options.gcc_dir):
      logger.GetLogger().LogError(
        '"{0}" does not exist.'.format(options.gcc_dir))
      return 1

  if options.branch and options.gcc_dir:
    parser.error('Only one of "--gcc" and "--branch" can be specified.')
    return 1
  if not (options.branch or options.gcc_dir):
    parser.error('At least one of "--gcc" and "--branch" must be specified.')
    return 1

  if Bootstrapper(
    options.chromeos_root, branch=options.branch, gcc_dir=options.gcc_dir,
    setup_gcc_ebuild_file_only=options.setup_gcc_ebuild_file_only).Do():
    return 0
  return 1


if __name__ == '__main__':
  retval = Main(sys.argv)
  sys.exit(retval)