-
Notifications
You must be signed in to change notification settings - Fork 12
/
cupper.py
82 lines (67 loc) · 2.92 KB
/
cupper.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
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import json
import shutil
import subprocess32 as subprocess
import json
from cookiecutter.main import cookiecutter
class TemporaryWorkdir():
"""Context Manager for a temporary working directory of a branch in a git repo"""
def __init__(self, path, repo, branch='master'):
self.repo = repo
self.path = path
self.branch = branch
def __enter__(self):
if not os.path.exists(os.path.join(self.repo, ".git")):
raise Exception("Not a git repository: %s" % self.repo)
if os.path.exists(self.path):
raise Exception("Temporary directory already exists: %s" % self.path)
os.makedirs(self.path)
subprocess.run(["git", "worktree", "add", "--no-checkout", self.path, self.branch],
cwd=self.repo)
def __exit__(self, type, value, traceback):
shutil.rmtree(self.path)
subprocess.run(["git", "worktree", "prune"], cwd=self.repo)
def update_template(context, root, branch, checkout=None):
"""Update template branch from a template url"""
template_url = context['_template']
tmpdir = os.path.join(root, ".git", "cookiecutter")
project_slug = os.path.basename(root)
tmp_workdir = os.path.join(tmpdir, project_slug)
context['project_slug'] = project_slug
# create a template branch if necessary
if subprocess.run(["git", "rev-parse", "-q", "--verify", branch], cwd=root).returncode != 0:
firstref = subprocess.run(["git", "rev-list", "--max-parents=0", "--max-count=1", "HEAD"],
cwd=root,
stdout=subprocess.PIPE,
universal_newlines=True).stdout.strip()
subprocess.run(["git", "branch", branch, firstref])
with TemporaryWorkdir(tmp_workdir, repo=root, branch=branch):
# update the template
cookiecutter(template_url,
checkout=checkout,
no_input=True,
extra_context=context,
overwrite_if_exists=True,
output_dir=tmpdir)
# commit to template branch
subprocess.run(["git", "add", "-A", "."], cwd=tmp_workdir)
subprocess.run(["git", "commit", "-m", "Update template"],
cwd=tmp_workdir)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"context_file",
metavar="context-file",
help="JSON file containing configuration for cookiecutter",
)
parser.add_argument("branch", help="name of the branch to create")
parser.add_argument(
"--checkout", "-c", metavar="REV", help="check out the given template revision"
)
args = parser.parse_args()
with open(args.context_file, 'r') as fd:
context = json.load(fd)
update_template(context, os.getcwd(), branch=args.branch, checkout=args.checkout)