1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2019 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Updates the status of all tryjobs to the result of `cros buildresult`."""
8
9from __future__ import print_function
10
11import argparse
12import json
13import os
14
15import chroot
16import update_tryjob_status
17
18
19def GetPathToUpdateAllTryjobsWithAutoScript():
20  """Returns the absolute path to this script."""
21
22  return os.path.abspath(__file__)
23
24
25def GetCommandLineArgs():
26  """Parses the command line for the command line arguments."""
27
28  # Default absoute path to the chroot if not specified.
29  cros_root = os.path.expanduser('~')
30  cros_root = os.path.join(cros_root, 'chromiumos')
31
32  # Create parser and add optional command-line arguments.
33  parser = argparse.ArgumentParser(description=__doc__)
34
35  # Add argument for the JSON file to use for the update of a tryjob.
36  parser.add_argument(
37      '--last_tested',
38      required=True,
39      help='The absolute path to the JSON file that contains the tryjobs used '
40      'for bisecting LLVM.')
41
42  # Add argument for a specific chroot path.
43  parser.add_argument(
44      '--chroot_path',
45      default=cros_root,
46      help='the path to the chroot (default: %(default)s)')
47
48  args_output = parser.parse_args()
49
50  if not os.path.isfile(args_output.last_tested) or \
51      not args_output.last_tested.endswith('.json'):
52    raise ValueError('File does not exist or does not ending in ".json" '
53                     ': %s' % args_output.last_tested)
54
55  return args_output
56
57
58def main():
59  """Updates the status of a tryjob."""
60
61  chroot.VerifyOutsideChroot()
62
63  args_output = GetCommandLineArgs()
64
65  with open(args_output.last_tested) as tryjobs:
66    bisect_contents = json.load(tryjobs)
67
68  for tryjob in bisect_contents['jobs']:
69    if tryjob['status'] == update_tryjob_status.TryjobStatus.PENDING.value:
70      tryjob['status'] = update_tryjob_status.GetAutoResult(
71          args_output.chroot_path, tryjob['buildbucket_id'])
72
73  new_file = '%s.new' % args_output.last_tested
74  with open(new_file, 'w') as update_tryjobs:
75    json.dump(bisect_contents, update_tryjobs, indent=4, separators=(',', ': '))
76  os.rename(new_file, args_output.last_tested)
77
78
79if __name__ == '__main__':
80  main()
81