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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
|
"""
Higher level commands for github pipeline
"""
from __future__ import absolute_import, unicode_literals
import argparse
import io
import logging
import os
import pipes
import random
import shutil
import subprocess
import sys
import tempfile
if True:
if os.path.samefile(sys.path[0], os.path.dirname(__file__)):
sys.path.pop(0)
import github
import keyring
from packaging import version as versiontool
import magic
logger = logging.getLogger(__name__)
PSEUDO_MESSAGE = """
This is a pseudo-release used only to stage artifacts for the release pipeline.
Please do not rely on the artifacts contained in this release as they change
frequently and are very likely to be broken.
""".replace("\n", " ")
def get_access_token():
if "GITHUB_ACCESS_TOKEN" in os.environ:
return os.environ["GITHUB_ACCESS_TOKEN"]
credential = keyring.get_credential("api.github.com", None)
if credential is not None:
return credential.password
raise RuntimeError(
"No github access token found, please set GITHUB_ACCESS_TOKEN "
"environment variable or add username@api.github.com to your "
"system keyring, e.g. run `keyring set api.github.com <username>`")
def create_pseudorelease_tag(reposlug, branch):
# TODO(josh): get title out of the script so that it can be reusable
hub = github.Github(get_access_token())
repo = hub.get_repo(reposlug)
branchobj = repo.get_branch(branch)
logger.info("Creating tag pseudo-%s -> %s", branch, branchobj.commit.sha)
refname = "tags/pseudo-" + branch
try:
existing_ref = repo.get_git_ref(refname)
logger.info("Updating existing ref for %s", refname)
existing_ref.edit(branchobj.commit.sha, force=True)
return
except github.UnknownObjectException:
pass
logger.info("Creating ref %s", refname)
refname = "refs/" + refname
repo.create_git_ref(refname, branchobj.commit.sha)
INITDIRS = [
"branches",
"hooks",
"info",
"objects/info",
"objects/pack",
"refs/heads",
"refs/tags",
]
CONFIGTPL = """
[core]
repositoryformatversion = 0
filemode = true
bare = true
[remote "origin"]
url = {}
fetch = +refs/heads/*:refs/heads/*
"""
MSGTPL = """Sync {commit_name}
This commit was automatically generated by the upstream build.
Upstream-Commit: {upstream_commit}
"""
CHARS = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ012345679"
def make_randstr(strlen=10):
"""Generate a random string."""
return ''.join(random.choice(CHARS) for i in range(strlen))
def init_repository(repodir, repo_url):
"""
Ensure that the specified directory is configured as a git repository.
We create any missing directories and overwrite the config and HEAD files,
putting the repository directory into a known state without blowing away
the object cache.
"""
# Ensure that the standard directories exit
for dirname in INITDIRS:
dirpath = os.path.join(repodir, dirname)
if os.path.lexists(dirpath):
if os.path.islink(dirpath) or not os.path.isdir(dirpath):
os.unlink(dirpath)
else:
continue
os.makedirs(dirpath)
# Write out the config and the HEAD files
outpath = os.path.join(repodir, "config")
with io.open(outpath, "w", encoding="utf-8") as outfile:
outfile.write(CONFIGTPL.format(repo_url))
outpath = os.path.join(repodir, "HEAD")
with io.open(outpath, "w", encoding="utf-8") as outfile:
outfile.write("ref: refs/heads/master")
def canonicalize_trailer_key(keystr):
"""Return canonical capitalization for a trailer key"""
return "-".join(part.capitalize() for part in keystr.split("-"))
def get_trailers(repodir, commit):
"""Return a dictionary of git commit trailers."""
proc = subprocess.Popen([
"git", "show", "--no-patch", '--format="%(trailers:unfold)',
commit], cwd=repodir, stdout=subprocess.PIPE)
out = {}
with proc.stdout as stdout:
for line in stdout:
line = line.strip().decode("utf-8")
if ":" not in line:
continue
key, value = line.split(":", 1)
if ", " in value:
value = value.split(", ")
out[canonicalize_trailer_key(key)] = value
proc.wait()
if proc.returncode != 0:
cmdstr = " ".join(pipes.quote(arg) for arg in proc.args)
raise subprocess.CalledProcessError(proc.returncode, cmdstr)
return out
def ref_exists(repodir, refname):
return subprocess.call(
["git", "show-ref", "--verify", "--quiet", "refs/" + refname],
cwd=repodir) == 0
def sync_doc_artifacts(
docrepo_url, docrepo_dir, scratch_dir, stage_dir, deploy_key_path,
branch=None, tag=None):
current_commit = subprocess.check_output(
["git", "rev-parse", "HEAD"]).strip().decode("utf-8")
env = os.environ.copy()
if deploy_key_path:
env["GIT_SSH_COMMAND"] = "ssh -i {} -F /dev/null".format(deploy_key_path)
# Initialize and fetch the docrepo clone
init_repository(docrepo_dir, docrepo_url)
subprocess.check_call([
"git", "fetch", "--prune", "--tags"], cwd=docrepo_dir, env=env)
# Create a temporary branchname for us to do our work in
workbranch = "work-" + make_randstr(10)
# Clear out scratch tree
if os.path.exists(scratch_dir):
shutil.rmtree(scratch_dir)
os.makedirs(scratch_dir)
if branch:
commit_name = branch
if ref_exists(docrepo_dir, "heads/" + branch):
# If the branch already exists on the remote, then check it out at
# it's current state
subprocess.check_call(
["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
"checkout", "-b", workbranch, branch])
else:
# Otherwise create a new orphan branch for it
subprocess.check_call(
["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
"checkout", "--orphan", workbranch])
elif tag:
commit_name = tag
if ref_exists(docrepo_dir, "tags/" + tag):
# If the tag already exists on the remote then checkout it's parent
subprocess.check_call(
["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
"checkout", "-b", workbranch, "{}^".format(tag)])
else:
# Otherwise checkout the current HEAD of master and just use that.
subprocess.check_call(
["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
"checkout", "-b", workbranch, "master"])
else:
raise ValueError("Both branch and tag are empty")
subprocess.check_call(
["git", "--git-dir=" + docrepo_dir, "--work-tree=" + stage_dir,
"add", "-A"])
result = subprocess.call(
["git", "diff", "--quiet", "--exit-code", "--cached"],
cwd=docrepo_dir)
if result == 0:
# There is nothing to commit, the doc sources have not changed.
return
tfile = tempfile.NamedTemporaryFile(
delete=False, prefix="gitmsg-", mode="w")
with tfile as outfile:
msgpath = outfile.name
outfile.write(MSGTPL.format(
commit_name=commit_name, upstream_commit=current_commit))
subprocess.check_call([
"git", "--git-dir=" + docrepo_dir, "--work-tree=" + stage_dir,
"commit", "--file", msgpath])
os.unlink(msgpath)
if branch:
subprocess.check_call(
["git", "push", "-f", "origin", "{}:{}".format(workbranch, branch)],
cwd=docrepo_dir, env=env)
elif tag:
subprocess.check_call(
["git", "tag", "-f", tag],
cwd=docrepo_dir)
subprocess.check_call(
["git", "push", "-f", "origin", "{0}:{0}".format(tag)],
cwd=docrepo_dir, env=env)
PSEUDO_MESSAGE = """\
This is a pseudo-release used only to stage artifacts for the release pipeline.
Please do not rely on the artifacts contained in this release as they change
frequently and are very likely to be broken.
""".replace("\n", " ")
def push_release(reposlug, tag, message_path, filepaths):
message = ""
if message_path:
with io.open(message_path, encoding="utf-8") as infile:
message = infile.read()
# TODO(josh): get title out of the script so that it can be reusable
prerelease = False
title = reposlug.split("/", 1)[1].replace("_", "-") + " " + tag
if tag.startswith("pseudo-"):
prerelease = True
title = "pseudo-release artifacts for " + tag[len("pseudo-"):]
else:
try:
version = versiontool.parse(tag)
if version.is_devrelease or version.is_prerelease:
prerelease = True
except versiontool.InvalidVersion:
version = None
filenames = set(filepath.rsplit(os.sep, 1)[-1] for filepath in filepaths)
hub = github.Github(get_access_token())
repo = hub.get_repo(reposlug)
try:
release = repo.get_release(tag)
logger.info("Found release for tag %s", tag)
except github.UnknownObjectException:
logger.info("Creating release for tag %s", tag)
try:
release = repo.create_git_release(
tag, title, message, prerelease=prerelease)
except github.UnknownObjectException:
logger.warning("Can't create a release for tag %s", tag)
raise
if release.title != title or release.body != message:
logger.info("Updating release message for: %d", release.id)
release.update_release(title, message, prerelease=prerelease)
for asset in release.get_assets():
if asset.name in filenames:
logger.info("Deleting asset %s", asset.name)
asset.delete_asset()
for filepath in filepaths:
filename = filepath.rsplit(os.sep, 1)[-1]
mime = magic.Magic(mime=True)
release.upload_asset(
filepath, content_type=mime.from_file(filepath), name=filename)
def setup_argparser(argparser):
argparser.add_argument(
"-l", "--log-level", default="info",
choices=["debug", "info", "warning", "error"])
subparsers = argparser.add_subparsers(dest="command")
subparser = subparsers.add_parser(
"create-pseudorelease-tag", help=(
"Create a tag pseudo-<branch> pointing to the current head of "
"<branch> on github."
))
subparser.add_argument("reposlug")
subparser.add_argument("branch")
subparser = subparsers.add_parser(
"sync-doc-artifacts", help=(
"Given the currently checked-out commit within an export repository,"
" create a new commit in the corresponding documentation artifacts"
" repository."
))
subparser.add_argument(
"--doc-repo", dest="docrepo_url",
help="URL of the documentation repository")
subparser.add_argument(
"--repo-dir", dest="docrepo_dir",
help="path to where we should checkout the doc artifacts repo")
subparser.add_argument(
"--scratch-tree", dest="scratch_dir",
help="directory to use as git work-tree for intermediate steps")
subparser.add_argument(
"--stage", dest="stage_dir",
help="directory that contains the new content for the repository")
subparser.add_argument(
"--deploy-key", dest="deploy_key_path", nargs="?",
help="Path to the deploy key for the documentation repository")
mgroup = subparser.add_mutually_exclusive_group(required=True)
mgroup.add_argument(
"--branch",
help="Name of the target branch to push to")
mgroup.add_argument(
"--tag",
help="Name of the target tag to push to")
subparser = subparsers.add_parser(
"push-release", help=(
"Create or modify the release for the currently built tag on travis."
))
subparser.add_argument(
"-m", "--message",
help="path to a file containing release notes message")
subparser.add_argument("--repo-slug", required=True)
subparser.add_argument("--tag", help="the tag we are deploying")
subparser.add_argument("files", nargs="*", help="files to upload")
def get_argdict(namespace):
blacklist = tuple()
out = {}
for key, value in vars(namespace).items():
if key.startswith("_"):
continue
if key in blacklist:
continue
out[key] = value
return out
def main():
logging.basicConfig(level=logging.INFO)
argparser = argparse.ArgumentParser(description=__doc__)
setup_argparser(argparser)
try:
import argcomplete
argcomplete.autocomplete(argparser)
except ImportError:
pass
args = argparser.parse_args()
logging.getLogger().setLevel(getattr(logging, args.log_level.upper()))
if hasattr(args, "tag"):
tagstr = getattr(args, "tag")
travis_tag = os.environ.get("TRAVIS_TAG", tagstr)
if travis_tag != tagstr:
# If this is a travis incremental build, then stage artifacts under the
# pseudo-release instead of creating a new release for the tag.
if travis_tag.startswith("pseudo-"):
setattr(args, "tag", travis_tag)
else:
logger.error(
"Cowardly refusing to to create a github release '%s' from a travis"
"build of tag '%s'", tagstr, os.environ["TRAVIS_TAG"])
sys.exit(1)
argdict = get_argdict(args)
command = argdict.pop("command")
argdict.pop("log_level")
if command == "create-pseudorelease-tag":
create_pseudorelease_tag(args.reposlug, args.branch)
elif command == "sync-doc-artifacts":
tag = argdict.pop("tag")
if tag.startswith("pseudo-"):
argdict["branch"] = tag[len("pseudo-"):]
else:
argdict["tag"] = tag
sync_doc_artifacts(**argdict)
elif command == "push-release":
push_release(args.repo_slug, args.tag, args.message, args.files)
else:
logger.error("Unknown command %s", command)
sys.exit(1)
if __name__ == "__main__":
main()
|