-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathpj_env.py
executable file
·72 lines (66 loc) · 1.95 KB
/
pj_env.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python3
# Script to facilitate executing Prow utilities that require information about
# a pull request. Sets the following variables based on its arguments:
#
# - BASE_REF
# - BASE_SHA
# - PULL_NUMBER
# - PULL_SHA
# - PULL_AUTHOR
#
# and can be used for a single execution:
#
# $ ./pj_env.py openshift/release master 31415 'Pull Author' some_script.sh
#
# or sourced by the shell:
#
# $ . <(./pj_env.py openshift/release master 31415 'Pull Author')
# $ some_script.sh
# $ some_script.sh
# $ some_script.sh
import os
import shlex
import subprocess
import sys
def main():
if len(sys.argv) < 4:
print(
'Usage: repo base_ref pull_number author [cmd...]',
file=sys.stderr)
sys.exit(1)
repo, base_ref, pull_number, pull_author, *cmd = sys.argv[1:]
refs = get_refs(repo, base_ref, pull_number)
if refs is None:
sys.exit(1)
base_sha, pull_sha = refs
var = {
'BASE_REF': base_ref,
'BASE_SHA': base_sha,
'PULL_NUMBER': pull_number,
'PULL_SHA': pull_sha,
'PULL_AUTHOR': pull_author}
if not cmd:
for k, v in var.items():
print(f'export {k}={shlex.quote(v)}')
else:
os.environ.update(var)
sys.exit(subprocess.call(cmd))
def get_refs(repo, base_ref, pull_number):
base_ref = f'refs/heads/{base_ref}'
pull_number = f'refs/pull/{pull_number}/head'
out = subprocess.check_output((
'git', 'ls-remote',
'https://github.com/' + repo,
base_ref, pull_number))
refs = dict(x.split('\t')[::-1] for x in out.decode('utf-8').splitlines())
base_sha = refs.get(base_ref)
pull_sha = refs.get(pull_number)
if base_sha is None:
print(f'Base ref {base_ref} not found', file=sys.stderr)
return None
if pull_sha is None:
print(f'Pull request {pull_number} not found', file=sys.stderr)
return None
return base_sha, pull_sha
if __name__ == '__main__':
main()