/
github_deploy.py
176 lines (147 loc) · 6.31 KB
/
github_deploy.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
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
# -*- coding: utf-8 -*-
# Copyright © 2014-2016 Puneeth Chaganti and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Deploy site to GitHub Pages."""
from __future__ import print_function
from datetime import datetime
import io
import os
import subprocess
from textwrap import dedent
from nikola.plugin_categories import Command
from nikola.plugins.command.check import real_scan_files
from nikola.utils import get_logger, req_missing, makedirs, unicode_str, STDERR_HANDLER
from nikola.__main__ import main
from nikola import __version__
def uni_check_output(*args, **kwargs):
"""Run command and return output as Unicode (UTf-8)."""
o = subprocess.check_output(*args, **kwargs)
return o.decode('utf-8')
def check_ghp_import_installed():
"""Check if ghp-import is installed."""
try:
if os.name == 'nt':
subprocess.check_output([b'ghp-import', b'-h'])
else:
subprocess.check_output(['ghp-import', '-h'])
except OSError:
# req_missing defaults to `python=True` — and it’s meant to be like this.
# `ghp-import` is installed via pip, but the only way to use it is by executing the script it installs.
req_missing(['ghp-import'], 'deploy the site to GitHub Pages')
class CommandGitHubDeploy(Command):
"""Deploy site to GitHub Pages."""
name = 'github_deploy'
doc_usage = '[-m COMMIT_MESSAGE]'
doc_purpose = 'deploy the site to GitHub Pages'
doc_description = dedent(
"""\
This command can be used to deploy your site to GitHub Pages.
It uses ghp-import to do this task.
"""
)
cmd_options = [
{
'name': 'commit_message',
'short': 'm',
'long': 'message',
'default': 'Nikola auto commit.',
'type': str,
'help': 'Commit message (default: Nikola auto commit.)',
},
]
logger = None
def _execute(self, options, args):
"""Run the deployment."""
self.logger = get_logger(CommandGitHubDeploy.name, STDERR_HANDLER)
# Check if ghp-import is installed
check_ghp_import_installed()
# Build before deploying
build = main(['build'])
if build != 0:
self.logger.error('Build failed, not deploying to GitHub')
return build
# Clean non-target files
only_on_output, _ = real_scan_files(self.site)
for f in only_on_output:
os.unlink(f)
# Commit and push
self._commit_and_push(options['commit_message'])
return
def _run_command(self, command, xfail=False):
"""Run a command that may or may not fail."""
self.logger.info("==> {0}".format(command))
if os.name == 'nt':
command = [i.encode('ascii', errors='replace') for i in command]
try:
subprocess.check_call(command)
return 0
except subprocess.CalledProcessError as e:
if xfail:
return e.returncode
self.logger.error(
'Failed GitHub deployment — command {0} '
'returned {1}'.format(e.cmd, e.returncode)
)
raise SystemError(e.returncode)
def _commit_and_push(self, commit_first_line):
"""Commit all the files and push."""
source = self.site.config['GITHUB_SOURCE_BRANCH']
deploy = self.site.config['GITHUB_DEPLOY_BRANCH']
remote = self.site.config['GITHUB_REMOTE_NAME']
autocommit = self.site.config['GITHUB_COMMIT_SOURCE']
try:
if autocommit:
commit_message = (
'{0}\n\n'
'Nikola version: {1}'.format(commit_first_line, __version__)
)
e = self._run_command(['git', 'checkout', source], True)
if e != 0:
self._run_command(['git', 'checkout', '-b', source])
self._run_command(['git', 'add', '.'])
# Figure out if there is anything to commit
e = self._run_command(['git', 'diff-index', '--quiet', 'HEAD'], True)
if e != 0:
self._run_command(['git', 'commit', '-am', commit_message])
else:
self.logger.notice('Nothing to commit to source branch.')
source_commit = uni_check_output(['git', 'rev-parse', source])
commit_message = (
'{0}\n\n'
'Source commit: {1}'
'Nikola version: {2}'.format(commit_first_line, source_commit, __version__)
)
output_folder = self.site.config['OUTPUT_FOLDER']
command = ['ghp-import', '-n', '-m', commit_message, '-p', '-r', remote, '-b', deploy, output_folder]
self._run_command(command)
if autocommit:
self._run_command(['git', 'push', '-u', remote, source])
except SystemError as e:
return e.args[0]
self.logger.info("Successful deployment")
# Store timestamp of successful deployment
timestamp_path = os.path.join(self.site.config["CACHE_FOLDER"], "lastdeploy")
new_deploy = datetime.utcnow()
makedirs(self.site.config["CACHE_FOLDER"])
with io.open(timestamp_path, "w+", encoding="utf8") as outf:
outf.write(unicode_str(new_deploy.isoformat()))