• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import os
2import sys
3import traceback
4
5def main(argv):
6  # Only check the history if the build is running on a pull request.
7  # Build could be running on pull request using travis or kokoro.
8  if is_travis_pull_request() or is_kokoro_presubmit_request():
9    # This function assumes that HEAD^1 is the base branch and HEAD^2 is the
10    # pull request.
11    exit_if_pull_request_has_merge_commits()
12    print 'Checked pull request history: SUCCEEDED'
13  else:
14    print 'Skipped history check.'
15
16def is_kokoro_presubmit_request():
17  '''Returns true if KOKORO_GITHUB_PULL_REQUEST_NUMBER is set.'''
18  if 'KOKORO_GITHUB_PULL_REQUEST_NUMBER' in os.environ:
19    return True
20  return False
21
22def is_travis_pull_request():
23  '''Returns true if TRAVIS_PULL_REQUEST is set to indicate a pull request.'''
24  if 'TRAVIS_PULL_REQUEST' in os.environ:
25    return os.environ['TRAVIS_PULL_REQUEST'] != 'false'
26  return False
27
28def exit_if_pull_request_has_merge_commits():
29  '''Exits with an error if any of the commits added by the pull request are
30     merge commits.'''
31  # Print the parents of each commit added by the pull request.
32  git_command = 'git log --format="%P" HEAD^1..HEAD^2'
33  for line in os.popen(git_command):
34    parents = line.split()
35    assert len(parents) >= 1, line
36    if len(parents) > 1:
37      print 'Pull request contains a merge commit:'
38      print_history()
39      print 'Checked pull request history: FAILED'
40      sys.exit(1)
41
42def print_history():
43  os.system('git log HEAD^1 HEAD^2 -30 --graph --oneline --decorate')
44
45def read_process(command):
46  '''Runs a command and returns everything printed to stdout.'''
47  with os.popen(command, 'r') as fd:
48    return fd.read()
49
50if __name__ == '__main__':
51  main(sys.argv)
52