-
Notifications
You must be signed in to change notification settings - Fork 37
/
moz-phab
executable file
·3548 lines (2890 loc) · 116 KB
/
moz-phab
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
#!/usr/bin/env python2
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# coding=utf-8
"""
Wrapper around Phabricator's `arc` cli to support submission of a series of commits.
Goals:
- must only use standard libraries
- must be a single file for easy deployment
- should work on python 2.7 and python 3.5+
"""
import argparse
import calendar
import ConfigParser
import datetime
import errno
import io
import json
import logging
import logging.handlers
import os
import re
import ssl
import stat
import subprocess
import sys
import tempfile
import time
import traceback
import urllib2
import uuid
from contextlib import contextmanager
from distutils.version import LooseVersion
from glob import glob
# Known Issues
# - reordering, folding, etc commits doesn't result in the stack being updated
# correctly on phabricator, or may outright fail due to dependency loops.
# to address this we'll need to query phabricator's api directly and clear
# dependencies prior to calling arc. we'd probably also have to
# abandon revisions that are no longer part of the stack. unfortunately
# phabricator's api currently doesn't expose calls to do this.
# - commits with a description already modified by arc (ie. the follow the arc commit
# description template with 'test plan', subscribers, etc) are not handled by this
# script. commits in this format should be detected and result in the commit being
# rejected. ideally this should extract the title, body, reviewers, and bug-id
# from the arc template and reformat to the standard mozilla format.
# Environment Vars
DEBUG = bool(os.getenv("DEBUG"))
IS_WINDOWS = sys.platform == "win32"
HAS_ANSI = not IS_WINDOWS and (
(hasattr(sys.stdout, "isatty") and sys.stdout.isatty())
or os.getenv("TERM", "") == "ANSI"
or os.getenv("PYCHARM_HOSTED", "") == "1"
)
SELF_FILE = os.getenv("UPDATE_FILE") if os.getenv("UPDATE_FILE") else __file__
# Constants and Globals
logger = logging.getLogger("moz-phab")
config = None
# Where to direct people when `arc` isn't installed.
GUIDE_URL = (
"https://moz-conduit.readthedocs.io/en/latest/phabricator-user.html#quick-start"
)
GIT_COMMAND = ["git.exe" if IS_WINDOWS else "git"]
HOME_DIR = os.path.expanduser("~")
# ~/.mozbuild/moz-phab
MOZBUILD_PATH = os.path.join(
os.environ.get("MOZBUILD_STATE_PATH", os.path.join(HOME_DIR, ".mozbuild")),
"moz-phab",
)
LOG_FILE = os.path.join(MOZBUILD_PATH, "moz-phab.log")
LOG_MAX_SIZE = 1024 * 1024 * 50
LOG_BACKUPS = 5
# Arcanist
LIBPHUTIL_PATH = os.path.join(MOZBUILD_PATH, "libphutil")
ARC_PATH = os.path.join(MOZBUILD_PATH, "arcanist")
ARC_COMMAND = os.path.join(ARC_PATH, "bin", "arc.bat" if IS_WINDOWS else "arc")
ARC = [ARC_COMMAND]
INSTALL_CERT_MSG = (
"You don't have credentials needed to access Phabricator.\n"
"Please run the following command to configure moz-phab:\n\n"
" moz-phab install-certificate\n "
)
ARC_CONDUIT_ERROR = (
{"matching": "install-certificate", "message": INSTALL_CERT_MSG},
{"matching": "ERR-INVALID_AUTH", "message": "Server rejected your token."},
)
LIBPHUTIL_URL = "https://github.com/phacility/libphutil.git"
ARC_URL = "https://github.com/mozilla-conduit/arcanist.git"
# Auto-update
SELF_REPO = "mozilla-conduit/review"
SELF_UPDATE_FREQUENCY = 24 * 3 # hours
ARC_UPDATE_FREQUENCY = 24 * 7 # hours
# Environment names (display purposes only)
PHABRICATOR_URLS = {
"https://phabricator.services.mozilla.com/": "Phabricator",
"https://phabricator-dev.allizom.org/": "Phabricator-Dev",
}
DEFAULT_UPDATE_MESSAGE = "Revision updated."
# arc related consts.
ARC_COMMIT_DESC_TEMPLATE = """
{title}
Summary:
{body}
{depends_on}
Test Plan:
Reviewers: {reviewers}
Subscribers:
Bug #: {bug_id}
""".strip()
ARC_OUTPUT_REV_URL_RE = re.compile(r"^\s*Revision URI: (http.+)$", flags=re.MULTILINE)
ARC_DIFF_REV_RE = re.compile(
r"^\s*Differential Revision:\s*https?://.+/D(\d+)\s*$", flags=re.MULTILINE
)
# If a commit body matches **all** of these, reject it. This is to avoid the
# necessity to merge arc-style fields across an existing commit description
# and what we need to set.
ARC_REJECT_RE_LIST = [
re.compile(r"^Summary:", flags=re.MULTILINE),
re.compile(r"^Reviewers:", flags=re.MULTILINE),
]
# Bug and review regexs (from vct's commitparser)
BUG_ID_RE = re.compile(r"(?:(?:bug|b=)(?:\s*)(\d+)(?=\b))", flags=re.IGNORECASE)
LIST = r"[;,\/\\]\s*"
LIST_RE = re.compile(LIST)
IRC_NICK_CHARS = r"a-zA-Z0-9\-\_!" # includes !, which is different from commitparser
IRC_NICK = r"#?[" + IRC_NICK_CHARS + "]+"
REVIEWERS_RE = (
r"([\s(.\[;,])(r%s)("
+ IRC_NICK
+ r"(?:"
+ LIST
+ r"(?![a-z0-9.\-]+[=?])"
+ IRC_NICK
+ r")*)?"
)
ALL_REVIEWERS_RE = re.compile(REVIEWERS_RE % r"[=?]")
REQUEST_REVIEWERS_RE = re.compile(REVIEWERS_RE % r"[?]")
GRANTED_REVIEWERS_RE = re.compile(REVIEWERS_RE % r"=")
R_SPECIFIER_RE = re.compile(r"\br[=?]")
BLOCKING_REVIEWERS_RE = re.compile(r"\b(r!)([" + IRC_NICK_CHARS + ",]+)")
DEPENDS_ON_RE = re.compile(r"^\s*Depends on\s*D(\d+)\s*$", flags=re.MULTILINE)
MINIMUM_MERCURIAL_VERSION = LooseVersion("4.3.3")
#
# Utilities
#
class SimpleCache:
"""Simple key/value store with all lowercase keys."""
def __init__(self):
self._cache = dict()
def __contains__(self, key):
return key.lower() in self._cache
def get(self, key):
return self._cache.get(key.lower())
def set(self, key, value):
self._cache[key.lower()] = value
def delete(self, key):
if key in self:
del self._cache[key.lower()]
def reset(self):
self._cache = dict()
cache = SimpleCache()
def which_path(path):
"""Check if an executable is provided. Fall back to which if not.
Args:
path: (str) filename or path to check for an executable command
Returns:
The full path of a command or None.
"""
if (
os.path.exists(path)
and os.access(path, os.F_OK | os.X_OK)
and not os.path.isdir(path)
):
return path
return which(path)
def which(filename):
# backport of shutil.which from py3
seen = set()
for path in os.environ.get("PATH", os.defpath).split(os.pathsep):
path = os.path.expanduser(path)
norm_path = os.path.normcase(path)
if norm_path not in seen:
seen.add(norm_path)
fn = os.path.join(path, filename)
if (
os.path.exists(fn)
and os.access(fn, os.F_OK | os.X_OK)
and not os.path.isdir(fn)
):
return fn
return None
def shell_quote(s):
# backport of shutil.quote from py3
# used for debugging output only
_find_unsafe = re.compile(r"[^\w@%+=:,./-]").search
if not s:
return "''"
if _find_unsafe(s) is None:
return s
return "'" + s.replace("'", "'\"'\"'").replace("\n", "\\n") + "'"
def parse_zulu_time(timestamp):
"""Parse YYYY-MM-DDTHH:mm:SSZ date string, return as epoch seconds in local tz."""
return calendar.timegm(time.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ"))
def check_call(command, **kwargs):
# wrapper around subprocess.check_call with debug output
logger.debug("$ %s" % " ".join(shell_quote(s) for s in command))
subprocess.check_call(command, **kwargs)
def check_call_by_line(command, cwd=None, never_log=False):
# similar to check_call, yields for line-by-line processing
logger.debug("$ %s" % " ".join(shell_quote(s) for s in command))
# Connecting the STDIN to the PIPE will make arc throw an exception on reading
# user input
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, cwd=cwd
)
try:
for line in iter(process.stdout.readline, ""):
line = line.rstrip()
if not never_log:
logger.debug("> %s" % line)
yield line
finally:
process.stdout.close()
process.wait()
if process.returncode:
raise subprocess.CalledProcessError(process.returncode, command)
def check_output(
command,
cwd=None,
split=True,
strip=True,
never_log=False,
stdin=None,
stderr=None,
env=None,
search_error=None,
):
# wrapper around subprocess.check_output with debug output and splitting
logger.debug("$ %s" % " ".join(shell_quote(s) for s in command))
kwargs = dict(cwd=cwd, stdin=stdin, stderr=stderr)
if env:
kwargs["env"] = env
try:
output = subprocess.check_output(command, **kwargs)
except subprocess.CalledProcessError as e:
if search_error:
for err in search_error:
if err["matching"] in e.output:
logger.error(err["message"])
logger.debug(e.output)
raise CommandError(
"command '%s' failed to complete successfully" % command[0], e.returncode
)
if strip:
output = output.rstrip()
if output and not never_log:
logger.debug(output)
return output.splitlines() if split else output
def read_json_field(files, field_path):
"""Parses json files in turn returning value as per field_path, or None."""
for filename in files:
try:
with open(filename) as f:
rc = json.load(f)
for field_name in field_path:
if field_name not in rc:
rc = None
break
rc = rc[field_name]
if not rc:
continue
return rc
except IOError as e:
if e.errno == errno.ENOENT:
continue
raise
except ValueError:
continue
return None
def prompt(question, options):
if HAS_ANSI:
question = "\033[33m%s\033[0m" % question
prompt_options = list(options)
prompt_options[0] = prompt_options[0].upper()
prompt_str = "%s (%s)? " % (question, "/".join(prompt_options))
options_map = {o[0].lower(): o for o in options}
options_map[""] = options[0]
while True:
res = raw_input(prompt_str)
if len(res) > 1:
res = res[0].lower()
if res == chr(27): # escape
sys.exit(1)
if res in options_map:
return options_map[res]
def parse_config(config_list, filter_func=None):
"""Parses list with "name=value" strings.
Args:
config_list: A list of "name=value" strings
filter_func: A function taking the parsing config name and value for each line.
If the function returns True the config value will be included in the final
dict.
Returns: A dict containing parsed data.
"""
result = dict()
for line in config_list:
# On Windows config file is likely to be cp1252 encoded, not UTF-8.
if IS_WINDOWS:
try:
line = line.decode("cp1252").encode("UTF-8")
except UnicodeDecodeError:
pass
name, value = line.split("=", 1)
name = name.strip()
value = value.strip()
if filter_func is None or (callable(filter_func) and filter_func(name, value)):
result[name] = value
return result
def normalise_reviewer(reviewer, strip_group=True):
"""This provide a canonical form of the reviewer for comparison."""
reviewer = reviewer.rstrip("!").lower()
if strip_group:
reviewer = reviewer.lstrip("#")
return reviewer
@contextmanager
def temporary_file(content):
f = tempfile.NamedTemporaryFile(delete=False)
try:
f.write(content)
f.flush()
f.close()
yield f.name
finally:
os.remove(f.name)
class Error(Exception):
"""Errors thrown explictly by this script; won't generate a stack trace."""
class NotFoundError(Exception):
"""Errors raised when node is not found."""
class NonLinearException(Exception):
"""Errors raised when multiple children or parents found."""
class CommandError(Exception):
status = None
def __init__(self, msg="", status=1):
self.status = status
super(CommandError, self).__init__(msg)
class ConduitAPIError(Error):
"""Raised when the Phabricator Conduit API returns an error response."""
#
# Configuration
#
class Config(object):
def __init__(self, should_access_file=True):
self._filename = os.path.join(HOME_DIR, ".moz-phab-config")
self.name = "~/.moz-phab-config" # human-readable name
# Default values.
defaults = u"""
[ui]
no_ansi = False
[vcs]
safe_mode = False
[git]
remote =
[submit]
auto_submit = False
always_blocking = False
warn_untracked = True
[patch]
apply_to = base
create_bookmark = True
always_full_stack = False
[updater]
self_last_check = 0
arc_last_check = 0
"""
self._config = ConfigParser.SafeConfigParser()
self._config.readfp(
io.StringIO("\n".join([l.strip() for l in defaults.splitlines()]))
)
if self._config.has_section("arc"):
self._config.remove_section("arc")
if should_access_file:
self._config.read([self._filename])
self.no_ansi = self._config.getboolean("ui", "no_ansi")
self.safe_mode = self._config.getboolean("vcs", "safe_mode")
self.auto_submit = self._config.getboolean("submit", "auto_submit")
self.always_blocking = self._config.getboolean("submit", "always_blocking")
self.warn_untracked = self._config.getboolean("submit", "warn_untracked")
self.apply_patch_to = self._config.get("patch", "apply_to")
self.create_bookmark = self._config.getboolean("patch", "create_bookmark")
self.always_full_stack = self._config.getboolean("patch", "always_full_stack")
self.self_last_check = self._config.getint("updater", "self_last_check")
self.arc_last_check = self._config.getint("updater", "arc_last_check")
git_remote = self._config.get("git", "remote")
self.git_remote = git_remote.replace(" ", "").split(",") if git_remote else []
if should_access_file and not os.path.exists(self._filename):
self.write()
self.arc = None
def _set(self, section, option, value):
if not self._config.has_section(section):
self._config.add_section(section)
self._config.set(section, option, str(value))
def write(self):
if os.path.exists(self._filename):
logger.debug("updating %s" % self._filename)
self._set("submit", "auto_submit", self.auto_submit)
self._set("patch", "always_full_stack", self.always_full_stack)
self._set("updater", "self_last_check", self.self_last_check)
self._set("updater", "arc_last_check", self.arc_last_check)
else:
logger.debug("creating %s" % self._filename)
self._set("ui", "no_ansi", self.no_ansi)
self._set("vcs", "safe_mode", self.safe_mode)
self._set("git", "remote", ", ".join(self.git_remote))
self._set("submit", "auto_submit", self.auto_submit)
self._set("submit", "always_blocking", self.always_blocking)
self._set("submit", "warn_untracked", self.warn_untracked)
self._set("patch", "apply_to", self.apply_patch_to)
self._set("patch", "create_bookmark", self.create_bookmark)
self._set("patch", "always_full_stack", self.always_full_stack)
with open(self._filename, "w") as f:
self._config.write(f)
#
# Repository
#
def find_repo_root(path):
"""Lightweight check for a repo in/under the specified path."""
path = os.path.abspath(path)
while os.path.split(path)[1]:
if Mercurial.is_repo(path) or Git.is_repo(path):
return path
path = os.path.abspath(os.path.join(path, os.path.pardir))
return None
def probe_repo(path):
try:
return Mercurial(path)
except ValueError:
pass
try:
return Git(path)
except ValueError:
pass
return None
def repo_from_args(args):
"""Returns a Repository object from either args.path or the cwd"""
repo = None
# This allows users to override the below sanity checks.
if hasattr(args, "path") and args.path:
repo = probe_repo(args.path)
if not repo:
raise Error("%s: Not a repository: .hg / .git" % args.path)
else:
# Walk parents to find repository root.
path = find_repo_root(os.getcwd())
if path:
repo = probe_repo(path)
if not repo:
raise Error(
"Not a repository (or any of the parent directories): .hg / .git"
)
repo.set_args(args)
return repo
class Repository(object):
def __init__(self, path, dot_path, phab_url=None):
self.path = path # base repository directory
self.dot_path = dot_path # .hg/.git directory
self.args = None
self.phab_url = phab_url or self._phab_url()
def is_worktree_clean(self):
"""Check if the working tree is clean."""
def before_submit(self):
"""Add special step for the submit command."""
def _phab_url(self):
"""Determine the phab/conduit URL."""
# In order of priority as per arc
# FIXME: This should also check {.hg|.git}/arc/config, which is where
# `arc set-config --local` writes to. See bug 1497786.
arcconfig_files = [
os.path.join(self.dot_path, ".arcconfig"),
os.path.join(self.path, ".arcconfig"),
]
if IS_WINDOWS:
defaults_files = [
os.path.join(os.getenv("APPDATA", ""), ".arcrc"),
os.path.join(
os.getenv("ProgramData", ""), "Phabricator", "Arcanist", "config"
),
]
else:
defaults_files = ["/etc/arcconfig", os.path.expanduser("~/.arcrc")]
phab_url = read_json_field(
arcconfig_files, ["phabricator.uri"]
) or read_json_field(defaults_files, ["config", "default"])
if not phab_url:
raise Error("Failed to determine Phabricator URL (missing .arcconfig?)")
return phab_url
def cleanup(self):
"""Perform any repo-related cleanup tasks.
May be called multiple times.
If an exception is raised this is NOT called (to avoid dataloss)."""
def finalize(self, commits):
"""Update the history after node changed."""
def set_args(self, args):
self.args = args
def untracked(self):
"""Return a list of untracked files."""
def commit_stack(self):
"""Return list of commits.
List of dicts with the following keys:
name human readable identifier of commit (eg. short sha)
node sha/hash
title first line of commit description (unaltered)
body commit description, excluding first line
title-preview title with bug-id and reviewer modifications
bug-id bmo bug-id
bug-id-orig original bug-id from commit desc
reviewers list of reviewers
rev-id phabricator revision id
"""
def refresh_commit_stack(self, commits):
"""Update the stack following an altering change (eg rebase)."""
def is_node(self, node):
"""Check if node exists.
Returns a Boolean.
"""
def check_node(self, node):
"""Check if node exists.
Returns a node if found.
Raises NotFoundError if node not found in the repository.
"""
def checkout(self, node):
"""Checkout/Update to specified node."""
def commit(self, body):
"""Commit the changes in the working directory."""
def amend_commit(self, commit, commits):
"""Amend commit description from `title` and `desc` fields"""
def rebase_commit(self, source_commit, dest_commit):
"""Rebase source onto destination."""
def before_patch(self, node, name):
"""Prepare repository to apply the patches."""
def apply_patch(self, diff, body, author, author_date):
"""Apply the patch and commit the changes."""
def check_commits_for_submit(self, commits, validate_reviewers=True):
"""Validate the list of commits (from commit_stack) are ok to submit"""
errors = []
warnings = []
# Extract a set of reviewers and verify first; they will be displayed
# with other commit errors.
all_reviewers = {}
reviewer_commit_map = {}
commit_invalid_reviewers = {}
for commit in commits:
commit_invalid_reviewers[commit["node"]] = []
if validate_reviewers:
# Flatten and deduplicate reviewer list, keeping track of the
# associated commit
for commit in commits:
for group in commit["reviewers"].keys():
for reviewer in commit["reviewers"][group]:
all_reviewers.setdefault(group, set())
all_reviewers[group].add(reviewer)
reviewer = normalise_reviewer(reviewer)
reviewer_commit_map.setdefault(reviewer, [])
reviewer_commit_map[reviewer].append(commit["node"])
# Verify all reviewers in a single call
for invalid_reviewer in check_for_invalid_reviewers(all_reviewers, self.path):
for node in reviewer_commit_map[
normalise_reviewer(invalid_reviewer["name"])
]:
commit_invalid_reviewers[node].append(invalid_reviewer)
unavailable_reviewers_warning = False
for commit in commits:
commit_errors = []
commit_warnings = []
# TODO allow NOBUG in commit message (not in arg)
# TODO be more relaxed if we're updating an existing rev?
if not commit["bug-id"]:
commit_errors.append("missing bug-id")
if has_arc_rejections(commit["body"]):
commit_errors.append("contains arc fields")
for reviewer in commit_invalid_reviewers[commit["node"]]:
if "until" in reviewer:
unavailable_reviewers_warning = True
msg = "%s is not available until %s" % (
reviewer["name"],
reviewer["until"],
)
if self.args.force:
commit_warnings.append(msg)
else:
commit_errors.append(msg)
else:
commit_errors.append(
"%s is not a valid reviewer's name" % reviewer["name"]
)
if commit_errors:
errors.append(
"%s %s\n- %s"
% (commit["name"], commit["title"], "\n- ".join(commit_errors))
)
if commit_warnings:
warnings.append(
"%s %s\n- %s"
% (commit["name"], commit["title"], "\n- ".join(commit_warnings))
)
if errors:
raise Error("\n\n".join(errors))
if warnings:
logger.warning("\n\n".join(warnings))
if unavailable_reviewers_warning:
logger.warning("Notice: reviewer availability overridden.")
def check_arc(self):
"""Check if arc can communicate with Phabricator."""
# Check if the cache file exists
path = os.path.join(self.dot_path, ".moz-phab_arc-configured")
if os.path.isfile(path):
return True
if arc_ping(self.path):
# Create the cache file
with open(path, "a"):
os.utime(path, None)
return True
return False
#
# Mercurial
#
class Mercurial(Repository):
def __init__(self, path):
dot_path = os.path.join(path, ".hg")
if not os.path.isdir(dot_path):
raise ValueError("%s: not a hg repository" % path)
logger.debug("found hg repo in %s" % path)
super(Mercurial, self).__init__(path, dot_path)
self._hg = ["hg.exe" if IS_WINDOWS else "hg"]
self.revset = None
self.strip_nodes = []
self.status = None
self.obsstore = None
self.unlink_obsstore = False
self.use_evolve = False
self.has_mq = False
self.has_shelve = False
# Normalise/standardise Mercurial's output.
os.environ["HGPLAIN"] = "1"
os.environ["HGENCODING"] = "UTF-8"
# Check for `hg`, and mercurial version.
if not which_path(self._hg[0]):
raise Error("Failed to find 'hg' executable")
m = re.search(
r"\(version ([^)]+)\)", self.hg_out(["--version", "--quiet"], split=False)
)
if not m:
raise Error("Failed to determine Mercurial version.")
if LooseVersion(m.group(1)) < MINIMUM_MERCURIAL_VERSION:
raise Error(
"You are currently running Mercurial %s. "
"Mercurial %s or newer is required."
% (m.group(1), MINIMUM_MERCURIAL_VERSION)
)
@classmethod
def is_repo(cls, path):
"""Quick check for repository at specified path."""
return os.path.exists(os.path.join(path, ".hg"))
@staticmethod
def _get_extension(extension, hg_config):
for prefix in ("extensions.%s", "extensions.hgext.%s"):
field = prefix % extension
if field in hg_config:
return hg_config.get(field, "")
return None
def is_worktree_clean(self):
status = self._status()
return not status["T"]
def hg(self, command, **kwargs):
check_call(self._hg + command, cwd=self.path, **kwargs)
def hg_out(self, command, **kwargs):
return check_output(self._hg + command, cwd=self.path, **kwargs)
def hg_log(self, revset, split=True, select="node"):
return self.hg_out(["log", "-T", "{%s}\n" % select, "-r", revset], split=split)
def cleanup(self):
# Remove the store of obsolescence markers; if the user doesn't have evolve
# installed mercurial will warn if this exists.
if not self.use_evolve and self.unlink_obsstore:
try:
os.unlink(self.obsstore)
except OSError as e:
if e.errno != errno.ENOENT:
raise
if self.strip_nodes:
# With the obsstore deleted the amended nodes are no longer hidden, so
# we need to strip them completely from the repo.
self.hg(["strip", "--hidden"] + self.strip_nodes)
self.strip_nodes = []
def _status(self):
# `hg status` is slow on large repos. As we'll need both uncommitted changes
# and untracked files separately, run it once and cache results.
if self.status is None:
self.status = dict(T=[], U=[])
for line in self.hg_out(
["status", "--added", "--deleted", "--modified", "--unknown"],
split=True,
):
status, path = line.split(" ", 1)
self.status["U" if status == "?" else "T"].append(path)
return self.status
def untracked(self):
return self._status()["U"]
def _refresh_commit(self, commit, node, rev=None):
"""Update commit's node and name from node and rev."""
if not rev:
rev = self.hg_log(node, select="rev", split=False)
commit["node"] = node
commit["name"] = "%s:%s" % (rev, node[:12])
def _get_successor(self, node):
"""Get the successor of the commit represented by its node.
Returns: a tuple containing rev and node"""
hg_log = self.hg_out(
["log"]
+ ["-T", "{rev} {node}\n"]
+ ["--hidden"]
+ ["-r", "successors(%s) and not obsolete()" % node]
)
if not hg_log:
return None, None
# Not sure the best way to handle multiple successors, so just bail out.
if len(hg_log) > 1:
raise Error("Multiple successors found for %s, unable to continue" % node)
return hg_log[0].split(" ", 1)
def refresh_commit_stack(self, commits):
"""Update all commits to point to their superseded commit."""
for commit in commits:
(rev, node) = self._get_successor(commit["node"])
if rev and node:
self._refresh_commit(commit, node, rev)
self.revset = "%s::%s" % (commits[0]["node"], commits[-1]["node"])
super(Mercurial, self).refresh_commit_stack(commits)
def set_args(self, args):
super(Mercurial, self).set_args(args)
# Load hg config into hg_config. We'll specify specific settings on
# the command line when calling hg; all other user settings are ignored.
# Do not parse shell alias extensions.
hg_config = parse_config(
self.hg_out(["config"], never_log=True),
lambda name, value: not (
name.startswith("extensions.") and value.startswith("!")
),
)
safe_options = []
options = []
# Need to use the correct username.
if "ui.username" not in hg_config:
raise Error("ui.username is not configured in your hgrc")
safe_options.extend(["--config", "ui.username=%s" % hg_config["ui.username"]])
# Always need rebase.
options.extend(["--config", "extensions.rebase="])
# Enable evolve if the user's currently using it. evolve makes amending
# commits with children trivial (amongst other things).
ext_evolve = self._get_extension("evolve", hg_config)
if ext_evolve is not None:
safe_options.extend(["--config", "extensions.evolve=%s" % ext_evolve])
self.use_evolve = True
# Otherwise just enable obsolescence markers, and when we're done remove
# the obsstore we created.
else:
options.extend(["--config", "experimental.evolution.createmarkers=true"])
options.extend(["--config", "extensions.strip="])
self.use_evolve = False
self.obsstore = os.path.join(self.path, ".hg", "store", "obsstore")
self.unlink_obsstore = not os.path.exists(self.obsstore)
# This script interacts poorly with mq.
ext_mq = self._get_extension("mq", hg_config)
self.has_mq = ext_mq is not None
if self.has_mq:
safe_options.extend(["--config", "extensions.mq=%s" % ext_mq])
# `shelve` is useful for dealing with uncommitted changes; track if it's
# currently enabled so we can tailor our error accordingly.
self.has_shelve = self._get_extension("shelve", hg_config) is not None
# Disable the user's hgrc file, to ensure we run without rogue extensions.
if self.args.safe_mode or config.safe_mode:
os.environ["HGRCPATH"] = ""
options.extend(safe_options)
self._hg.extend(options)
if hasattr(self.args, "start_rev"):
# Set the default start revision.
if self.args.start_rev == "(auto)":
start = "ancestors(.) and not public() and not obsolete()"
else:
start = self.args.start_rev
# Resolve to nodes as that's nicer to read.
try:
start = self.hg_log(start)[0]
except IndexError:
if self.args.start_rev == "(auto)":
raise Error("Failed to find draft commits to submit")
else:
raise Error(