aboutsummaryrefslogtreecommitdiff
path: root/check-git-history.py
blob: fa9d350e534ced7a5e2bd6dfa65919a374c8e540 (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
import os
import sys
import traceback

def main(argv):
  try:
    # Only check the history if the build is running on a pull request.
    if is_travis_pull_request():
      # This function assumes that HEAD^1 is the base branch and HEAD^2 is the
      # pull request.
      exit_if_pull_request_has_merge_commits()
      print 'Checked pull request history.'
    else:
      print 'Skipped history check.'
  except Exception as e:
    # Don't stop the build if this script has a bug.
    traceback.print_exc(e)

def is_travis_pull_request():
  '''Returns true if TRAVIS_PULL_REQUEST is set to indicate a pull request.'''
  return os.environ['TRAVIS_PULL_REQUEST'] != 'false'

def exit_if_pull_request_has_merge_commits():
  '''Exits with an error if any of the commits added by the pull request are
     merge commits.'''
  # Print the parents of each commit added by the pull request.
  git_command = 'git log --format="%P" HEAD^1..HEAD^2'
  for line in os.popen(git_command):
    parents = line.split()
    assert len(parents) >= 1, line
    if len(parents) > 1:
      print 'Pull request contains a merge commit:'
      print_history()
      sys.exit(1)

def print_history():
  os.system('git log HEAD^1 HEAD^2 -30 --graph --oneline --decorate')

def read_process(command):
  '''Runs a command and returns everything printed to stdout.'''
  with os.popen(command, 'r') as fd:
    return fd.read()

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