1#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import sys
7import subprocess
8
9"""Detect forced pushes (on the client) and prompt the user before going on."""
10
11def read_from_tty():
12  try:
13    import posix  # No way to do this on Windows, just give up there.
14    with open('/dev/tty') as tty_fd:
15      return tty_fd.readline().strip()
16  except:
17    return None
18
19
20def Main():
21  # Allow force pushes in repos forked elsewhere (e.g. googlesource).
22  remote_url = sys.argv[2] if len(sys.argv) >= 2 else ''
23  if 'github.com' not in remote_url:
24    return 0
25
26  parts = sys.stdin.readline().split()
27  if len(parts) < 4:
28    return 0
29  local_ref, local_sha, remote_ref, remote_sha = parts
30  cmd = ['git', 'rev-list', '--count', remote_sha, '--not', local_sha,
31         '--max-count=1']
32
33  is_force_push = '0'
34  try:
35    is_force_push = subprocess.check_output(cmd).strip()
36  except(subprocess.CalledProcessError):
37    return 0
38
39  if is_force_push != '0':
40    sys.stderr.write('\033[31mWARNING: Force pushing will break the ' +
41                     'github.com -> googlesource.com mirroring.\033[0m\n' +
42                     'This is almost certainly a bad idea.\n')
43
44    sys.stderr.write('Type y to continue: ')
45    if read_from_tty() != 'y':
46      return 1
47
48  return 0
49
50
51if __name__ == '__main__':
52  sys.exit(Main())
53