-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtasks.py
More file actions
1664 lines (1308 loc) · 59.7 KB
/
tasks.py
File metadata and controls
1664 lines (1308 loc) · 59.7 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import absolute_import, unicode_literals
import codecs
from contextlib import closing
import datetime
import importlib
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
import urllib.request
from invoke import task
from packaging.version import Version, parse as parse_version
RE_CHANGELOG_FILE_HEADER = re.compile(r'^=+$')
RE_CHANGELOG_VERSION_HEADER = re.compile(r'^-+$')
RE_FILE_EXTENSION = re.compile(r'\.\w+$')
RE_VERSION = re.compile(r'^\d+\.\d+\.\d+([a-zA-Z\d.+-]*[a-zA-Z\d]+)?$')
RE_VERSION_BRANCH_MAJOR = re.compile(r'^\d+\.x\.x$')
RE_VERSION_BRANCH_MINOR = re.compile(r'^\d+\.\d+\.x$')
RE_SPLIT_AFTER_DIGITS = re.compile(r'(\d+)')
VERSION_INFO_VARIABLE_TEMPLATE = '__version_info__ = {}'
VERSION_VARIABLE_TEMPLATE = (
"__version__ = '{}'.join(filter(None, ['.'.join(map(str, __version_info__[:3])), "
"(__version_info__[3:] or [None])[0]]))"
)
RELEASE_MESSAGE_TEMPLATE = 'Released [unknown] version {}'
MODULE_NAME = 'unknown'
MODULE_DISPLAY_NAME = '[unknown]'
USE_PULL_REQUEST = False
USE_TAG = True
RELEASE_PLUGINS = []
ROOT_DIRECTORY = ''
VERSION_FILENAME = 'python/unknown/version.py'
VERSION_FILE_IS_TXT = False
CHANGELOG_FILENAME = 'CHANGELOG.txt'
CHANGELOG_COMMENT_FIRST_CHAR = '#'
PARAMETERS_CONFIGURED = False
__POST_APPLY = False
__all__ = [
'configure_release_parameters',
'version',
'branch',
'wheel',
'release',
'rollback_release',
]
_output = sys.stdout
_output_is_tty = _output.isatty()
COLOR_GREEN_BOLD = '32;1'
COLOR_RED_STANDARD = '31'
COLOR_RED_BOLD = '31;1'
COLOR_GRAY_LIGHT = '38;5;242'
COLOR_WHITE = '37;1'
PUSH_RESULT_NO_ACTION = 0
PUSH_RESULT_PUSHED = 1
PUSH_RESULT_ROLLBACK = 2
HEAD_BRANCH = 'HEAD branch: '
INSTRUCTION_NO = 'n'
INSTRUCTION_YES = 'y'
INSTRUCTION_NEW = 'new'
INSTRUCTION_EDIT = 'edit'
INSTRUCTION_ACCEPT = 'accept'
INSTRUCTION_DELETE = 'delete'
INSTRUCTION_EXIT = 'exit'
INSTRUCTION_ROLLBACK = 'rollback'
INSTRUCTION_MAJOR = 'major'
MAJOR_VERSION_PREFIX = '- [MAJOR]'
MINOR_VERSION_PREFIX = '- [MINOR]'
PATCH_VERSION_PREFIX = '- [PATCH]'
class ErrorStreamWrapper(object):
def __init__(self, wrapped):
self.wrapped = wrapped
def write(self, err):
self.wrapped.write('\x1b[{color}m{err}\x1b[0m'.format(color=COLOR_RED_STANDARD, err=err))
def writelines(self, lines):
self.wrapped.write('\x1b[{}m'.format(COLOR_RED_STANDARD))
self.wrapped.writelines(lines)
self.wrapped.write('\x1b[0m')
def __getattribute__(self, item):
try:
return super(ErrorStreamWrapper, self).__getattribute__(item)
except AttributeError:
return self.wrapped.__getattribute__(item)
sys.stderr = ErrorStreamWrapper(sys.stderr)
class ReleaseFailure(Exception):
"""
Exception raised when something caused the release to fail, and cleanup is required.
"""
class ReleaseExit(Exception):
"""
Control-flow exception raised to cancel a release before changes are made.
"""
def _print_output(color, message, *args, **kwargs):
if _output_is_tty:
_output.write(
'\x1b[{color}m{message}\x1b[0m'.format(
color=color,
message=message.format(*args, **kwargs),
),
)
_output.flush()
else:
print(message.format(*args, **kwargs))
def _standard_output(message, *args, **kwargs):
_print_output(COLOR_GREEN_BOLD, message + '\n', *args, **kwargs)
def _prompt(message, *args, **kwargs):
_print_output(COLOR_WHITE, message + ' ', *args, **kwargs)
response = input()
if response:
return response.strip()
return ''
def _error_output(message, *args, **kwargs):
_print_output(COLOR_RED_BOLD, ''.join(('ERROR: ', message, '\n')), *args, **kwargs)
def _error_output_exit(message, *args, **kwargs):
_error_output(message, *args, **kwargs)
sys.exit(1)
def _verbose_output(verbose, message, *args, **kwargs):
if verbose:
_print_output(COLOR_GRAY_LIGHT, ''.join(('DEBUG: ', message, '\n')), *args, **kwargs)
def _case_sensitive_regular_file_exists(filename):
if not os.path.isfile(filename):
# Short circuit
return False
directory, filename = os.path.split(filename)
return filename in os.listdir(directory)
def _get_root_directory():
root_directory = subprocess.check_output(
['git', 'rev-parse', '--show-toplevel'],
stderr=sys.stderr,
).decode('utf8').strip()
if not root_directory:
_error_output_exit('Failed to find Git root directory.')
return root_directory
def _setup_task(no_stash, verbose):
if not no_stash:
global __POST_APPLY
# stash changes before we execute task
_verbose_output(verbose, 'Stashing changes...')
result = subprocess.check_output(
['git', 'stash'],
stderr=sys.stderr,
).decode('utf8')
if result.startswith('Saved'):
__POST_APPLY = True
_verbose_output(verbose, 'Finished stashing changes.')
def _cleanup_task(verbose):
if __POST_APPLY:
_verbose_output(verbose, 'Un-stashing changes...')
subprocess.check_output(
['git', 'stash', 'pop'],
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished un-stashing changes.')
def _write_to_version_file(release_version, version_info, version_separator, verbose):
_verbose_output(verbose, 'Writing version to {}...', VERSION_FILENAME)
if not _case_sensitive_regular_file_exists(VERSION_FILENAME):
raise ReleaseFailure(
'Failed to find version file: {}. File names are case sensitive!'.format(VERSION_FILENAME),
)
if VERSION_FILE_IS_TXT:
with codecs.open(VERSION_FILENAME, 'wb', encoding='utf8') as version_write:
version_write.write(release_version)
else:
with codecs.open(VERSION_FILENAME, 'rb', encoding='utf8') as version_read:
output = []
version_info_written = False
# We replace u' with ' in this, because Py2 projects should use unicode_literals in their version file
version_info = VERSION_INFO_VARIABLE_TEMPLATE.format(tuple(version_info)).replace(", u'", ", '")
for line in version_read:
if line.startswith('__version_info__'):
output.append(version_info)
version_info_written = True
elif line.startswith('__version__'):
if not version_info_written:
output.append(version_info)
output.append(VERSION_VARIABLE_TEMPLATE.format(version_separator))
else:
output.append(line.rstrip())
with codecs.open(VERSION_FILENAME, 'wb', encoding='utf8') as version_write:
for line in output:
version_write.write(line + '\n')
_verbose_output(verbose, 'Finished writing to {}.version.', MODULE_NAME)
def _gather_commit_messages(verbose):
_verbose_output(verbose, 'Gathering commit messages since last release commit.')
command = [
'git',
'log',
'-1',
'--format=%H',
'--grep={}'.format(RELEASE_MESSAGE_TEMPLATE.replace(' {}', '').replace('"', '\\"'))
]
_verbose_output(verbose, 'Running command: "{}"', '" "'.join(command))
commit_hash = subprocess.check_output(command, stderr=sys.stderr).decode('utf8').strip()
if not commit_hash:
_verbose_output(verbose, 'No previous release commit was found. Not gathering messages.')
return []
command = [
'git',
'log',
'--format=%s',
'{}..HEAD'.format(commit_hash)
]
_verbose_output(verbose, 'Running command: "{}"', '" "'.join(command))
output = subprocess.check_output(command, stderr=sys.stderr).decode('utf8')
messages = []
for message in output.splitlines():
if not message.strip().startswith('Merge pull request #'):
messages.append('- {}'.format(message))
_verbose_output(
verbose,
'Returning {number} commit messages gathered since last release commit:\n{messages}',
number=len(messages),
messages=messages,
)
return messages
def _prompt_for_changelog(verbose):
built_up_changelog = []
changelog_header = []
changelog_message = []
changelog_footer = []
_verbose_output(verbose, 'Reading changelog file {} looking for built-up changes...', CHANGELOG_FILENAME)
with codecs.open(CHANGELOG_FILENAME, 'rb', encoding='utf8') as changelog_read:
previous_line = ''
passed_header = passed_changelog = False
for line_number, line in enumerate(changelog_read):
if not passed_header:
changelog_header.append(line)
# .txt and .md changelog files start like this:
# Changelog
# =========
# .rst changelog files start like this
# =========
# Changelog
# =========
if line_number > 0 and RE_CHANGELOG_FILE_HEADER.search(line):
passed_header = True
continue
if not passed_changelog and RE_CHANGELOG_VERSION_HEADER.search(line):
changelog_footer.append(previous_line)
passed_changelog = True
if passed_changelog:
changelog_footer.append(line)
else:
if previous_line.strip():
built_up_changelog.append(previous_line)
previous_line = line
if len(built_up_changelog) > 0:
_verbose_output(verbose, 'Read {} lines of built-up changelog text:', len(built_up_changelog))
if verbose:
_verbose_output(verbose, str(built_up_changelog))
_standard_output('There are existing changelog details for this release. You can "edit" the changes, '
'"accept" them as-is, delete them and create a "new" changelog message, or "delete" '
'them and enter no changelog.')
instruction = _prompt('How would you like to proceed? (EDIT/new/accept/delete/exit):').lower()
if instruction in (INSTRUCTION_NEW, INSTRUCTION_DELETE):
built_up_changelog = []
if instruction == INSTRUCTION_ACCEPT:
changelog_message = built_up_changelog
if not instruction or instruction in (INSTRUCTION_EDIT, INSTRUCTION_NEW):
instruction = INSTRUCTION_YES
else:
_verbose_output(verbose, 'No existing lines of built-up changelog text were read.')
instruction = _prompt(
'Would you like to enter changelog details for this release? (Y/n/exit):',
).lower() or INSTRUCTION_YES
if instruction == INSTRUCTION_EXIT:
raise ReleaseExit()
if instruction == INSTRUCTION_YES:
gather = _prompt(
'Would you like to{also} gather commit messages from recent commits and add them to the '
'changelog? ({y_n}/exit):',
**({'also': ' also', 'y_n': 'y/N'} if built_up_changelog else {'also': '', 'y_n': 'Y/n'})
).lower() or (INSTRUCTION_NO if built_up_changelog else INSTRUCTION_YES)
commit_messages = []
if gather == INSTRUCTION_YES:
commit_messages = _gather_commit_messages(verbose)
elif gather == INSTRUCTION_EXIT:
raise ReleaseExit()
tf_o = tempfile.NamedTemporaryFile(mode='wb')
codec = codecs.lookup('utf8')
with codecs.StreamReaderWriter(tf_o, codec.streamreader, codec.streamwriter, 'strict') as tf:
_verbose_output(verbose, 'Opened temporary file {} for editing changelog.', tf.name)
if commit_messages:
tf.write('\n'.join(commit_messages) + '\n')
if built_up_changelog:
tf.writelines(built_up_changelog)
tf.writelines([
'\n',
'# Enter your changelog message above this comment, then save and close editor when finished.\n',
'# Any existing contents were pulled from changes to CHANGELOG.txt since the last release.\n',
'# Leave it blank (delete all existing contents) to release with no changelog details.\n',
'# All lines starting with "#" are comments and ignored.\n',
'# As a best practice, if you are entering multiple items as a list, prefix each item with a "-".'
])
tf.flush()
_verbose_output(verbose, 'Wrote existing changelog contents and instructions to temporary file.')
editor = os.environ.get('INVOKE_RELEASE_EDITOR', os.environ.get('EDITOR', 'vim'))
_verbose_output(verbose, 'Opening editor {} to edit changelog.', editor)
try:
subprocess.check_call(
shlex.split(editor) + [tf.name],
stdout=sys.stdout,
stderr=sys.stderr,
)
except (subprocess.CalledProcessError, OSError) as e:
args = {'editor': editor}
if isinstance(e, OSError):
message = 'Failed to open changelog editor `{editor}` due to error: {error} (err {error_code}).'
args.update(error=e.strerror, error_code=e.errno)
else:
message = 'Failed to open changelog editor `{editor}` due to return code: {return_code}.'
args.update(return_code=e.returncode)
message += (
' Try setting $INVOKE_RELEASE_EDITOR or $EDITOR in your shell profile to the full path to '
'Vim or another editor.'
)
raise ReleaseFailure(message.format(**args))
_verbose_output(verbose, 'User has closed editor')
with codecs.open(tf.name, 'rb', encoding='utf8') as read:
first_line = True
last_line_blank = False
for line in read:
line_blank = not line.strip()
if (first_line or last_line_blank) and line_blank:
# Suppress leading blank lines and compress multiple blank lines into one
continue
if line.startswith(CHANGELOG_COMMENT_FIRST_CHAR):
# Suppress comments
continue
changelog_message.append(line)
last_line_blank = line_blank
first_line = False
if last_line_blank:
# Suppress trailing blank lines
changelog_message.pop()
_verbose_output(verbose, 'Changelog message read from temporary file:\n{}', changelog_message)
return changelog_header, changelog_message, changelog_footer
def _write_to_changelog_file(release_version, changelog_header, changelog_message, changelog_footer, verbose):
_verbose_output(verbose, 'Writing changelog contents to {}.', CHANGELOG_FILENAME)
if not _case_sensitive_regular_file_exists(CHANGELOG_FILENAME):
raise ReleaseFailure(
'Failed to find changelog file: {}. File names are case sensitive!'.format(CHANGELOG_FILENAME),
)
with codecs.open(CHANGELOG_FILENAME, 'wb', encoding='utf8') as changelog_write:
header_line = '{version} ({date})'.format(
version=release_version,
date=datetime.datetime.now().strftime('%Y-%m-%d'),
)
changelog_write.writelines(changelog_header + ['\n'])
if changelog_message:
changelog_write.writelines([
header_line, '\n', '-' * len(header_line), '\n',
])
changelog_write.writelines(changelog_message + ['\n'])
changelog_write.writelines(changelog_footer)
_verbose_output(verbose, 'Finished writing to changelog.')
def _tag_branch(release_version, changelog_lines, verbose, overwrite=False):
_verbose_output(verbose, 'Tagging branch...')
try:
gpg = subprocess.check_output(['which', 'gpg']).decode('utf8').strip()
_verbose_output(verbose, 'Found location of `gpg` to be {}'.format(gpg))
except subprocess.CalledProcessError:
gpg = None
if not gpg:
try:
gpg = subprocess.check_output(['which', 'gpg2']).decode('utf8').strip()
_verbose_output(verbose, 'Found location of `gpg2` to be {}'.format(gpg))
except subprocess.CalledProcessError:
gpg = None
try:
tty = subprocess.check_output(['tty']).decode('utf8').strip()
_verbose_output(verbose, 'Found location of `tty` to be {}'.format(tty))
except subprocess.CalledProcessError:
_verbose_output(verbose, 'Could not get tty path ... Maybe a problem? Maybe not.')
tty = ''
release_message = RELEASE_MESSAGE_TEMPLATE.format(release_version)
if changelog_lines:
release_message += '\n\nChangelog Details:'
for line in changelog_lines:
release_message += '\n' + line.strip()
cmd = ['git', 'tag', '-a', release_version, '-m', release_message]
if overwrite:
cmd.append('-f')
signed = False
if gpg:
sign_with_key = _prompt(
'GPG is installed on your system. Would you like to sign the release tag with your GitHub committer email '
'GPG key? (y/N/[alternative key ID]):',
).lower() or INSTRUCTION_NO
if sign_with_key == INSTRUCTION_YES:
cmd.append('-s')
elif sign_with_key != INSTRUCTION_NO:
cmd.extend(['-u', sign_with_key])
if sign_with_key != INSTRUCTION_NO:
signed = True
try:
subprocess.check_output(
['git', 'config', '--global', 'gpg.program', gpg],
)
except subprocess.CalledProcessError as e:
raise ReleaseFailure(
'Failed to configure Git+GPG. Something is not right. Aborting.\n{code}: {output}'.format(
code=e.returncode,
output=e.output.decode('utf8'),
)
)
else:
_standard_output('GPG is not installed on your system. Will not sign the release tag.')
try:
result = subprocess.check_output(
cmd,
stderr=subprocess.STDOUT,
env=dict(os.environ, GPG_TTY=tty),
).decode('utf8')
except subprocess.CalledProcessError as e:
result = '`git` command exit code {code} - {output}'.format(code=e.returncode, output=e.output.decode('utf8'))
if result:
if 'unable to sign the tag' in result:
raise ReleaseFailure(
'Failed tagging branch due to error signing the tag. Perhaps you need to create a code-signing key, or '
'the alternate key ID you specified was incorrect?\n\n'
'Suggestions:\n'
' - Generate a key with `{gpg} --get-key` (GPG v1) or `{gpg} --full-gen-key` (GPG v2) (and use 4096)\n'
' - It is not enough for the key email to match your committer email; the full display name must '
'match, too (e.g. "First Last <email@example.org>")\n'
' - If the key display name does not match the committer display name, use the alternate key ID\n'
'Error output: {output}'.format(gpg=gpg, output=result)
)
raise ReleaseFailure('Failed tagging branch: {}'.format(result))
if signed:
try:
subprocess.check_call(
['git', 'tag', '-v', release_version],
stdout=sys.stdout,
stderr=sys.stderr,
)
except subprocess.CalledProcessError:
raise ReleaseFailure(
'Successfully created a signed release tag, but failed to verify its signature. Something is not right.'
)
_verbose_output(verbose, 'Finished tagging branch.')
def _commit_release_changes(release_version, changelog_lines, verbose):
_verbose_output(verbose, 'Committing release changes...')
files_to_commit = [VERSION_FILENAME, CHANGELOG_FILENAME] + _get_extra_files_to_commit()
_verbose_output(verbose, 'Staging changes for files {}.'.format(files_to_commit))
try:
result = subprocess.check_output(
['git', 'add'] + files_to_commit,
stderr=subprocess.STDOUT,
)
except subprocess.CalledProcessError as e:
result = '`git` command exit code {code} - {output}'.format(code=e.returncode, output=e.output.decode('utf8'))
if result:
raise ReleaseFailure('Failed staging release files for commit: {}'.format(result))
release_message = [RELEASE_MESSAGE_TEMPLATE.format(release_version)]
if changelog_lines:
release_message.append('\nChangelog Details:')
for line in changelog_lines:
release_message.append(line.strip())
subprocess.check_call(
['git', 'commit', '-m', '\n'.join(release_message)],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished releasing changes.')
def _push_release_changes(release_version, branch_name, default_branch, verbose):
try:
if USE_TAG:
message = 'Push release changes and tag to remote origin (branch "{}")? (y/N/rollback):'
else:
message = 'Push release changes to remote origin (branch "{}")? (y/N/rollback):'
push = _prompt(message, branch_name).lower()
except KeyboardInterrupt:
push = INSTRUCTION_ROLLBACK
if push == INSTRUCTION_YES:
_verbose_output(verbose, 'Pushing changes to remote origin...')
subprocess.check_call(
['git', 'push', 'origin', '{0}:{0}'.format(branch_name)],
stdout=sys.stdout,
stderr=sys.stderr,
)
if USE_TAG:
# push the release tag
subprocess.check_call(
['git', 'push', 'origin', release_version],
stdout=sys.stdout,
stderr=sys.stderr,
)
if USE_PULL_REQUEST:
_checkout_branch(verbose, default_branch)
_delete_branch(verbose, branch_name)
_verbose_output(verbose, 'Finished pushing changes to remote origin.')
return PUSH_RESULT_PUSHED
elif push == INSTRUCTION_ROLLBACK:
_standard_output('Rolling back local release commit and tag...')
if USE_PULL_REQUEST:
_checkout_branch(verbose, default_branch)
_delete_branch(verbose, branch_name)
else:
_delete_last_commit(verbose)
if USE_TAG:
_delete_local_tag(release_version, verbose)
_verbose_output(verbose, 'Finished rolling back local release commit.')
return PUSH_RESULT_ROLLBACK
else:
_standard_output('Not pushing changes to remote origin!')
if USE_TAG:
_print_output(
COLOR_RED_BOLD,
'Make sure you remember to explicitly push {branch} and the tag '
'(or revert your local changes if you are trying to cancel)! '
'You can push with the following commands:\n'
' git push origin {branch}:{branch}\n'
' git push origin "{tag}"\n',
branch=branch_name,
tag=release_version,
)
else:
_print_output(
COLOR_RED_BOLD,
'Make sure you remember to explicitly push {branch} (or revert your local changes if you are '
'trying to cancel)! You can push with the following command:\n'
' git push origin {branch}:{branch}\n',
branch=branch_name,
)
return PUSH_RESULT_NO_ACTION
def _get_last_commit_hash(verbose):
_verbose_output(verbose, 'Getting last commit hash...')
commit_hash = subprocess.check_output(
['git', 'log', '-n', '1', '--pretty=format:%H'],
stderr=sys.stderr,
).decode('utf8').strip()
_verbose_output(verbose, 'Last commit hash is {}.', commit_hash)
return commit_hash
def _get_commit_subject(commit_hash, verbose):
_verbose_output(verbose, 'Getting commit message for hash {}...', commit_hash)
message = subprocess.check_output(
['git', 'log', '-n', '1', '--pretty=format:%s', commit_hash],
stderr=sys.stderr,
).decode('utf8').strip()
_verbose_output(verbose, 'Commit message for hash {hash} is "{value}".', hash=commit_hash, value=message)
return message
def _get_branch_name(verbose):
_verbose_output(verbose, 'Determining current Git branch name.')
branch_name = subprocess.check_output(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
stderr=sys.stderr,
).decode('utf8').strip()
_verbose_output(verbose, 'Current Git branch name is {}.', branch_name)
return branch_name
def _get_default_branch(verbose):
_verbose_output(verbose, 'Determining current Git default branch.')
remote_info = subprocess.check_output(
['git', 'remote', 'show', 'origin'],
stderr=sys.stderr,
).decode('utf8').strip()
for line in iter(remote_info.splitlines()):
if HEAD_BRANCH in line:
default_branch = line.strip().replace(HEAD_BRANCH, '')
_verbose_output(verbose, 'Current Git default branch is {}.', default_branch)
return default_branch
def _create_branch(verbose, branch_name):
_verbose_output(verbose, 'Creating branch {branch}...', branch=branch_name)
subprocess.check_call(
['git', 'checkout', '-b', branch_name],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done creating branch {}.', branch_name)
def _create_local_tracking_branch(verbose, branch_name):
"""Create a local tracking branch of origin/<branch_name>.
Returns True if successful, False otherwise.
"""
_verbose_output(
verbose,
'Creating local branch {branch} set up to track remote branch {branch} from \'origin\'...',
branch=branch_name
)
success = True
try:
subprocess.check_call(
['git', 'checkout', '--track', 'origin/{}'.format(branch_name)],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done creating branch {}.', branch_name)
except subprocess.CalledProcessError:
_verbose_output(verbose, 'Creating branch {} failed.', branch_name)
success = False
return success
def _checkout_branch(verbose, branch_name):
_verbose_output(verbose, 'Checking out branch {branch}...', branch=branch_name)
subprocess.check_call(
['git', 'checkout', branch_name],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done checking out branch {}.', branch_name)
def _delete_branch(verbose, branch_name):
_verbose_output(verbose, 'Deleting branch {branch}...', branch=branch_name)
subprocess.check_call(
['git', 'branch', '-D', branch_name],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done deleting branch {}.', branch_name)
def _is_branch_on_remote(verbose, branch_name):
_verbose_output(verbose, 'Checking if branch {} exists on remote...', branch_name)
result = subprocess.check_output(
['git', 'ls-remote', '--heads', 'origin', branch_name],
stderr=sys.stderr,
).decode('utf8').strip()
on_remote = branch_name in result
_verbose_output(
verbose,
'Result of on-remote check for branch {branch_name} is {result}.',
branch_name=branch_name,
result=on_remote,
)
return on_remote
def _create_branch_from_tag(verbose, tag_name, branch_name):
_verbose_output(verbose, 'Creating branch {branch} from tag {tag}...', branch=branch_name, tag=tag_name)
subprocess.check_call(
['git', 'checkout', 'tags/{}'.format(tag_name), '-b', branch_name],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done creating branch {}.', branch_name)
def _push_branch(verbose, branch_name):
_verbose_output(verbose, 'Pushing branch {} to remote.', branch_name)
subprocess.check_call(
['git', 'push', 'origin', '{0}:{0}'.format(branch_name)],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done pushing branch {}.', branch_name)
def _fetch_tags(verbose):
_verbose_output(verbose, 'Fetching all remote tags...')
subprocess.check_call(
['git', 'fetch', '--tags'],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Done fetching tags.')
def _get_tag_list(verbose):
_verbose_output(verbose, 'Parsing list of local tags...')
result = subprocess.check_output(
['git', 'tag', '--list'],
stderr=sys.stderr,
).decode('utf8').strip().split()
_verbose_output(verbose, 'Result of tag list parsing is {}.', result)
return result
def _does_tag_exist_locally(release_version, verbose):
_verbose_output(verbose, 'Checking if tag {} exists locally...', release_version)
result = subprocess.check_output(
['git', 'tag', '--list', release_version],
stderr=sys.stderr,
).decode('utf8').strip()
exists = release_version in result
_verbose_output(verbose, 'Result of exists check for tag {tag} is {result}.', tag=release_version, result=exists)
return exists
def _is_tag_on_remote(release_version, verbose):
_verbose_output(verbose, 'Checking if tag {} was pushed to remote...', release_version)
result = subprocess.check_output(
['git', 'ls-remote', '--tags', 'origin', release_version],
stderr=sys.stderr,
).decode('utf8').strip()
on_remote = release_version in result
_verbose_output(
verbose,
'Result of on-remote check for tag {tag} is {result}.',
tag=release_version,
result=on_remote,
)
return on_remote
def _get_remote_branches_with_commit(commit_hash, verbose):
_verbose_output(verbose, 'Checking if commit {} was pushed to any remote branches...', commit_hash)
result = subprocess.check_output(
['git', 'branch', '-r', '--contains', commit_hash],
stderr=sys.stderr,
).decode('utf8').strip()
on_remote = []
for line in result.splitlines():
line = line.strip()
if line.startswith('origin/') and not line.startswith('origin/HEAD'):
on_remote.append(line)
_verbose_output(
verbose,
'Result of on-remote check for commit {hash} is {remote}.',
hash=commit_hash,
remote=on_remote,
)
return on_remote
def _delete_local_tag(tag_name, verbose):
_verbose_output(verbose, 'Deleting local tag {}...', tag_name)
subprocess.check_call(
['git', 'tag', '-d', tag_name],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished deleting local tag {}.', tag_name)
def _delete_remote_tag(tag_name, verbose):
_verbose_output(verbose, 'Deleting remote tag {}...', tag_name)
subprocess.check_call(
['git', 'push', 'origin', ':refs/tags/{}'.format(tag_name)],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished deleting remote tag {}.', tag_name)
def _delete_last_commit(verbose):
_verbose_output(verbose, 'Deleting last commit, assumed to be for version and changelog files...')
extra_files = _get_extra_files_to_commit()
subprocess.check_call(
['git', 'reset', '--soft', 'HEAD~1'],
stdout=sys.stdout,
stderr=sys.stderr,
)
subprocess.check_call(
['git', 'reset', 'HEAD', VERSION_FILENAME, CHANGELOG_FILENAME] + extra_files,
stdout=sys.stdout,
stderr=sys.stderr,
)
subprocess.check_call(
['git', 'checkout', '--', VERSION_FILENAME, CHANGELOG_FILENAME] + extra_files,
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished deleting last commit.')
def _revert_remote_commit(release_version, commit_hash, branch_name, verbose):
_verbose_output(verbose, 'Rolling back release commit on remote branch "{}"...', branch_name)
subprocess.check_call(
['git', 'revert', '--no-edit', '--no-commit', commit_hash],
stdout=sys.stdout,
stderr=sys.stderr,
)
release_message = 'REVERT: {}'.format(RELEASE_MESSAGE_TEMPLATE.format(release_version))
subprocess.check_call(
['git', 'commit', '-m', release_message],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Pushing changes to remote branch "{}"...', branch_name)
subprocess.check_call(
['git', 'push', 'origin', '{0}:{0}'.format(branch_name)],
stdout=sys.stdout,
stderr=sys.stderr,
)
_verbose_output(verbose, 'Finished rolling back release commit.')
def _import_version_or_exit():
if VERSION_FILE_IS_TXT:
# if there is version.txt, use that
with codecs.open(VERSION_FILENAME, 'rb', encoding='utf8') as version_txt:
return version_txt.read()
try:
return __import__('{}.version'.format(MODULE_NAME), fromlist=[str('__version__')]).__version__
except ImportError as e:
import pprint
_error_output_exit(
'Could not import `__version__` from `{module}.version`. Error was "ImportError: {err}." Path is:\n{path}',
module=MODULE_NAME,
err=e.args[0],
path=pprint.pformat(sys.path),
)
except AttributeError as e:
_error_output_exit('Could not retrieve `__version__` from imported module. Error was "{}."', e.args[0])
def _ensure_files_exist(exit_on_failure):
failure = False
if not _case_sensitive_regular_file_exists(VERSION_FILENAME):
_error_output('Version file {} was not found!', RE_FILE_EXTENSION.sub('.(py|txt)', VERSION_FILENAME))
failure = True
if not _case_sensitive_regular_file_exists(CHANGELOG_FILENAME):