blob: df13e4232861b302f5991ed55bd0ed3436d85afe [file] [log] [blame]
Kristen Kozakc39e0692017-01-28 16:54:37 -08001import os
2import sys
3import traceback
4
5def main(argv):
Kristen Kozaked5e46b2017-03-24 16:38:12 -07006 # Only check the history if the build is running on a pull request.
rghetia9f1a1be2018-05-16 09:45:53 -07007 # Build could be running on pull request using travis or kokoro.
8 if is_travis_pull_request() or is_kokoro_presubmit_request():
Kristen Kozaked5e46b2017-03-24 16:38:12 -07009 # 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()
Kristen Kozak39b5dee2017-03-24 17:17:35 -070012 print 'Checked pull request history: SUCCEEDED'
Kristen Kozaked5e46b2017-03-24 16:38:12 -070013 else:
14 print 'Skipped history check.'
Kristen Kozakc39e0692017-01-28 16:54:37 -080015
rghetia9f1a1be2018-05-16 09:45:53 -070016def 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
Kristen Kozak952ddd82017-03-22 18:00:36 -070022def is_travis_pull_request():
23 '''Returns true if TRAVIS_PULL_REQUEST is set to indicate a pull request.'''
rghetia9f1a1be2018-05-16 09:45:53 -070024 if 'TRAVIS_PULL_REQUEST' in os.environ:
25 return os.environ['TRAVIS_PULL_REQUEST'] != 'false'
26 return False
Kristen Kozakc39e0692017-01-28 16:54:37 -080027
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()
Kristen Kozak39b5dee2017-03-24 17:17:35 -070039 print 'Checked pull request history: FAILED'
Kristen Kozakc39e0692017-01-28 16:54:37 -080040 sys.exit(1)
41
Kristen Kozakc39e0692017-01-28 16:54:37 -080042def 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)