1 import sys, os, subprocess
2 import configparser, itertools, json, re
3 import email.mime.text, email.utils, smtplib
6 def __getattr__(self, name):
7 def call(*args, capture_stderr = False, check = True):
8 '''If <capture_stderr>, return stderr merged with stdout. Otherwise, return stdout and forward stderr to our own.
9 If <check> is true, throw an exception of the process fails with non-zero exit code. Otherwise, do not.
10 In any case, return a pair of the captured output and the exit code.'''
11 cmd = ["git", name.replace('_', '-')] + list(args)
12 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if capture_stderr else None) as p:
13 (stdout, stderr) = p.communicate()
17 raise Exception("Error running {0}: Non-zero exit code".format(cmd))
18 return (stdout.decode('utf-8').strip('\n'), code)
24 def git_is_forced_update(oldsha, newsha):
25 out, code = git.merge_base("--is-ancestor", oldsha, newsha, check = False) # "Check if the first <commit> is an ancestor of the second <commit>"
28 return False if code == 0 else True # if oldsha is an ancestor of newsha, then this was a "good" (non-forced) update
30 def read_config(fname, defSection = 'DEFAULT'):
31 '''Reads a config file that may have options outside of any section.'''
32 config = configparser.ConfigParser()
33 with open(fname) as file:
34 stream = itertools.chain(("["+defSection+"]\n",), file)
35 config.read_file(stream)
38 def send_mail(subject, text, receivers, sender='post+webhook@ralfj.de', replyTo=None):
39 assert isinstance(receivers, list)
40 if not len(receivers): return # nothing to do
42 msg = email.mime.text.MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')
43 msg['Subject'] = subject
44 msg['Date'] = email.utils.formatdate(localtime=True)
46 msg['To'] = ', '.join(receivers)
47 if replyTo is not None:
48 msg['Reply-To'] = replyTo
49 # put into envelope and send
50 s = smtplib.SMTP('localhost')
51 s.sendmail(sender, receivers, msg.as_string())
54 def get_github_payload():
55 '''Reeturn the github-style JSON encoded payload (as if we were called as a github webhook)'''
57 data = sys.stdin.buffer.read()
58 data = json.loads(data.decode('utf-8'))
61 return {} # nothing read
64 def __init__(self, name, conf):
65 '''Creates a repository from a section of the git-mirror configuration file'''
67 self.local = conf['local']
68 self.owner = conf['owner'] # email address to notify in case of problems
69 self.mirrors = {} # maps mirrors to their URLs
70 mirror_prefix = 'mirror-'
71 for name in filter(lambda s: s.startswith(mirror_prefix), conf.keys()):
72 mirror = name[len(mirror_prefix):]
73 self.mirrors[mirror] = conf[name]
75 def mail_owner(self, msg):
76 send_mail("git-mirror {0}".format(self.name), msg, [self.owner])
78 def find_mirror_by_url(self, match_urls):
79 for mirror, url in self.mirrors.items():
84 def update_mirrors(self, ref, oldsha, newsha, except_mirrors = [], suppress_stderr = False):
85 '''Update the <ref> from <oldsha> to <newsha> on all mirrors. The update must already have happened locally.'''
86 assert len(oldsha) == 40 and len(newsha) == 40, "These are not valid SHAs."
88 # check for a forced update
89 is_forced = newsha != git_nullsha and oldsha != git_nullsha and git_is_forced_update(oldsha, newsha)
90 # tell all the mirrors
91 for mirror in self.mirrors:
92 if mirror in except_mirrors:
96 # forcibly update ref remotely (someone already did a force push and hence accepted data loss)
97 git.push('--force', self.mirrors[mirror], newsha+":"+ref, capture_stderr = suppress_stderr)
99 # nicely update ref remotely (this avoids data loss due to race conditions)
100 git.push(self.mirrors[mirror], newsha+":"+ref, capture_stderr = suppress_stderr)
102 def update_ref_from_mirror(self, ref, oldsha, newsha, mirror, suppress_stderr = False):
103 '''Update the local version of this <ref> to what's currently on the given <mirror>. <oldsha> and <newsha> are checked. Then update all the other mirrors.'''
105 url = self.mirrors[mirror]
106 # first check whether the remote really is at newsha
107 remote_state, code = git.ls_remote(url, ref)
109 remote_sha = remote_state.split()[0]
111 remote_sha = git_nullsha
112 assert newsha == remote_sha, "Someone lied about the new SHA, which should be {0}.".format(newsha)
113 # locally, we have to be at oldsha or newsha (the latter can happen if we already got this update, e.g. if it originated from us)
114 local_state, code = git.show_ref(ref, check=False)
116 local_sha = local_state.split()[0]
119 raise Exception("Something went wrong getting the local state of {0}.".format(ref))
120 local_sha = git_nullsha
121 assert local_sha in (oldsha, newsha), "Someone lied about the old SHA."
122 # if we are already at newsha locally, we also ran the local hooks, so we do not have to do anything
123 if local_sha == newsha:
125 # update local state from local_sha to newsha.
126 if newsha != git_nullsha:
127 # We *could* now fetch the remote ref and immediately update the local one. However, then we would have to
128 # decide whether we want to allow a force-update or not. Also, the ref could already have changed remotely,
129 # so that may update to some other commit.
130 # Instead, we just fetch without updating any local ref. If the remote side changed in such a way that
131 # <newsha> is not actually fetched, that's a race and will be noticed when updating the local ref.
132 git.fetch(url, ref, capture_stderr = suppress_stderr)
133 # now update the ref, checking the old value is still local_oldsha.
134 git.update_ref(ref, newsha, 40*"0" if local_sha is None else local_sha)
136 # ref does not exist anymore. delete it.
137 assert local_sha != git_nullsha, "Why didn't we bail out earlier if there is nothing to do...?"
138 git.update_ref("-d", ref, local_sha) # this checks that the old value is still local_sha
139 # update all the mirrors
140 self.update_mirrors(ref, oldsha, newsha, [mirror], suppress_stderr)
142 def find_repo_by_directory(repos, dir):
143 for (name, repo) in repos.items():
144 if dir == repo.local:
149 conffile = os.path.join(os.path.dirname(__file__), 'git-mirror.conf')
150 conf = read_config(conffile)
152 for name, section in conf.items():
153 if name != 'DEFAULT':
154 repos[name] = Repo(name, section)