| 1 |
# phabricator.py - simple Phabricator integration |
| 2 |
# |
| 3 |
# Copyright 2017 Facebook, Inc. |
| 4 |
# |
| 5 |
# This software may be used and distributed according to the terms of the |
| 6 |
# GNU General Public License version 2 or any later version. |
| 7 |
"""simple Phabricator integration (EXPERIMENTAL) |
| 8 |
|
| 9 |
This extension provides a ``phabsend`` command which sends a stack of |
| 10 |
changesets to Phabricator, and a ``phabread`` command which prints a stack of |
| 11 |
revisions in a format suitable for :hg:`import`, and a ``phabupdate`` command |
| 12 |
to update statuses in batch. |
| 13 |
|
| 14 |
A "phabstatus" view for :hg:`show` is also provided; it displays status |
| 15 |
information of Phabricator differentials associated with unfinished |
| 16 |
changesets. |
| 17 |
|
| 18 |
By default, Phabricator requires ``Test Plan`` which might prevent some |
| 19 |
changeset from being sent. The requirement could be disabled by changing |
| 20 |
``differential.require-test-plan-field`` config server side. |
| 21 |
|
| 22 |
Config:: |
| 23 |
|
| 24 |
[phabricator] |
| 25 |
# Phabricator URL |
| 26 |
url = https://phab.example.com/ |
| 27 |
|
| 28 |
# Repo callsign. If a repo has a URL https://$HOST/diffusion/FOO, then its |
| 29 |
# callsign is "FOO". |
| 30 |
callsign = FOO |
| 31 |
|
| 32 |
# curl command to use. If not set (default), use builtin HTTP library to |
| 33 |
# communicate. If set, use the specified curl command. This could be useful |
| 34 |
# if you need to specify advanced options that is not easily supported by |
| 35 |
# the internal library. |
| 36 |
curlcmd = curl --connect-timeout 2 --retry 3 --silent |
| 37 |
|
| 38 |
# retry failed command N time (default 0). Useful when using the extension |
| 39 |
# over flakly connection. |
| 40 |
# |
| 41 |
# We wait `retry.interval` between each retry, in seconds. |
| 42 |
# (default 1 second). |
| 43 |
retry = 3 |
| 44 |
retry.interval = 10 |
| 45 |
|
| 46 |
# the retry option can combine well with the http.timeout one. |
| 47 |
# |
| 48 |
# For example to give up on http request after 20 seconds: |
| 49 |
[http] |
| 50 |
timeout=20 |
| 51 |
|
| 52 |
[auth] |
| 53 |
example.schemes = https |
| 54 |
example.prefix = phab.example.com |
| 55 |
|
| 56 |
# API token. Get it from https://$HOST/conduit/login/ |
| 57 |
example.phabtoken = cli-xxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 58 |
""" |
| 59 |
|
| 60 |
from __future__ import annotations |
| 61 |
|
| 62 |
import base64 |
| 63 |
import contextlib |
| 64 |
import hashlib |
| 65 |
import io |
| 66 |
import itertools |
| 67 |
import json |
| 68 |
import mimetypes |
| 69 |
import operator |
| 70 |
import re |
| 71 |
import time |
| 72 |
import typing |
| 73 |
|
| 74 |
from mercurial.node import bin, short |
| 75 |
from mercurial.i18n import _ |
| 76 |
from mercurial.thirdparty import attr |
| 77 |
|
| 78 |
# Force pytype to use the non-vendored package |
| 79 |
if typing.TYPE_CHECKING: |
| 80 |
# noinspection PyPackageRequirements |
| 81 |
import attr |
| 82 |
|
| 83 |
from mercurial import ( |
| 84 |
cmdutil, |
| 85 |
context, |
| 86 |
copies, |
| 87 |
encoding, |
| 88 |
error, |
| 89 |
exthelper, |
| 90 |
graphmod, |
| 91 |
httpconnection as httpconnectionmod, |
| 92 |
localrepo, |
| 93 |
logcmdutil, |
| 94 |
match, |
| 95 |
mdiff, |
| 96 |
obsutil, |
| 97 |
parser, |
| 98 |
patch, |
| 99 |
phases, |
| 100 |
pycompat, |
| 101 |
rewriteutil, |
| 102 |
scmutil, |
| 103 |
smartset, |
| 104 |
tags, |
| 105 |
templatefilters, |
| 106 |
templateutil, |
| 107 |
url as urlmod, |
| 108 |
util, |
| 109 |
) |
| 110 |
from mercurial.utils import ( |
| 111 |
procutil, |
| 112 |
stringutil, |
| 113 |
urlutil, |
| 114 |
) |
| 115 |
from . import show |
| 116 |
|
| 117 |
|
| 118 |
# Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for |
| 119 |
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should |
| 120 |
# be specifying the version(s) of Mercurial they are tested with, or |
| 121 |
# leave the attribute unspecified. |
| 122 |
testedwith = b'ships-with-hg-core' |
| 123 |
|
| 124 |
eh = exthelper.exthelper() |
| 125 |
|
| 126 |
cmdtable = eh.cmdtable |
| 127 |
command = eh.command |
| 128 |
configtable = eh.configtable |
| 129 |
templatekeyword = eh.templatekeyword |
| 130 |
uisetup = eh.finaluisetup |
| 131 |
|
| 132 |
# developer config: phabricator.batchsize |
| 133 |
eh.configitem( |
| 134 |
b'phabricator', |
| 135 |
b'batchsize', |
| 136 |
default=12, |
| 137 |
) |
| 138 |
eh.configitem( |
| 139 |
b'phabricator', |
| 140 |
b'callsign', |
| 141 |
default=None, |
| 142 |
) |
| 143 |
eh.configitem( |
| 144 |
b'phabricator', |
| 145 |
b'curlcmd', |
| 146 |
default=None, |
| 147 |
) |
| 148 |
# developer config: phabricator.debug |
| 149 |
eh.configitem( |
| 150 |
b'phabricator', |
| 151 |
b'debug', |
| 152 |
default=False, |
| 153 |
) |
| 154 |
# developer config: phabricator.repophid |
| 155 |
eh.configitem( |
| 156 |
b'phabricator', |
| 157 |
b'repophid', |
| 158 |
default=None, |
| 159 |
) |
| 160 |
eh.configitem( |
| 161 |
b'phabricator', |
| 162 |
b'retry', |
| 163 |
default=0, |
| 164 |
) |
| 165 |
eh.configitem( |
| 166 |
b'phabricator', |
| 167 |
b'retry.interval', |
| 168 |
default=1, |
| 169 |
) |
| 170 |
eh.configitem( |
| 171 |
b'phabricator', |
| 172 |
b'url', |
| 173 |
default=None, |
| 174 |
) |
| 175 |
eh.configitem( |
| 176 |
b'phabsend', |
| 177 |
b'confirm', |
| 178 |
default=False, |
| 179 |
) |
| 180 |
eh.configitem( |
| 181 |
b'phabimport', |
| 182 |
b'secret', |
| 183 |
default=False, |
| 184 |
) |
| 185 |
eh.configitem( |
| 186 |
b'phabimport', |
| 187 |
b'obsolete', |
| 188 |
default=False, |
| 189 |
) |
| 190 |
|
| 191 |
colortable = { |
| 192 |
b'phabricator.action.created': b'green', |
| 193 |
b'phabricator.action.skipped': b'magenta', |
| 194 |
b'phabricator.action.updated': b'magenta', |
| 195 |
b'phabricator.drev': b'bold', |
| 196 |
b'phabricator.status.abandoned': b'magenta dim', |
| 197 |
b'phabricator.status.accepted': b'green bold', |
| 198 |
b'phabricator.status.closed': b'green', |
| 199 |
b'phabricator.status.needsreview': b'yellow', |
| 200 |
b'phabricator.status.needsrevision': b'red', |
| 201 |
b'phabricator.status.changesplanned': b'red', |
| 202 |
} |
| 203 |
|
| 204 |
_VCR_FLAGS = [ |
| 205 |
( |
| 206 |
b'', |
| 207 |
b'test-vcr', |
| 208 |
b'', |
| 209 |
_( |
| 210 |
b'Path to a vcr file. If nonexistent, will record a new vcr transcript' |
| 211 |
b', otherwise will mock all http requests using the specified vcr file.' |
| 212 |
b' (ADVANCED)' |
| 213 |
), |
| 214 |
), |
| 215 |
] |
| 216 |
|
| 217 |
|
| 218 |
@eh.wrapfunction(localrepo, "loadhgrc") |
| 219 |
def _loadhgrc(orig, ui, wdirvfs, hgvfs, requirements, *args, **opts): |
| 220 |
"""Load ``.arcconfig`` content into a ui instance on repository open.""" |
| 221 |
result = False |
| 222 |
arcconfig = {} |
| 223 |
|
| 224 |
try: |
| 225 |
# json.loads only accepts bytes from 3.6+ |
| 226 |
rawparams = encoding.unifromlocal(wdirvfs.read(b".arcconfig")) |
| 227 |
# json.loads only returns unicode strings |
| 228 |
arcconfig = pycompat.rapply( |
| 229 |
lambda x: encoding.unitolocal(x) if isinstance(x, str) else x, |
| 230 |
pycompat.json_loads(rawparams), |
| 231 |
) |
| 232 |
|
| 233 |
result = True |
| 234 |
except ValueError: |
| 235 |
ui.warn(_(b"invalid JSON in %s\n") % wdirvfs.join(b".arcconfig")) |
| 236 |
except OSError: |
| 237 |
pass |
| 238 |
|
| 239 |
cfg = util.sortdict() |
| 240 |
|
| 241 |
if b"repository.callsign" in arcconfig: |
| 242 |
cfg[(b"phabricator", b"callsign")] = arcconfig[b"repository.callsign"] |
| 243 |
|
| 244 |
if b"phabricator.uri" in arcconfig: |
| 245 |
cfg[(b"phabricator", b"url")] = arcconfig[b"phabricator.uri"] |
| 246 |
|
| 247 |
if cfg: |
| 248 |
ui.applyconfig(cfg, source=wdirvfs.join(b".arcconfig")) |
| 249 |
|
| 250 |
return ( |
| 251 |
orig(ui, wdirvfs, hgvfs, requirements, *args, **opts) or result |
| 252 |
) # Load .hg/hgrc |
| 253 |
|
| 254 |
|
| 255 |
def vcrcommand(name, flags, spec, helpcategory=None, optionalrepo=False): |
| 256 |
fullflags = flags + _VCR_FLAGS |
| 257 |
|
| 258 |
def hgmatcher(r1, r2): |
| 259 |
if r1.uri != r2.uri or r1.method != r2.method: |
| 260 |
return False |
| 261 |
r1params = util.urlreq.parseqs(r1.body) |
| 262 |
r2params = util.urlreq.parseqs(r2.body) |
| 263 |
for key in r1params: |
| 264 |
if key not in r2params: |
| 265 |
return False |
| 266 |
value = r1params[key][0] |
| 267 |
# we want to compare json payloads without worrying about ordering |
| 268 |
if value.startswith(b'{') and value.endswith(b'}'): |
| 269 |
r1json = pycompat.json_loads(value) |
| 270 |
r2json = pycompat.json_loads(r2params[key][0]) |
| 271 |
if r1json != r2json: |
| 272 |
return False |
| 273 |
elif r2params[key][0] != value: |
| 274 |
return False |
| 275 |
return True |
| 276 |
|
| 277 |
def sanitiserequest(request): |
| 278 |
request.body = re.sub( |
| 279 |
br'cli-[a-z0-9]+', br'cli-hahayouwish', request.body |
| 280 |
) |
| 281 |
return request |
| 282 |
|
| 283 |
def sanitiseresponse(response): |
| 284 |
if 'set-cookie' in response['headers']: |
| 285 |
del response['headers']['set-cookie'] |
| 286 |
return response |
| 287 |
|
| 288 |
def decorate(fn): |
| 289 |
def inner(*args, **kwargs): |
| 290 |
vcr = kwargs.pop('test_vcr') |
| 291 |
if vcr: |
| 292 |
cassette = pycompat.fsdecode(vcr) |
| 293 |
import hgdemandimport |
| 294 |
|
| 295 |
with hgdemandimport.deactivated(): |
| 296 |
# pytype: disable=import-error |
| 297 |
import vcr as vcrmod |
| 298 |
import vcr.stubs as stubs |
| 299 |
|
| 300 |
# pytype: enable=import-error |
| 301 |
|
| 302 |
vcr = vcrmod.VCR( |
| 303 |
serializer='json', |
| 304 |
before_record_request=sanitiserequest, |
| 305 |
before_record_response=sanitiseresponse, |
| 306 |
custom_patches=[ |
| 307 |
( |
| 308 |
urlmod, |
| 309 |
'httpconnection', |
| 310 |
stubs.VCRHTTPConnection, |
| 311 |
), |
| 312 |
( |
| 313 |
urlmod, |
| 314 |
'httpsconnection', |
| 315 |
stubs.VCRHTTPSConnection, |
| 316 |
), |
| 317 |
], |
| 318 |
) |
| 319 |
vcr.register_matcher('hgmatcher', hgmatcher) |
| 320 |
with vcr.use_cassette(cassette, match_on=['hgmatcher']): |
| 321 |
return fn(*args, **kwargs) |
| 322 |
return fn(*args, **kwargs) |
| 323 |
|
| 324 |
cmd = util.checksignature(inner, depth=2) |
| 325 |
cmd.__name__ = fn.__name__ |
| 326 |
cmd.__doc__ = fn.__doc__ |
| 327 |
|
| 328 |
return command( |
| 329 |
name, |
| 330 |
fullflags, |
| 331 |
spec, |
| 332 |
helpcategory=helpcategory, |
| 333 |
optionalrepo=optionalrepo, |
| 334 |
)(cmd) |
| 335 |
|
| 336 |
return decorate |
| 337 |
|
| 338 |
|
| 339 |
def _debug(ui, *msg, **opts): |
| 340 |
"""write debug output for Phabricator if ``phabricator.debug`` is set |
| 341 |
|
| 342 |
Specifically, this avoids dumping Conduit and HTTP auth chatter that is |
| 343 |
printed with the --debug argument. |
| 344 |
""" |
| 345 |
if ui.configbool(b"phabricator", b"debug"): |
| 346 |
flag = ui.debugflag |
| 347 |
try: |
| 348 |
ui.debugflag = True |
| 349 |
ui.write(*msg, **opts) |
| 350 |
finally: |
| 351 |
ui.debugflag = flag |
| 352 |
|
| 353 |
|
| 354 |
def urlencodenested(params): |
| 355 |
"""like urlencode, but works with nested parameters. |
| 356 |
|
| 357 |
For example, if params is {'a': ['b', 'c'], 'd': {'e': 'f'}}, it will be |
| 358 |
flattened to {'a[0]': 'b', 'a[1]': 'c', 'd[e]': 'f'} and then passed to |
| 359 |
urlencode. Note: the encoding is consistent with PHP's http_build_query. |
| 360 |
""" |
| 361 |
flatparams = util.sortdict() |
| 362 |
|
| 363 |
def process(prefix: bytes, obj): |
| 364 |
if isinstance(obj, bool): |
| 365 |
obj = {True: b'true', False: b'false'}[obj] # Python -> PHP form |
| 366 |
lister = lambda l: [(b'%d' % k, v) for k, v in enumerate(l)] |
| 367 |
# .items() will only be called for a dict type |
| 368 |
# pytype: disable=attribute-error |
| 369 |
items = {list: lister, dict: lambda x: x.items()}.get(type(obj)) |
| 370 |
# pytype: enable=attribute-error |
| 371 |
if items is None: |
| 372 |
flatparams[prefix] = obj |
| 373 |
else: |
| 374 |
for k, v in items(obj): |
| 375 |
if prefix: |
| 376 |
process(b'%s[%s]' % (prefix, k), v) |
| 377 |
else: |
| 378 |
process(k, v) |
| 379 |
|
| 380 |
process(b'', params) |
| 381 |
return urlutil.urlreq.urlencode(flatparams) |
| 382 |
|
| 383 |
|
| 384 |
def readurltoken(ui): |
| 385 |
"""return conduit url, token and make sure they exist |
| 386 |
|
| 387 |
Currently read from [auth] config section. In the future, it might |
| 388 |
make sense to read from .arcconfig and .arcrc as well. |
| 389 |
""" |
| 390 |
url = ui.config(b'phabricator', b'url') |
| 391 |
if not url: |
| 392 |
raise error.Abort( |
| 393 |
_(b'config %s.%s is required') % (b'phabricator', b'url') |
| 394 |
) |
| 395 |
|
| 396 |
res = httpconnectionmod.readauthforuri(ui, url, urlutil.url(url).user) |
| 397 |
token = None |
| 398 |
|
| 399 |
if res: |
| 400 |
group, auth = res |
| 401 |
|
| 402 |
ui.debug(b"using auth.%s.* for authentication\n" % group) |
| 403 |
|
| 404 |
token = auth.get(b'phabtoken') |
| 405 |
|
| 406 |
if not token: |
| 407 |
raise error.Abort( |
| 408 |
_(b'Can\'t find conduit token associated to %s') % (url,) |
| 409 |
) |
| 410 |
|
| 411 |
return url, token |
| 412 |
|
| 413 |
|
| 414 |
def callconduit(ui, name, params): |
| 415 |
"""call Conduit API, params is a dict. return json.loads result, or None""" |
| 416 |
host, token = readurltoken(ui) |
| 417 |
url, authinfo = urlutil.url(b'/'.join([host, b'api', name])).authinfo() |
| 418 |
ui.debug(b'Conduit Call: %s %s\n' % (url, pycompat.byterepr(params))) |
| 419 |
params = params.copy() |
| 420 |
params[b'__conduit__'] = { |
| 421 |
b'token': token, |
| 422 |
} |
| 423 |
rawdata = { |
| 424 |
b'params': templatefilters.json(params), |
| 425 |
b'output': b'json', |
| 426 |
b'__conduit__': 1, |
| 427 |
} |
| 428 |
data = urlencodenested(rawdata) |
| 429 |
curlcmd = ui.config(b'phabricator', b'curlcmd') |
| 430 |
if curlcmd: |
| 431 |
sin, sout = procutil.popen2( |
| 432 |
b'%s -d @- %s' % (curlcmd, procutil.shellquote(url)) |
| 433 |
) |
| 434 |
sin.write(data) |
| 435 |
sin.close() |
| 436 |
body = sout.read() |
| 437 |
else: |
| 438 |
urlopener = urlmod.opener(ui, authinfo) |
| 439 |
request = util.urlreq.request(pycompat.strurl(url), data=data) |
| 440 |
max_try = ui.configint(b'phabricator', b'retry') + 1 |
| 441 |
timeout = ui.configwith(float, b'http', b'timeout') |
| 442 |
for try_count in range(max_try): |
| 443 |
try: |
| 444 |
with contextlib.closing( |
| 445 |
urlopener.open(request, timeout=timeout) |
| 446 |
) as rsp: |
| 447 |
body = rsp.read() |
| 448 |
break |
| 449 |
except util.urlerr.urlerror as err: |
| 450 |
if try_count == max_try - 1: |
| 451 |
raise |
| 452 |
ui.debug( |
| 453 |
b'Conduit Request failed (try %d/%d): %r\n' |
| 454 |
% (try_count + 1, max_try, err) |
| 455 |
) |
| 456 |
# failing request might come from overloaded server |
| 457 |
retry_interval = ui.configint(b'phabricator', b'retry.interval') |
| 458 |
time.sleep(retry_interval) |
| 459 |
ui.debug(b'Conduit Response: %s\n' % body) |
| 460 |
parsed = pycompat.rapply( |
| 461 |
lambda x: encoding.unitolocal(x) if isinstance(x, str) else x, |
| 462 |
# json.loads only accepts bytes from py3.6+ |
| 463 |
pycompat.json_loads(encoding.unifromlocal(body)), |
| 464 |
) |
| 465 |
if parsed.get(b'error_code'): |
| 466 |
msg = _(b'Conduit Error (%s): %s') % ( |
| 467 |
parsed[b'error_code'], |
| 468 |
parsed[b'error_info'], |
| 469 |
) |
| 470 |
raise error.Abort(msg) |
| 471 |
return parsed[b'result'] |
| 472 |
|
| 473 |
|
| 474 |
@vcrcommand(b'debugcallconduit', [], _(b'METHOD'), optionalrepo=True) |
| 475 |
def debugcallconduit(ui, repo, name): |
| 476 |
"""call Conduit API |
| 477 |
|
| 478 |
Call parameters are read from stdin as a JSON blob. Result will be written |
| 479 |
to stdout as a JSON blob. |
| 480 |
""" |
| 481 |
# json.loads only accepts bytes from 3.6+ |
| 482 |
rawparams = encoding.unifromlocal(ui.fin.read()) |
| 483 |
# json.loads only returns unicode strings |
| 484 |
params = pycompat.rapply( |
| 485 |
lambda x: encoding.unitolocal(x) if isinstance(x, str) else x, |
| 486 |
pycompat.json_loads(rawparams), |
| 487 |
) |
| 488 |
# json.dumps only accepts unicode strings |
| 489 |
result = pycompat.rapply( |
| 490 |
lambda x: encoding.unifromlocal(x) if isinstance(x, bytes) else x, |
| 491 |
callconduit(ui, name, params), |
| 492 |
) |
| 493 |
s = json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')) |
| 494 |
ui.write(b'%s\n' % encoding.unitolocal(s)) |
| 495 |
|
| 496 |
|
| 497 |
def getrepophid(repo): |
| 498 |
"""given callsign, return repository PHID or None""" |
| 499 |
# developer config: phabricator.repophid |
| 500 |
repophid = repo.ui.config(b'phabricator', b'repophid') |
| 501 |
if repophid: |
| 502 |
return repophid |
| 503 |
callsign = repo.ui.config(b'phabricator', b'callsign') |
| 504 |
if not callsign: |
| 505 |
return None |
| 506 |
query = callconduit( |
| 507 |
repo.ui, |
| 508 |
b'diffusion.repository.search', |
| 509 |
{b'constraints': {b'callsigns': [callsign]}}, |
| 510 |
) |
| 511 |
if len(query[b'data']) == 0: |
| 512 |
return None |
| 513 |
repophid = query[b'data'][0][b'phid'] |
| 514 |
repo.ui.setconfig(b'phabricator', b'repophid', repophid) |
| 515 |
return repophid |
| 516 |
|
| 517 |
|
| 518 |
_differentialrevisiontagre = re.compile(br'\AD([1-9][0-9]*)\Z') |
| 519 |
_differentialrevisiondescre = re.compile( |
| 520 |
br'^Differential Revision:\s*(?P<url>(?:.*)D(?P<id>[1-9][0-9]*))$', re.M |
| 521 |
) |
| 522 |
|
| 523 |
|
| 524 |
def getoldnodedrevmap(repo, nodelist): |
| 525 |
"""find previous nodes that has been sent to Phabricator |
| 526 |
|
| 527 |
return {node: (oldnode, Differential diff, Differential Revision ID)} |
| 528 |
for node in nodelist with known previous sent versions, or associated |
| 529 |
Differential Revision IDs. ``oldnode`` and ``Differential diff`` could |
| 530 |
be ``None``. |
| 531 |
|
| 532 |
Examines commit messages like "Differential Revision:" to get the |
| 533 |
association information. |
| 534 |
|
| 535 |
If such commit message line is not found, examines all precursors and their |
| 536 |
tags. Tags with format like "D1234" are considered a match and the node |
| 537 |
with that tag, and the number after "D" (ex. 1234) will be returned. |
| 538 |
|
| 539 |
The ``old node``, if not None, is guaranteed to be the last diff of |
| 540 |
corresponding Differential Revision, and exist in the repo. |
| 541 |
""" |
| 542 |
unfi = repo.unfiltered() |
| 543 |
has_node = unfi.changelog.index.has_node |
| 544 |
|
| 545 |
result = {} # {node: (oldnode?, lastdiff?, drev)} |
| 546 |
# ordered for test stability when printing new -> old mapping below |
| 547 |
toconfirm = util.sortdict() # {node: (force, {precnode}, drev)} |
| 548 |
for node in nodelist: |
| 549 |
ctx = unfi[node] |
| 550 |
# For tags like "D123", put them into "toconfirm" to verify later |
| 551 |
precnodes = list(obsutil.allpredecessors(unfi.obsstore, [node])) |
| 552 |
for n in precnodes: |
| 553 |
if has_node(n): |
| 554 |
for tag in unfi.nodetags(n): |
| 555 |
m = _differentialrevisiontagre.match(tag) |
| 556 |
if m: |
| 557 |
toconfirm[node] = (0, set(precnodes), int(m.group(1))) |
| 558 |
break |
| 559 |
else: |
| 560 |
continue # move to next predecessor |
| 561 |
break # found a tag, stop |
| 562 |
else: |
| 563 |
# Check commit message |
| 564 |
m = _differentialrevisiondescre.search(ctx.description()) |
| 565 |
if m: |
| 566 |
toconfirm[node] = (1, set(precnodes), int(m.group('id'))) |
| 567 |
|
| 568 |
# Double check if tags are genuine by collecting all old nodes from |
| 569 |
# Phabricator, and expect precursors overlap with it. |
| 570 |
if toconfirm: |
| 571 |
drevs = [drev for force, precs, drev in toconfirm.values()] |
| 572 |
alldiffs = callconduit( |
| 573 |
unfi.ui, b'differential.querydiffs', {b'revisionIDs': drevs} |
| 574 |
) |
| 575 |
|
| 576 |
def getnodes(d, precset): |
| 577 |
# Ignore other nodes that were combined into the Differential |
| 578 |
# that aren't predecessors of the current local node. |
| 579 |
return [n for n in getlocalcommits(d) if n in precset] |
| 580 |
|
| 581 |
for newnode, (force, precset, drev) in toconfirm.items(): |
| 582 |
diffs = [ |
| 583 |
d for d in alldiffs.values() if int(d[b'revisionID']) == drev |
| 584 |
] |
| 585 |
|
| 586 |
# local predecessors known by Phabricator |
| 587 |
phprecset = {n for d in diffs for n in getnodes(d, precset)} |
| 588 |
|
| 589 |
# Ignore if precursors (Phabricator and local repo) do not overlap, |
| 590 |
# and force is not set (when commit message says nothing) |
| 591 |
if not force and not phprecset: |
| 592 |
tagname = b'D%d' % drev |
| 593 |
tags.tag( |
| 594 |
repo, |
| 595 |
tagname, |
| 596 |
repo.nullid, |
| 597 |
message=None, |
| 598 |
user=None, |
| 599 |
date=None, |
| 600 |
local=True, |
| 601 |
) |
| 602 |
unfi.ui.warn( |
| 603 |
_( |
| 604 |
b'D%d: local tag removed - does not match ' |
| 605 |
b'Differential history\n' |
| 606 |
) |
| 607 |
% drev |
| 608 |
) |
| 609 |
continue |
| 610 |
|
| 611 |
# Find the last node using Phabricator metadata, and make sure it |
| 612 |
# exists in the repo |
| 613 |
oldnode = lastdiff = None |
| 614 |
if diffs: |
| 615 |
lastdiff = max(diffs, key=lambda d: int(d[b'id'])) |
| 616 |
oldnodes = getnodes(lastdiff, precset) |
| 617 |
|
| 618 |
_debug( |
| 619 |
unfi.ui, |
| 620 |
b"%s mapped to old nodes %s\n" |
| 621 |
% ( |
| 622 |
short(newnode), |
| 623 |
stringutil.pprint([short(n) for n in sorted(oldnodes)]), |
| 624 |
), |
| 625 |
) |
| 626 |
|
| 627 |
# If this commit was the result of `hg fold` after submission, |
| 628 |
# and now resubmitted with --fold, the easiest thing to do is |
| 629 |
# to leave the node clear. This only results in creating a new |
| 630 |
# diff for the _same_ Differential Revision if this commit is |
| 631 |
# the first or last in the selected range. If we picked a node |
| 632 |
# from the list instead, it would have to be the lowest if at |
| 633 |
# the beginning of the --fold range, or the highest at the end. |
| 634 |
# Otherwise, one or more of the nodes wouldn't be considered in |
| 635 |
# the diff, and the Differential wouldn't be properly updated. |
| 636 |
# If this commit is the result of `hg split` in the same |
| 637 |
# scenario, there is a single oldnode here (and multiple |
| 638 |
# newnodes mapped to it). That makes it the same as the normal |
| 639 |
# case, as the edges of the newnode range cleanly maps to one |
| 640 |
# oldnode each. |
| 641 |
if len(oldnodes) == 1: |
| 642 |
oldnode = oldnodes[0] |
| 643 |
if oldnode and not has_node(oldnode): |
| 644 |
oldnode = None |
| 645 |
|
| 646 |
result[newnode] = (oldnode, lastdiff, drev) |
| 647 |
|
| 648 |
return result |
| 649 |
|
| 650 |
|
| 651 |
def getdrevmap(repo, revs): |
| 652 |
"""Return a dict mapping each rev in `revs` to their Differential Revision |
| 653 |
ID or None. |
| 654 |
""" |
| 655 |
result = {} |
| 656 |
for rev in revs: |
| 657 |
result[rev] = None |
| 658 |
ctx = repo[rev] |
| 659 |
# Check commit message |
| 660 |
m = _differentialrevisiondescre.search(ctx.description()) |
| 661 |
if m: |
| 662 |
result[rev] = int(m.group('id')) |
| 663 |
continue |
| 664 |
# Check tags |
| 665 |
for tag in repo.nodetags(ctx.node()): |
| 666 |
m = _differentialrevisiontagre.match(tag) |
| 667 |
if m: |
| 668 |
result[rev] = int(m.group(1)) |
| 669 |
break |
| 670 |
|
| 671 |
return result |
| 672 |
|
| 673 |
|
| 674 |
def getdiff(basectx, ctx, diffopts): |
| 675 |
"""plain-text diff without header (user, commit message, etc)""" |
| 676 |
output = util.stringio() |
| 677 |
for chunk, _label in patch.diffui( |
| 678 |
ctx.repo(), basectx.p1().node(), ctx.node(), None, opts=diffopts |
| 679 |
): |
| 680 |
output.write(chunk) |
| 681 |
return output.getvalue() |
| 682 |
|
| 683 |
|
| 684 |
class DiffChangeType: |
| 685 |
ADD = 1 |
| 686 |
CHANGE = 2 |
| 687 |
DELETE = 3 |
| 688 |
MOVE_AWAY = 4 |
| 689 |
COPY_AWAY = 5 |
| 690 |
MOVE_HERE = 6 |
| 691 |
COPY_HERE = 7 |
| 692 |
MULTICOPY = 8 |
| 693 |
|
| 694 |
|
| 695 |
class DiffFileType: |
| 696 |
TEXT = 1 |
| 697 |
IMAGE = 2 |
| 698 |
BINARY = 3 |
| 699 |
|
| 700 |
|
| 701 |
@attr.s |
| 702 |
class phabhunk(dict): |
| 703 |
"""Represents a Differential hunk, which is owned by a Differential change""" |
| 704 |
|
| 705 |
oldOffset = attr.ib(default=0) # camelcase-required |
| 706 |
oldLength = attr.ib(default=0) # camelcase-required |
| 707 |
newOffset = attr.ib(default=0) # camelcase-required |
| 708 |
newLength = attr.ib(default=0) # camelcase-required |
| 709 |
corpus = attr.ib(default=b'') |
| 710 |
# These get added to the phabchange's equivalents |
| 711 |
addLines = attr.ib(default=0) # camelcase-required |
| 712 |
delLines = attr.ib(default=0) # camelcase-required |
| 713 |
|
| 714 |
|
| 715 |
@attr.s |
| 716 |
class phabchange: |
| 717 |
"""Represents a Differential change, owns Differential hunks and owned by a |
| 718 |
Differential diff. Each one represents one file in a diff. |
| 719 |
""" |
| 720 |
|
| 721 |
currentPath = attr.ib(default=None) # camelcase-required |
| 722 |
oldPath = attr.ib(default=None) # camelcase-required |
| 723 |
awayPaths = attr.ib(default=attr.Factory(list)) # camelcase-required |
| 724 |
metadata = attr.ib(default=attr.Factory(dict)) |
| 725 |
oldProperties = attr.ib(default=attr.Factory(dict)) # camelcase-required |
| 726 |
newProperties = attr.ib(default=attr.Factory(dict)) # camelcase-required |
| 727 |
type = attr.ib(default=DiffChangeType.CHANGE) |
| 728 |
fileType = attr.ib(default=DiffFileType.TEXT) # camelcase-required |
| 729 |
commitHash = attr.ib(default=None) # camelcase-required |
| 730 |
addLines = attr.ib(default=0) # camelcase-required |
| 731 |
delLines = attr.ib(default=0) # camelcase-required |
| 732 |
hunks = attr.ib(default=attr.Factory(list)) |
| 733 |
|
| 734 |
def copynewmetadatatoold(self): |
| 735 |
for key in list(self.metadata.keys()): |
| 736 |
newkey = key.replace(b'new:', b'old:') |
| 737 |
self.metadata[newkey] = self.metadata[key] |
| 738 |
|
| 739 |
def addoldmode(self, value): |
| 740 |
self.oldProperties[b'unix:filemode'] = value |
| 741 |
|
| 742 |
def addnewmode(self, value): |
| 743 |
self.newProperties[b'unix:filemode'] = value |
| 744 |
|
| 745 |
def addhunk(self, hunk): |
| 746 |
if not isinstance(hunk, phabhunk): |
| 747 |
raise error.Abort(b'phabchange.addhunk only takes phabhunks') |
| 748 |
self.hunks.append(pycompat.byteskwargs(attr.asdict(hunk))) |
| 749 |
# It's useful to include these stats since the Phab web UI shows them, |
| 750 |
# and uses them to estimate how large a change a Revision is. Also used |
| 751 |
# in email subjects for the [+++--] bit. |
| 752 |
self.addLines += hunk.addLines |
| 753 |
self.delLines += hunk.delLines |
| 754 |
|
| 755 |
|
| 756 |
@attr.s |
| 757 |
class phabdiff: |
| 758 |
"""Represents a Differential diff, owns Differential changes. Corresponds |
| 759 |
to a commit. |
| 760 |
""" |
| 761 |
|
| 762 |
# Doesn't seem to be any reason to send this (output of uname -n) |
| 763 |
sourceMachine = attr.ib(default=b'') # camelcase-required |
| 764 |
sourcePath = attr.ib(default=b'/') # camelcase-required |
| 765 |
sourceControlBaseRevision = attr.ib(default=b'0' * 40) # camelcase-required |
| 766 |
sourceControlPath = attr.ib(default=b'/') # camelcase-required |
| 767 |
sourceControlSystem = attr.ib(default=b'hg') # camelcase-required |
| 768 |
branch = attr.ib(default=b'default') |
| 769 |
bookmark = attr.ib(default=None) |
| 770 |
creationMethod = attr.ib(default=b'phabsend') # camelcase-required |
| 771 |
lintStatus = attr.ib(default=b'none') # camelcase-required |
| 772 |
unitStatus = attr.ib(default=b'none') # camelcase-required |
| 773 |
changes = attr.ib(default=attr.Factory(dict)) |
| 774 |
repositoryPHID = attr.ib(default=None) # camelcase-required |
| 775 |
|
| 776 |
def addchange(self, change): |
| 777 |
if not isinstance(change, phabchange): |
| 778 |
raise error.Abort(b'phabdiff.addchange only takes phabchanges') |
| 779 |
self.changes[change.currentPath] = pycompat.byteskwargs( |
| 780 |
attr.asdict(change) |
| 781 |
) |
| 782 |
|
| 783 |
|
| 784 |
def maketext(pchange, basectx, ctx, fname): |
| 785 |
"""populate the phabchange for a text file""" |
| 786 |
repo = ctx.repo() |
| 787 |
fmatcher = match.exact([fname]) |
| 788 |
diffopts = mdiff.diffopts(git=True, context=32767) |
| 789 |
_pfctx, _fctx, header, fhunks = next( |
| 790 |
patch.diffhunks(repo, basectx.p1(), ctx, fmatcher, opts=diffopts) |
| 791 |
) |
| 792 |
|
| 793 |
for fhunk in fhunks: |
| 794 |
(oldOffset, oldLength, newOffset, newLength), lines = fhunk |
| 795 |
corpus = b''.join(lines[1:]) |
| 796 |
shunk = list(header) |
| 797 |
shunk.extend(lines) |
| 798 |
_mf, _mt, addLines, delLines, _hb = patch.diffstatsum( |
| 799 |
patch.diffstatdata(util.iterlines(shunk)) |
| 800 |
) |
| 801 |
pchange.addhunk( |
| 802 |
phabhunk( |
| 803 |
oldOffset, |
| 804 |
oldLength, |
| 805 |
newOffset, |
| 806 |
newLength, |
| 807 |
corpus, |
| 808 |
addLines, |
| 809 |
delLines, |
| 810 |
) |
| 811 |
) |
| 812 |
|
| 813 |
|
| 814 |
def uploadchunks(fctx, fphid): |
| 815 |
"""upload large binary files as separate chunks. |
| 816 |
Phab requests chunking over 8MiB, and splits into 4MiB chunks |
| 817 |
""" |
| 818 |
ui = fctx.repo().ui |
| 819 |
chunks = callconduit(ui, b'file.querychunks', {b'filePHID': fphid}) |
| 820 |
with ui.makeprogress( |
| 821 |
_(b'uploading file chunks'), unit=_(b'chunks'), total=len(chunks) |
| 822 |
) as progress: |
| 823 |
for chunk in chunks: |
| 824 |
progress.increment() |
| 825 |
if chunk[b'complete']: |
| 826 |
continue |
| 827 |
bstart = int(chunk[b'byteStart']) |
| 828 |
bend = int(chunk[b'byteEnd']) |
| 829 |
callconduit( |
| 830 |
ui, |
| 831 |
b'file.uploadchunk', |
| 832 |
{ |
| 833 |
b'filePHID': fphid, |
| 834 |
b'byteStart': bstart, |
| 835 |
b'data': base64.b64encode(fctx.data()[bstart:bend]), |
| 836 |
b'dataEncoding': b'base64', |
| 837 |
}, |
| 838 |
) |
| 839 |
|
| 840 |
|
| 841 |
def uploadfile(fctx): |
| 842 |
"""upload binary files to Phabricator""" |
| 843 |
repo = fctx.repo() |
| 844 |
ui = repo.ui |
| 845 |
fname = fctx.path() |
| 846 |
size = fctx.size() |
| 847 |
fhash = pycompat.bytestr(hashlib.sha256(fctx.data()).hexdigest()) |
| 848 |
|
| 849 |
# an allocate call is required first to see if an upload is even required |
| 850 |
# (Phab might already have it) and to determine if chunking is needed |
| 851 |
allocateparams = { |
| 852 |
b'name': fname, |
| 853 |
b'contentLength': size, |
| 854 |
b'contentHash': fhash, |
| 855 |
} |
| 856 |
filealloc = callconduit(ui, b'file.allocate', allocateparams) |
| 857 |
fphid = filealloc[b'filePHID'] |
| 858 |
|
| 859 |
if filealloc[b'upload']: |
| 860 |
ui.write(_(b'uploading %s\n') % bytes(fctx)) |
| 861 |
if not fphid: |
| 862 |
uploadparams = { |
| 863 |
b'name': fname, |
| 864 |
b'data_base64': base64.b64encode(fctx.data()), |
| 865 |
} |
| 866 |
fphid = callconduit(ui, b'file.upload', uploadparams) |
| 867 |
else: |
| 868 |
uploadchunks(fctx, fphid) |
| 869 |
else: |
| 870 |
ui.debug(b'server already has %s\n' % bytes(fctx)) |
| 871 |
|
| 872 |
if not fphid: |
| 873 |
raise error.Abort(b'Upload of %s failed.' % bytes(fctx)) |
| 874 |
|
| 875 |
return fphid |
| 876 |
|
| 877 |
|
| 878 |
def addoldbinary(pchange, oldfctx, fctx): |
| 879 |
"""add the metadata for the previous version of a binary file to the |
| 880 |
phabchange for the new version |
| 881 |
|
| 882 |
``oldfctx`` is the previous version of the file; ``fctx`` is the new |
| 883 |
version of the file, or None if the file is being removed. |
| 884 |
""" |
| 885 |
if not fctx or fctx.cmp(oldfctx): |
| 886 |
# Files differ, add the old one |
| 887 |
pchange.metadata[b'old:file:size'] = oldfctx.size() |
| 888 |
mimeguess, _enc = mimetypes.guess_type( |
| 889 |
encoding.unifromlocal(oldfctx.path()) |
| 890 |
) |
| 891 |
if mimeguess: |
| 892 |
pchange.metadata[b'old:file:mime-type'] = pycompat.bytestr( |
| 893 |
mimeguess |
| 894 |
) |
| 895 |
fphid = uploadfile(oldfctx) |
| 896 |
pchange.metadata[b'old:binary-phid'] = fphid |
| 897 |
else: |
| 898 |
# If it's left as IMAGE/BINARY web UI might try to display it |
| 899 |
pchange.fileType = DiffFileType.TEXT |
| 900 |
pchange.copynewmetadatatoold() |
| 901 |
|
| 902 |
|
| 903 |
def makebinary(pchange, fctx): |
| 904 |
"""populate the phabchange for a binary file""" |
| 905 |
pchange.fileType = DiffFileType.BINARY |
| 906 |
fphid = uploadfile(fctx) |
| 907 |
pchange.metadata[b'new:binary-phid'] = fphid |
| 908 |
pchange.metadata[b'new:file:size'] = fctx.size() |
| 909 |
mimeguess, _enc = mimetypes.guess_type(encoding.unifromlocal(fctx.path())) |
| 910 |
if mimeguess: |
| 911 |
mimeguess = pycompat.bytestr(mimeguess) |
| 912 |
pchange.metadata[b'new:file:mime-type'] = mimeguess |
| 913 |
if mimeguess.startswith(b'image/'): |
| 914 |
pchange.fileType = DiffFileType.IMAGE |
| 915 |
|
| 916 |
|
| 917 |
# Copied from mercurial/patch.py |
| 918 |
gitmode = {b'l': b'120000', b'x': b'100755', b'': b'100644'} |
| 919 |
|
| 920 |
|
| 921 |
def notutf8(fctx): |
| 922 |
"""detect non-UTF-8 text files since Phabricator requires them to be marked |
| 923 |
as binary |
| 924 |
""" |
| 925 |
try: |
| 926 |
fctx.data().decode('utf-8') |
| 927 |
return False |
| 928 |
except UnicodeDecodeError: |
| 929 |
fctx.repo().ui.write( |
| 930 |
_(b'file %s detected as non-UTF-8, marked as binary\n') |
| 931 |
% fctx.path() |
| 932 |
) |
| 933 |
return True |
| 934 |
|
| 935 |
|
| 936 |
def addremoved(pdiff, basectx, ctx, removed): |
| 937 |
"""add removed files to the phabdiff. Shouldn't include moves""" |
| 938 |
for fname in removed: |
| 939 |
pchange = phabchange( |
| 940 |
currentPath=fname, oldPath=fname, type=DiffChangeType.DELETE |
| 941 |
) |
| 942 |
oldfctx = basectx.p1()[fname] |
| 943 |
pchange.addoldmode(gitmode[oldfctx.flags()]) |
| 944 |
if not (oldfctx.isbinary() or notutf8(oldfctx)): |
| 945 |
maketext(pchange, basectx, ctx, fname) |
| 946 |
|
| 947 |
pdiff.addchange(pchange) |
| 948 |
|
| 949 |
|
| 950 |
def addmodified(pdiff, basectx, ctx, modified): |
| 951 |
"""add modified files to the phabdiff""" |
| 952 |
for fname in modified: |
| 953 |
fctx = ctx[fname] |
| 954 |
oldfctx = basectx.p1()[fname] |
| 955 |
pchange = phabchange(currentPath=fname, oldPath=fname) |
| 956 |
filemode = gitmode[fctx.flags()] |
| 957 |
originalmode = gitmode[oldfctx.flags()] |
| 958 |
if filemode != originalmode: |
| 959 |
pchange.addoldmode(originalmode) |
| 960 |
pchange.addnewmode(filemode) |
| 961 |
|
| 962 |
if ( |
| 963 |
fctx.isbinary() |
| 964 |
or notutf8(fctx) |
| 965 |
or oldfctx.isbinary() |
| 966 |
or notutf8(oldfctx) |
| 967 |
): |
| 968 |
makebinary(pchange, fctx) |
| 969 |
addoldbinary(pchange, oldfctx, fctx) |
| 970 |
else: |
| 971 |
maketext(pchange, basectx, ctx, fname) |
| 972 |
|
| 973 |
pdiff.addchange(pchange) |
| 974 |
|
| 975 |
|
| 976 |
def addadded(pdiff, basectx, ctx, added, removed): |
| 977 |
"""add file adds to the phabdiff, both new files and copies/moves""" |
| 978 |
# Keep track of files that've been recorded as moved/copied, so if there are |
| 979 |
# additional copies we can mark them (moves get removed from removed) |
| 980 |
copiedchanges = {} |
| 981 |
movedchanges = {} |
| 982 |
|
| 983 |
copy = {} |
| 984 |
if basectx != ctx: |
| 985 |
copy = copies.pathcopies(basectx.p1(), ctx) |
| 986 |
|
| 987 |
for fname in added: |
| 988 |
fctx = ctx[fname] |
| 989 |
oldfctx = None |
| 990 |
pchange = phabchange(currentPath=fname) |
| 991 |
|
| 992 |
filemode = gitmode[fctx.flags()] |
| 993 |
|
| 994 |
if copy: |
| 995 |
originalfname = copy.get(fname, fname) |
| 996 |
else: |
| 997 |
originalfname = fname |
| 998 |
if fctx.renamed(): |
| 999 |
originalfname = fctx.renamed()[0] |
| 1000 |
|
| 1001 |
renamed = fname != originalfname |
| 1002 |
|
| 1003 |
if renamed: |
| 1004 |
oldfctx = basectx.p1()[originalfname] |
| 1005 |
originalmode = gitmode[oldfctx.flags()] |
| 1006 |
pchange.oldPath = originalfname |
| 1007 |
|
| 1008 |
if originalfname in removed: |
| 1009 |
origpchange = phabchange( |
| 1010 |
currentPath=originalfname, |
| 1011 |
oldPath=originalfname, |
| 1012 |
type=DiffChangeType.MOVE_AWAY, |
| 1013 |
awayPaths=[fname], |
| 1014 |
) |
| 1015 |
movedchanges[originalfname] = origpchange |
| 1016 |
removed.remove(originalfname) |
| 1017 |
pchange.type = DiffChangeType.MOVE_HERE |
| 1018 |
elif originalfname in movedchanges: |
| 1019 |
movedchanges[originalfname].type = DiffChangeType.MULTICOPY |
| 1020 |
movedchanges[originalfname].awayPaths.append(fname) |
| 1021 |
pchange.type = DiffChangeType.COPY_HERE |
| 1022 |
else: # pure copy |
| 1023 |
if originalfname not in copiedchanges: |
| 1024 |
origpchange = phabchange( |
| 1025 |
currentPath=originalfname, type=DiffChangeType.COPY_AWAY |
| 1026 |
) |
| 1027 |
copiedchanges[originalfname] = origpchange |
| 1028 |
else: |
| 1029 |
origpchange = copiedchanges[originalfname] |
| 1030 |
origpchange.awayPaths.append(fname) |
| 1031 |
pchange.type = DiffChangeType.COPY_HERE |
| 1032 |
|
| 1033 |
if filemode != originalmode: |
| 1034 |
pchange.addoldmode(originalmode) |
| 1035 |
pchange.addnewmode(filemode) |
| 1036 |
else: # Brand-new file |
| 1037 |
pchange.addnewmode(gitmode[fctx.flags()]) |
| 1038 |
pchange.type = DiffChangeType.ADD |
| 1039 |
|
| 1040 |
if ( |
| 1041 |
fctx.isbinary() |
| 1042 |
or notutf8(fctx) |
| 1043 |
or (oldfctx and (oldfctx.isbinary() or notutf8(oldfctx))) |
| 1044 |
): |
| 1045 |
makebinary(pchange, fctx) |
| 1046 |
if renamed: |
| 1047 |
addoldbinary(pchange, oldfctx, fctx) |
| 1048 |
else: |
| 1049 |
maketext(pchange, basectx, ctx, fname) |
| 1050 |
|
| 1051 |
pdiff.addchange(pchange) |
| 1052 |
|
| 1053 |
for _path, copiedchange in copiedchanges.items(): |
| 1054 |
pdiff.addchange(copiedchange) |
| 1055 |
for _path, movedchange in movedchanges.items(): |
| 1056 |
pdiff.addchange(movedchange) |
| 1057 |
|
| 1058 |
|
| 1059 |
def creatediff(basectx, ctx): |
| 1060 |
"""create a Differential Diff""" |
| 1061 |
repo = ctx.repo() |
| 1062 |
repophid = getrepophid(repo) |
| 1063 |
# Create a "Differential Diff" via "differential.creatediff" API |
| 1064 |
pdiff = phabdiff( |
| 1065 |
sourceControlBaseRevision=b'%s' % basectx.p1().hex(), |
| 1066 |
branch=b'%s' % ctx.branch(), |
| 1067 |
) |
| 1068 |
modified, added, removed, _d, _u, _i, _c = basectx.p1().status(ctx) |
| 1069 |
# addadded will remove moved files from removed, so addremoved won't get |
| 1070 |
# them |
| 1071 |
addadded(pdiff, basectx, ctx, added, removed) |
| 1072 |
addmodified(pdiff, basectx, ctx, modified) |
| 1073 |
addremoved(pdiff, basectx, ctx, removed) |
| 1074 |
if repophid: |
| 1075 |
pdiff.repositoryPHID = repophid |
| 1076 |
diff = callconduit( |
| 1077 |
repo.ui, |
| 1078 |
b'differential.creatediff', |
| 1079 |
pycompat.byteskwargs(attr.asdict(pdiff)), |
| 1080 |
) |
| 1081 |
if not diff: |
| 1082 |
if basectx != ctx: |
| 1083 |
msg = _(b'cannot create diff for %s::%s') % (basectx, ctx) |
| 1084 |
else: |
| 1085 |
msg = _(b'cannot create diff for %s') % ctx |
| 1086 |
raise error.Abort(msg) |
| 1087 |
return diff |
| 1088 |
|
| 1089 |
|
| 1090 |
def writediffproperties(ctxs, diff): |
| 1091 |
"""write metadata to diff so patches could be applied losslessly |
| 1092 |
|
| 1093 |
``ctxs`` is the list of commits that created the diff, in ascending order. |
| 1094 |
The list is generally a single commit, but may be several when using |
| 1095 |
``phabsend --fold``. |
| 1096 |
""" |
| 1097 |
# creatediff returns with a diffid but query returns with an id |
| 1098 |
diffid = diff.get(b'diffid', diff.get(b'id')) |
| 1099 |
basectx = ctxs[0] |
| 1100 |
tipctx = ctxs[-1] |
| 1101 |
|
| 1102 |
params = { |
| 1103 |
b'diff_id': diffid, |
| 1104 |
b'name': b'hg:meta', |
| 1105 |
b'data': templatefilters.json( |
| 1106 |
{ |
| 1107 |
b'user': tipctx.user(), |
| 1108 |
b'date': b'%d %d' % tipctx.date(), |
| 1109 |
b'branch': tipctx.branch(), |
| 1110 |
b'node': tipctx.hex(), |
| 1111 |
b'parent': basectx.p1().hex(), |
| 1112 |
} |
| 1113 |
), |
| 1114 |
} |
| 1115 |
callconduit(basectx.repo().ui, b'differential.setdiffproperty', params) |
| 1116 |
|
| 1117 |
commits = {} |
| 1118 |
for ctx in ctxs: |
| 1119 |
commits[ctx.hex()] = { |
| 1120 |
b'author': stringutil.person(ctx.user()), |
| 1121 |
b'authorEmail': stringutil.email(ctx.user()), |
| 1122 |
b'time': int(ctx.date()[0]), |
| 1123 |
b'commit': ctx.hex(), |
| 1124 |
b'parents': [ctx.p1().hex()], |
| 1125 |
b'branch': ctx.branch(), |
| 1126 |
} |
| 1127 |
params = { |
| 1128 |
b'diff_id': diffid, |
| 1129 |
b'name': b'local:commits', |
| 1130 |
b'data': templatefilters.json(commits), |
| 1131 |
} |
| 1132 |
callconduit(basectx.repo().ui, b'differential.setdiffproperty', params) |
| 1133 |
|
| 1134 |
|
| 1135 |
def createdifferentialrevision( |
| 1136 |
ctxs, |
| 1137 |
revid=None, |
| 1138 |
parentrevphid=None, |
| 1139 |
oldbasenode=None, |
| 1140 |
oldnode=None, |
| 1141 |
olddiff=None, |
| 1142 |
actions=None, |
| 1143 |
comment=None, |
| 1144 |
): |
| 1145 |
"""create or update a Differential Revision |
| 1146 |
|
| 1147 |
If revid is None, create a new Differential Revision, otherwise update |
| 1148 |
revid. If parentrevphid is not None, set it as a dependency. |
| 1149 |
|
| 1150 |
If there is a single commit for the new Differential Revision, ``ctxs`` will |
| 1151 |
be a list of that single context. Otherwise, it is a list that covers the |
| 1152 |
range of changes for the differential, where ``ctxs[0]`` is the first change |
| 1153 |
to include and ``ctxs[-1]`` is the last. |
| 1154 |
|
| 1155 |
If oldnode is not None, check if the patch content (without commit message |
| 1156 |
and metadata) has changed before creating another diff. For a Revision with |
| 1157 |
a single commit, ``oldbasenode`` and ``oldnode`` have the same value. For a |
| 1158 |
Revision covering multiple commits, ``oldbasenode`` corresponds to |
| 1159 |
``ctxs[0]`` the previous time this Revision was posted, and ``oldnode`` |
| 1160 |
corresponds to ``ctxs[-1]``. |
| 1161 |
|
| 1162 |
If actions is not None, they will be appended to the transaction. |
| 1163 |
""" |
| 1164 |
ctx = ctxs[-1] |
| 1165 |
basectx = ctxs[0] |
| 1166 |
|
| 1167 |
repo = ctx.repo() |
| 1168 |
if oldnode: |
| 1169 |
diffopts = mdiff.diffopts(git=True, context=32767) |
| 1170 |
unfi = repo.unfiltered() |
| 1171 |
oldctx = unfi[oldnode] |
| 1172 |
oldbasectx = unfi[oldbasenode] |
| 1173 |
neednewdiff = getdiff(basectx, ctx, diffopts) != getdiff( |
| 1174 |
oldbasectx, oldctx, diffopts |
| 1175 |
) |
| 1176 |
else: |
| 1177 |
neednewdiff = True |
| 1178 |
|
| 1179 |
transactions = [] |
| 1180 |
if neednewdiff: |
| 1181 |
diff = creatediff(basectx, ctx) |
| 1182 |
transactions.append({b'type': b'update', b'value': diff[b'phid']}) |
| 1183 |
if comment: |
| 1184 |
transactions.append({b'type': b'comment', b'value': comment}) |
| 1185 |
else: |
| 1186 |
# Even if we don't need to upload a new diff because the patch content |
| 1187 |
# does not change. We might still need to update its metadata so |
| 1188 |
# pushers could know the correct node metadata. |
| 1189 |
assert olddiff |
| 1190 |
diff = olddiff |
| 1191 |
writediffproperties(ctxs, diff) |
| 1192 |
|
| 1193 |
# Set the parent Revision every time, so commit re-ordering is picked-up |
| 1194 |
if parentrevphid: |
| 1195 |
transactions.append( |
| 1196 |
{b'type': b'parents.set', b'value': [parentrevphid]} |
| 1197 |
) |
| 1198 |
|
| 1199 |
if actions: |
| 1200 |
transactions += actions |
| 1201 |
|
| 1202 |
# When folding multiple local commits into a single review, arcanist will |
| 1203 |
# take the summary line of the first commit as the title, and then |
| 1204 |
# concatenate the rest of the remaining messages (including each of their |
| 1205 |
# first lines) to the rest of the first commit message (each separated by |
| 1206 |
# an empty line), and use that as the summary field. Do the same here. |
| 1207 |
# For commits with only a one line message, there is no summary field, as |
| 1208 |
# this gets assigned to the title. |
| 1209 |
fields = util.sortdict() # sorted for stable wire protocol in tests |
| 1210 |
|
| 1211 |
for i, _ctx in enumerate(ctxs): |
| 1212 |
# Parse commit message and update related fields. |
| 1213 |
desc = _ctx.description() |
| 1214 |
info = callconduit( |
| 1215 |
repo.ui, b'differential.parsecommitmessage', {b'corpus': desc} |
| 1216 |
) |
| 1217 |
|
| 1218 |
for k in [b'title', b'summary', b'testPlan']: |
| 1219 |
v = info[b'fields'].get(k) |
| 1220 |
if not v: |
| 1221 |
continue |
| 1222 |
|
| 1223 |
if i == 0: |
| 1224 |
# Title, summary and test plan (if present) are taken verbatim |
| 1225 |
# for the first commit. |
| 1226 |
fields[k] = v.rstrip() |
| 1227 |
continue |
| 1228 |
elif k == b'title': |
| 1229 |
# Add subsequent titles (i.e. the first line of the commit |
| 1230 |
# message) back to the summary. |
| 1231 |
k = b'summary' |
| 1232 |
|
| 1233 |
# Append any current field to the existing composite field |
| 1234 |
fields[k] = b'\n\n'.join(filter(None, [fields.get(k), v.rstrip()])) |
| 1235 |
|
| 1236 |
for k, v in fields.items(): |
| 1237 |
transactions.append({b'type': k, b'value': v}) |
| 1238 |
|
| 1239 |
params = {b'transactions': transactions} |
| 1240 |
if revid is not None: |
| 1241 |
# Update an existing Differential Revision |
| 1242 |
params[b'objectIdentifier'] = revid |
| 1243 |
|
| 1244 |
revision = callconduit(repo.ui, b'differential.revision.edit', params) |
| 1245 |
if not revision: |
| 1246 |
if len(ctxs) == 1: |
| 1247 |
msg = _(b'cannot create revision for %s') % ctx |
| 1248 |
else: |
| 1249 |
msg = _(b'cannot create revision for %s::%s') % (basectx, ctx) |
| 1250 |
raise error.Abort(msg) |
| 1251 |
|
| 1252 |
return revision, diff |
| 1253 |
|
| 1254 |
|
| 1255 |
def userphids(ui, names): |
| 1256 |
"""convert user names to PHIDs""" |
| 1257 |
names = [name.lower() for name in names] |
| 1258 |
query = {b'constraints': {b'usernames': names}} |
| 1259 |
result = callconduit(ui, b'user.search', query) |
| 1260 |
# username not found is not an error of the API. So check if we have missed |
| 1261 |
# some names here. |
| 1262 |
data = result[b'data'] |
| 1263 |
resolved = {entry[b'fields'][b'username'].lower() for entry in data} |
| 1264 |
unresolved = set(names) - resolved |
| 1265 |
if unresolved: |
| 1266 |
raise error.Abort( |
| 1267 |
_(b'unknown username: %s') % b' '.join(sorted(unresolved)) |
| 1268 |
) |
| 1269 |
return [entry[b'phid'] for entry in data] |
| 1270 |
|
| 1271 |
|
| 1272 |
def _print_phabsend_action(ui, ctx, newrevid, action): |
| 1273 |
"""print the ``action`` that occurred when posting ``ctx`` for review |
| 1274 |
|
| 1275 |
This is a utility function for the sending phase of ``phabsend``, which |
| 1276 |
makes it easier to show a status for all local commits with `--fold``. |
| 1277 |
""" |
| 1278 |
actiondesc = ui.label( |
| 1279 |
{ |
| 1280 |
b'created': _(b'created'), |
| 1281 |
b'skipped': _(b'skipped'), |
| 1282 |
b'updated': _(b'updated'), |
| 1283 |
}[action], |
| 1284 |
b'phabricator.action.%s' % action, |
| 1285 |
) |
| 1286 |
drevdesc = ui.label(b'D%d' % newrevid, b'phabricator.drev') |
| 1287 |
summary = cmdutil.format_changeset_summary(ui, ctx, b'phabsend') |
| 1288 |
ui.write(_(b'%s - %s - %s\n') % (drevdesc, actiondesc, summary)) |
| 1289 |
|
| 1290 |
|
| 1291 |
def _amend_diff_properties(unfi, drevid, newnodes, diff): |
| 1292 |
"""update the local commit list for the ``diff`` associated with ``drevid`` |
| 1293 |
|
| 1294 |
This is a utility function for the amend phase of ``phabsend``, which |
| 1295 |
converts failures to warning messages. |
| 1296 |
""" |
| 1297 |
_debug( |
| 1298 |
unfi.ui, |
| 1299 |
b"new commits: %s\n" % stringutil.pprint([short(n) for n in newnodes]), |
| 1300 |
) |
| 1301 |
|
| 1302 |
try: |
| 1303 |
writediffproperties([unfi[newnode] for newnode in newnodes], diff) |
| 1304 |
except util.urlerr.urlerror: |
| 1305 |
# If it fails just warn and keep going, otherwise the DREV |
| 1306 |
# associations will be lost |
| 1307 |
unfi.ui.warnnoi18n(b'Failed to update metadata for D%d\n' % drevid) |
| 1308 |
|
| 1309 |
|
| 1310 |
@vcrcommand( |
| 1311 |
b'phabsend', |
| 1312 |
[ |
| 1313 |
(b'r', b'rev', [], _(b'revisions to send'), _(b'REV')), |
| 1314 |
(b'', b'amend', True, _(b'update commit messages')), |
| 1315 |
(b'', b'reviewer', [], _(b'specify reviewers')), |
| 1316 |
(b'', b'blocker', [], _(b'specify blocking reviewers')), |
| 1317 |
( |
| 1318 |
b'm', |
| 1319 |
b'comment', |
| 1320 |
b'', |
| 1321 |
_(b'add a comment to Revisions with new/updated Diffs'), |
| 1322 |
), |
| 1323 |
(b'', b'confirm', None, _(b'ask for confirmation before sending')), |
| 1324 |
(b'', b'fold', False, _(b'combine the revisions into one review')), |
| 1325 |
], |
| 1326 |
_(b'REV [OPTIONS]'), |
| 1327 |
helpcategory=command.CATEGORY_IMPORT_EXPORT, |
| 1328 |
) |
| 1329 |
def phabsend(ui, repo, *revs, **opts): |
| 1330 |
"""upload changesets to Phabricator |
| 1331 |
|
| 1332 |
If there are multiple revisions specified, they will be send as a stack |
| 1333 |
with a linear dependencies relationship using the order specified by the |
| 1334 |
revset. |
| 1335 |
|
| 1336 |
For the first time uploading changesets, local tags will be created to |
| 1337 |
maintain the association. After the first time, phabsend will check |
| 1338 |
obsstore and tags information so it can figure out whether to update an |
| 1339 |
existing Differential Revision, or create a new one. |
| 1340 |
|
| 1341 |
If --amend is set, update commit messages so they have the |
| 1342 |
``Differential Revision`` URL, remove related tags. This is similar to what |
| 1343 |
arcanist will do, and is more desired in author-push workflows. Otherwise, |
| 1344 |
use local tags to record the ``Differential Revision`` association. |
| 1345 |
|
| 1346 |
The --confirm option lets you confirm changesets before sending them. You |
| 1347 |
can also add following to your configuration file to make it default |
| 1348 |
behaviour:: |
| 1349 |
|
| 1350 |
[phabsend] |
| 1351 |
confirm = true |
| 1352 |
|
| 1353 |
By default, a separate review will be created for each commit that is |
| 1354 |
selected, and will have the same parent/child relationship in Phabricator. |
| 1355 |
If ``--fold`` is set, multiple commits are rolled up into a single review |
| 1356 |
as if diffed from the parent of the first revision to the last. The commit |
| 1357 |
messages are concatenated in the summary field on Phabricator. |
| 1358 |
|
| 1359 |
phabsend will check obsstore and the above association to decide whether to |
| 1360 |
update an existing Differential Revision, or create a new one. |
| 1361 |
""" |
| 1362 |
opts = pycompat.byteskwargs(opts) |
| 1363 |
revs = list(revs) + opts.get(b'rev', []) |
| 1364 |
revs = logcmdutil.revrange(repo, revs) |
| 1365 |
revs.sort() # ascending order to preserve topological parent/child in phab |
| 1366 |
|
| 1367 |
if not revs: |
| 1368 |
raise error.Abort(_(b'phabsend requires at least one changeset')) |
| 1369 |
if opts.get(b'amend'): |
| 1370 |
cmdutil.checkunfinished(repo) |
| 1371 |
|
| 1372 |
ctxs = [repo[rev] for rev in revs] |
| 1373 |
|
| 1374 |
if any(c for c in ctxs if c.obsolete()): |
| 1375 |
raise error.Abort(_(b"obsolete commits cannot be posted for review")) |
| 1376 |
|
| 1377 |
# Ensure the local commits are an unbroken range. The semantics of the |
| 1378 |
# --fold option implies this, and the auto restacking of orphans requires |
| 1379 |
# it. Otherwise A+C in A->B->C will cause B to be orphaned, and C' to |
| 1380 |
# get A' as a parent. |
| 1381 |
def _fail_nonlinear_revs(revs, revtype): |
| 1382 |
badnodes = [repo[r].node() for r in revs] |
| 1383 |
raise error.Abort( |
| 1384 |
_(b"cannot phabsend multiple %s revisions: %s") |
| 1385 |
% (revtype, scmutil.nodesummaries(repo, badnodes)), |
| 1386 |
hint=_(b"the revisions must form a linear chain"), |
| 1387 |
) |
| 1388 |
|
| 1389 |
heads = repo.revs(b'heads(%ld)', revs) |
| 1390 |
if len(heads) > 1: |
| 1391 |
_fail_nonlinear_revs(heads, b"head") |
| 1392 |
|
| 1393 |
roots = repo.revs(b'roots(%ld)', revs) |
| 1394 |
if len(roots) > 1: |
| 1395 |
_fail_nonlinear_revs(roots, b"root") |
| 1396 |
|
| 1397 |
fold = opts.get(b'fold') |
| 1398 |
if fold: |
| 1399 |
if len(revs) == 1: |
| 1400 |
# TODO: just switch to --no-fold instead? |
| 1401 |
raise error.Abort(_(b"cannot fold a single revision")) |
| 1402 |
|
| 1403 |
# There's no clear way to manage multiple commits with a Dxxx tag, so |
| 1404 |
# require the amend option. (We could append "_nnn", but then it |
| 1405 |
# becomes jumbled if earlier commits are added to an update.) It should |
| 1406 |
# lock the repo and ensure that the range is editable, but that would |
| 1407 |
# make the code pretty convoluted. The default behavior of `arc` is to |
| 1408 |
# create a new review anyway. |
| 1409 |
if not opts.get(b"amend"): |
| 1410 |
raise error.Abort(_(b"cannot fold with --no-amend")) |
| 1411 |
|
| 1412 |
# It might be possible to bucketize the revisions by the DREV value, and |
| 1413 |
# iterate over those groups when posting, and then again when amending. |
| 1414 |
# But for simplicity, require all selected revisions to be for the same |
| 1415 |
# DREV (if present). Adding local revisions to an existing DREV is |
| 1416 |
# acceptable. |
| 1417 |
drevmatchers = [ |
| 1418 |
_differentialrevisiondescre.search(ctx.description()) |
| 1419 |
for ctx in ctxs |
| 1420 |
] |
| 1421 |
if len({m.group('url') for m in drevmatchers if m}) > 1: |
| 1422 |
raise error.Abort( |
| 1423 |
_(b"cannot fold revisions with different DREV values") |
| 1424 |
) |
| 1425 |
|
| 1426 |
# {newnode: (oldnode, olddiff, olddrev} |
| 1427 |
oldmap = getoldnodedrevmap(repo, [repo[r].node() for r in revs]) |
| 1428 |
|
| 1429 |
confirm = ui.configbool(b'phabsend', b'confirm') |
| 1430 |
confirm |= bool(opts.get(b'confirm')) |
| 1431 |
if confirm: |
| 1432 |
confirmed = _confirmbeforesend(repo, revs, oldmap) |
| 1433 |
if not confirmed: |
| 1434 |
raise error.Abort(_(b'phabsend cancelled')) |
| 1435 |
|
| 1436 |
actions = [] |
| 1437 |
reviewers = opts.get(b'reviewer', []) |
| 1438 |
blockers = opts.get(b'blocker', []) |
| 1439 |
phids = [] |
| 1440 |
if reviewers: |
| 1441 |
phids.extend(userphids(repo.ui, reviewers)) |
| 1442 |
if blockers: |
| 1443 |
phids.extend( |
| 1444 |
map( |
| 1445 |
lambda phid: b'blocking(%s)' % phid, |
| 1446 |
userphids(repo.ui, blockers), |
| 1447 |
) |
| 1448 |
) |
| 1449 |
if phids: |
| 1450 |
actions.append({b'type': b'reviewers.add', b'value': phids}) |
| 1451 |
|
| 1452 |
drevids = [] # [int] |
| 1453 |
diffmap = {} # {newnode: diff} |
| 1454 |
|
| 1455 |
# Send patches one by one so we know their Differential Revision PHIDs and |
| 1456 |
# can provide dependency relationship |
| 1457 |
lastrevphid = None |
| 1458 |
for ctx in ctxs: |
| 1459 |
if fold: |
| 1460 |
ui.debug(b'sending rev %d::%d\n' % (ctx.rev(), ctxs[-1].rev())) |
| 1461 |
else: |
| 1462 |
ui.debug(b'sending rev %d\n' % ctx.rev()) |
| 1463 |
|
| 1464 |
# Get Differential Revision ID |
| 1465 |
oldnode, olddiff, revid = oldmap.get(ctx.node(), (None, None, None)) |
| 1466 |
oldbasenode, oldbasediff, oldbaserevid = oldnode, olddiff, revid |
| 1467 |
|
| 1468 |
if fold: |
| 1469 |
oldbasenode, oldbasediff, oldbaserevid = oldmap.get( |
| 1470 |
ctxs[-1].node(), (None, None, None) |
| 1471 |
) |
| 1472 |
|
| 1473 |
if oldnode != ctx.node() or opts.get(b'amend'): |
| 1474 |
# Create or update Differential Revision |
| 1475 |
revision, diff = createdifferentialrevision( |
| 1476 |
ctxs if fold else [ctx], |
| 1477 |
revid, |
| 1478 |
lastrevphid, |
| 1479 |
oldbasenode, |
| 1480 |
oldnode, |
| 1481 |
olddiff, |
| 1482 |
actions, |
| 1483 |
opts.get(b'comment'), |
| 1484 |
) |
| 1485 |
|
| 1486 |
if fold: |
| 1487 |
for ctx in ctxs: |
| 1488 |
diffmap[ctx.node()] = diff |
| 1489 |
else: |
| 1490 |
diffmap[ctx.node()] = diff |
| 1491 |
|
| 1492 |
newrevid = int(revision[b'object'][b'id']) |
| 1493 |
newrevphid = revision[b'object'][b'phid'] |
| 1494 |
if revid: |
| 1495 |
action = b'updated' |
| 1496 |
else: |
| 1497 |
action = b'created' |
| 1498 |
|
| 1499 |
# Create a local tag to note the association, if commit message |
| 1500 |
# does not have it already |
| 1501 |
if not fold: |
| 1502 |
m = _differentialrevisiondescre.search(ctx.description()) |
| 1503 |
if not m or int(m.group('id')) != newrevid: |
| 1504 |
tagname = b'D%d' % newrevid |
| 1505 |
tags.tag( |
| 1506 |
repo, |
| 1507 |
tagname, |
| 1508 |
ctx.node(), |
| 1509 |
message=None, |
| 1510 |
user=None, |
| 1511 |
date=None, |
| 1512 |
local=True, |
| 1513 |
) |
| 1514 |
else: |
| 1515 |
# Nothing changed. But still set "newrevphid" so the next revision |
| 1516 |
# could depend on this one and "newrevid" for the summary line. |
| 1517 |
newrevphid = querydrev(repo.ui, b'%d' % revid)[0][b'phid'] |
| 1518 |
newrevid = revid |
| 1519 |
action = b'skipped' |
| 1520 |
|
| 1521 |
drevids.append(newrevid) |
| 1522 |
lastrevphid = newrevphid |
| 1523 |
|
| 1524 |
if fold: |
| 1525 |
for c in ctxs: |
| 1526 |
if oldmap.get(c.node(), (None, None, None))[2]: |
| 1527 |
action = b'updated' |
| 1528 |
else: |
| 1529 |
action = b'created' |
| 1530 |
_print_phabsend_action(ui, c, newrevid, action) |
| 1531 |
break |
| 1532 |
|
| 1533 |
_print_phabsend_action(ui, ctx, newrevid, action) |
| 1534 |
|
| 1535 |
# Update commit messages and remove tags |
| 1536 |
if opts.get(b'amend'): |
| 1537 |
unfi = repo.unfiltered() |
| 1538 |
drevs = callconduit(ui, b'differential.query', {b'ids': drevids}) |
| 1539 |
with repo.wlock(), repo.lock(), repo.transaction(b'phabsend'): |
| 1540 |
# Eagerly evaluate commits to restabilize before creating new |
| 1541 |
# commits. The selected revisions are excluded because they are |
| 1542 |
# automatically restacked as part of the submission process. |
| 1543 |
restack = [ |
| 1544 |
c |
| 1545 |
for c in repo.set( |
| 1546 |
b"(%ld::) - (%ld) - unstable() - obsolete() - public()", |
| 1547 |
revs, |
| 1548 |
revs, |
| 1549 |
) |
| 1550 |
] |
| 1551 |
wnode = unfi[b'.'].node() |
| 1552 |
mapping = {} # {oldnode: [newnode]} |
| 1553 |
newnodes = [] |
| 1554 |
|
| 1555 |
drevid = drevids[0] |
| 1556 |
|
| 1557 |
for i, rev in enumerate(revs): |
| 1558 |
old = unfi[rev] |
| 1559 |
if not fold: |
| 1560 |
drevid = drevids[i] |
| 1561 |
drev = [d for d in drevs if int(d[b'id']) == drevid][0] |
| 1562 |
|
| 1563 |
newdesc = get_amended_desc(drev, old, fold) |
| 1564 |
# Make sure commit message contain "Differential Revision" |
| 1565 |
if ( |
| 1566 |
old.description() != newdesc |
| 1567 |
or old.p1().node() in mapping |
| 1568 |
or old.p2().node() in mapping |
| 1569 |
): |
| 1570 |
if old.phase() == phases.public: |
| 1571 |
ui.warn( |
| 1572 |
_(b"warning: not updating public commit %s\n") |
| 1573 |
% scmutil.formatchangeid(old) |
| 1574 |
) |
| 1575 |
continue |
| 1576 |
parents = [ |
| 1577 |
mapping.get(old.p1().node(), (old.p1(),))[0], |
| 1578 |
mapping.get(old.p2().node(), (old.p2(),))[0], |
| 1579 |
] |
| 1580 |
newdesc = rewriteutil.update_hash_refs( |
| 1581 |
repo, |
| 1582 |
newdesc, |
| 1583 |
mapping, |
| 1584 |
) |
| 1585 |
new = context.metadataonlyctx( |
| 1586 |
repo, |
| 1587 |
old, |
| 1588 |
parents=parents, |
| 1589 |
text=newdesc, |
| 1590 |
user=old.user(), |
| 1591 |
date=old.date(), |
| 1592 |
extra=old.extra(), |
| 1593 |
) |
| 1594 |
|
| 1595 |
newnode = new.commit() |
| 1596 |
|
| 1597 |
mapping[old.node()] = [newnode] |
| 1598 |
|
| 1599 |
if fold: |
| 1600 |
# Defer updating the (single) Diff until all nodes are |
| 1601 |
# collected. No tags were created, so none need to be |
| 1602 |
# removed. |
| 1603 |
newnodes.append(newnode) |
| 1604 |
continue |
| 1605 |
|
| 1606 |
_amend_diff_properties( |
| 1607 |
unfi, drevid, [newnode], diffmap[old.node()] |
| 1608 |
) |
| 1609 |
|
| 1610 |
# Remove local tags since it's no longer necessary |
| 1611 |
tagname = b'D%d' % drevid |
| 1612 |
if tagname in repo.tags(): |
| 1613 |
tags.tag( |
| 1614 |
repo, |
| 1615 |
tagname, |
| 1616 |
repo.nullid, |
| 1617 |
message=None, |
| 1618 |
user=None, |
| 1619 |
date=None, |
| 1620 |
local=True, |
| 1621 |
) |
| 1622 |
elif fold: |
| 1623 |
# When folding multiple commits into one review with |
| 1624 |
# --fold, track even the commits that weren't amended, so |
| 1625 |
# that their association isn't lost if the properties are |
| 1626 |
# rewritten below. |
| 1627 |
newnodes.append(old.node()) |
| 1628 |
|
| 1629 |
# If the submitted commits are public, no amend takes place so |
| 1630 |
# there are no newnodes and therefore no diff update to do. |
| 1631 |
if fold and newnodes: |
| 1632 |
diff = diffmap[old.node()] |
| 1633 |
|
| 1634 |
# The diff object in diffmap doesn't have the local commits |
| 1635 |
# because that could be returned from differential.creatediff, |
| 1636 |
# not differential.querydiffs. So use the queried diff (if |
| 1637 |
# present), or force the amend (a new revision is being posted.) |
| 1638 |
if not olddiff or set(newnodes) != getlocalcommits(olddiff): |
| 1639 |
_debug(ui, b"updating local commit list for D%d\n" % drevid) |
| 1640 |
_amend_diff_properties(unfi, drevid, newnodes, diff) |
| 1641 |
else: |
| 1642 |
_debug( |
| 1643 |
ui, |
| 1644 |
b"local commit list for D%d is already up-to-date\n" |
| 1645 |
% drevid, |
| 1646 |
) |
| 1647 |
elif fold: |
| 1648 |
_debug(ui, b"no newnodes to update\n") |
| 1649 |
|
| 1650 |
# Restack any children of first-time submissions that were orphaned |
| 1651 |
# in the process. The ctx won't report that it is an orphan until |
| 1652 |
# the cleanup takes place below. |
| 1653 |
for old in restack: |
| 1654 |
parents = [ |
| 1655 |
mapping.get(old.p1().node(), (old.p1(),))[0], |
| 1656 |
mapping.get(old.p2().node(), (old.p2(),))[0], |
| 1657 |
] |
| 1658 |
new = context.metadataonlyctx( |
| 1659 |
repo, |
| 1660 |
old, |
| 1661 |
parents=parents, |
| 1662 |
text=rewriteutil.update_hash_refs( |
| 1663 |
repo, old.description(), mapping |
| 1664 |
), |
| 1665 |
user=old.user(), |
| 1666 |
date=old.date(), |
| 1667 |
extra=old.extra(), |
| 1668 |
) |
| 1669 |
|
| 1670 |
newnode = new.commit() |
| 1671 |
|
| 1672 |
# Don't obsolete unselected descendants of nodes that have not |
| 1673 |
# been changed in this transaction- that results in an error. |
| 1674 |
if newnode != old.node(): |
| 1675 |
mapping[old.node()] = [newnode] |
| 1676 |
_debug( |
| 1677 |
ui, |
| 1678 |
b"restabilizing %s as %s\n" |
| 1679 |
% (short(old.node()), short(newnode)), |
| 1680 |
) |
| 1681 |
else: |
| 1682 |
_debug( |
| 1683 |
ui, |
| 1684 |
b"not restabilizing unchanged %s\n" % short(old.node()), |
| 1685 |
) |
| 1686 |
|
| 1687 |
cmdutil.cleanup_nodes(repo, mapping, b'phabsend', fixphase=True) |
| 1688 |
if wnode in mapping: |
| 1689 |
unfi.setparents(mapping[wnode][0]) |
| 1690 |
|
| 1691 |
|
| 1692 |
# Map from "hg:meta" keys to header understood by "hg import". The order is |
| 1693 |
# consistent with "hg export" output. |
| 1694 |
_metanamemap: util.sortdict[bytes, bytes] = util.sortdict( |
| 1695 |
[ |
| 1696 |
(b'user', b'User'), |
| 1697 |
(b'date', b'Date'), |
| 1698 |
(b'branch', b'Branch'), |
| 1699 |
(b'node', b'Node ID'), |
| 1700 |
(b'parent', b'Parent '), |
| 1701 |
] |
| 1702 |
) |
| 1703 |
|
| 1704 |
|
| 1705 |
def _confirmbeforesend(repo, revs, oldmap): |
| 1706 |
url, token = readurltoken(repo.ui) |
| 1707 |
ui = repo.ui |
| 1708 |
for rev in revs: |
| 1709 |
ctx = repo[rev] |
| 1710 |
oldnode, olddiff, drevid = oldmap.get(ctx.node(), (None, None, None)) |
| 1711 |
if drevid: |
| 1712 |
drevdesc = ui.label(b'D%d' % drevid, b'phabricator.drev') |
| 1713 |
else: |
| 1714 |
drevdesc = ui.label(_(b'NEW'), b'phabricator.drev') |
| 1715 |
|
| 1716 |
ui.write( |
| 1717 |
_(b'%s - %s\n') |
| 1718 |
% ( |
| 1719 |
drevdesc, |
| 1720 |
cmdutil.format_changeset_summary(ui, ctx, b'phabsend'), |
| 1721 |
) |
| 1722 |
) |
| 1723 |
|
| 1724 |
if ui.promptchoice( |
| 1725 |
_(b'Send the above changes to %s (Y/n)?$$ &Yes $$ &No') % url |
| 1726 |
): |
| 1727 |
return False |
| 1728 |
|
| 1729 |
return True |
| 1730 |
|
| 1731 |
|
| 1732 |
_knownstatusnames = { |
| 1733 |
b'accepted', |
| 1734 |
b'needsreview', |
| 1735 |
b'needsrevision', |
| 1736 |
b'closed', |
| 1737 |
b'abandoned', |
| 1738 |
b'changesplanned', |
| 1739 |
} |
| 1740 |
|
| 1741 |
|
| 1742 |
def _getstatusname(drev): |
| 1743 |
"""get normalized status name from a Differential Revision""" |
| 1744 |
return drev[b'statusName'].replace(b' ', b'').lower() |
| 1745 |
|
| 1746 |
|
| 1747 |
# Small language to specify differential revisions. Support symbols: (), :X, |
| 1748 |
# +, and -. |
| 1749 |
|
| 1750 |
_elements = { |
| 1751 |
# token-type: binding-strength, primary, prefix, infix, suffix |
| 1752 |
b'(': (12, None, (b'group', 1, b')'), None, None), |
| 1753 |
b':': (8, None, (b'ancestors', 8), None, None), |
| 1754 |
b'&': (5, None, None, (b'and_', 5), None), |
| 1755 |
b'+': (4, None, None, (b'add', 4), None), |
| 1756 |
b'-': (4, None, None, (b'sub', 4), None), |
| 1757 |
b')': (0, None, None, None, None), |
| 1758 |
b'symbol': (0, b'symbol', None, None, None), |
| 1759 |
b'end': (0, None, None, None, None), |
| 1760 |
} |
| 1761 |
|
| 1762 |
|
| 1763 |
def _tokenize(text): |
| 1764 |
view = memoryview(text) # zero-copy slice |
| 1765 |
special = b'():+-& ' |
| 1766 |
pos = 0 |
| 1767 |
length = len(text) |
| 1768 |
while pos < length: |
| 1769 |
symbol = b''.join( |
| 1770 |
itertools.takewhile( |
| 1771 |
lambda ch: ch not in special, pycompat.iterbytestr(view[pos:]) |
| 1772 |
) |
| 1773 |
) |
| 1774 |
if symbol: |
| 1775 |
yield (b'symbol', symbol, pos) |
| 1776 |
pos += len(symbol) |
| 1777 |
else: # special char, ignore space |
| 1778 |
if text[pos : pos + 1] != b' ': |
| 1779 |
yield (text[pos : pos + 1], None, pos) |
| 1780 |
pos += 1 |
| 1781 |
yield (b'end', None, pos) |
| 1782 |
|
| 1783 |
|
| 1784 |
def _parse(text): |
| 1785 |
tree, pos = parser.parser(_elements).parse(_tokenize(text)) |
| 1786 |
if pos != len(text): |
| 1787 |
raise error.ParseError(b'invalid token', pos) |
| 1788 |
return tree |
| 1789 |
|
| 1790 |
|
| 1791 |
def _parsedrev(symbol): |
| 1792 |
"""str -> int or None, ex. 'D45' -> 45; '12' -> 12; 'x' -> None""" |
| 1793 |
if symbol.startswith(b'D') and symbol[1:].isdigit(): |
| 1794 |
return int(symbol[1:]) |
| 1795 |
if symbol.isdigit(): |
| 1796 |
return int(symbol) |
| 1797 |
|
| 1798 |
|
| 1799 |
def _prefetchdrevs(tree): |
| 1800 |
"""return ({single-drev-id}, {ancestor-drev-id}) to prefetch""" |
| 1801 |
drevs = set() |
| 1802 |
ancestordrevs = set() |
| 1803 |
op = tree[0] |
| 1804 |
if op == b'symbol': |
| 1805 |
r = _parsedrev(tree[1]) |
| 1806 |
if r: |
| 1807 |
drevs.add(r) |
| 1808 |
elif op == b'ancestors': |
| 1809 |
r, a = _prefetchdrevs(tree[1]) |
| 1810 |
drevs.update(r) |
| 1811 |
ancestordrevs.update(r) |
| 1812 |
ancestordrevs.update(a) |
| 1813 |
else: |
| 1814 |
for t in tree[1:]: |
| 1815 |
r, a = _prefetchdrevs(t) |
| 1816 |
drevs.update(r) |
| 1817 |
ancestordrevs.update(a) |
| 1818 |
return drevs, ancestordrevs |
| 1819 |
|
| 1820 |
|
| 1821 |
def querydrev(ui, spec): |
| 1822 |
"""return a list of "Differential Revision" dicts |
| 1823 |
|
| 1824 |
spec is a string using a simple query language, see docstring in phabread |
| 1825 |
for details. |
| 1826 |
|
| 1827 |
A "Differential Revision dict" looks like: |
| 1828 |
|
| 1829 |
{ |
| 1830 |
"activeDiffPHID": "PHID-DIFF-xoqnjkobbm6k4dk6hi72", |
| 1831 |
"authorPHID": "PHID-USER-tv3ohwc4v4jeu34otlye", |
| 1832 |
"auxiliary": { |
| 1833 |
"phabricator:depends-on": [ |
| 1834 |
"PHID-DREV-gbapp366kutjebt7agcd" |
| 1835 |
] |
| 1836 |
"phabricator:projects": [], |
| 1837 |
}, |
| 1838 |
"branch": "default", |
| 1839 |
"ccs": [], |
| 1840 |
"commits": [], |
| 1841 |
"dateCreated": "1499181406", |
| 1842 |
"dateModified": "1499182103", |
| 1843 |
"diffs": [ |
| 1844 |
"3", |
| 1845 |
"4", |
| 1846 |
], |
| 1847 |
"hashes": [], |
| 1848 |
"id": "2", |
| 1849 |
"lineCount": "2", |
| 1850 |
"phid": "PHID-DREV-672qvysjcczopag46qty", |
| 1851 |
"properties": {}, |
| 1852 |
"repositoryPHID": "PHID-REPO-hub2hx62ieuqeheznasv", |
| 1853 |
"reviewers": [], |
| 1854 |
"sourcePath": null |
| 1855 |
"status": "0", |
| 1856 |
"statusName": "Needs Review", |
| 1857 |
"summary": "", |
| 1858 |
"testPlan": "", |
| 1859 |
"title": "example", |
| 1860 |
"uri": "https://phab.example.com/D2", |
| 1861 |
} |
| 1862 |
""" |
| 1863 |
# TODO: replace differential.query and differential.querydiffs with |
| 1864 |
# differential.diff.search because the former (and their output) are |
| 1865 |
# frozen, and planned to be deprecated and removed. |
| 1866 |
|
| 1867 |
def fetch(params): |
| 1868 |
"""params -> single drev or None""" |
| 1869 |
key = (params.get(b'ids') or params.get(b'phids') or [None])[0] |
| 1870 |
if key in prefetched: |
| 1871 |
return prefetched[key] |
| 1872 |
drevs = callconduit(ui, b'differential.query', params) |
| 1873 |
# Fill prefetched with the result |
| 1874 |
for drev in drevs: |
| 1875 |
prefetched[drev[b'phid']] = drev |
| 1876 |
prefetched[int(drev[b'id'])] = drev |
| 1877 |
if key not in prefetched: |
| 1878 |
raise error.Abort( |
| 1879 |
_(b'cannot get Differential Revision %r') % params |
| 1880 |
) |
| 1881 |
return prefetched[key] |
| 1882 |
|
| 1883 |
def getstack(topdrevids): |
| 1884 |
"""given a top, get a stack from the bottom, [id] -> [id]""" |
| 1885 |
visited = set() |
| 1886 |
result = [] |
| 1887 |
queue = [{b'ids': [i]} for i in topdrevids] |
| 1888 |
while queue: |
| 1889 |
params = queue.pop() |
| 1890 |
drev = fetch(params) |
| 1891 |
if drev[b'id'] in visited: |
| 1892 |
continue |
| 1893 |
visited.add(drev[b'id']) |
| 1894 |
result.append(int(drev[b'id'])) |
| 1895 |
auxiliary = drev.get(b'auxiliary', {}) |
| 1896 |
depends = auxiliary.get(b'phabricator:depends-on', []) |
| 1897 |
for phid in depends: |
| 1898 |
queue.append({b'phids': [phid]}) |
| 1899 |
result.reverse() |
| 1900 |
return smartset.baseset(result) |
| 1901 |
|
| 1902 |
# Initialize prefetch cache |
| 1903 |
prefetched = {} # {id or phid: drev} |
| 1904 |
|
| 1905 |
tree = _parse(spec) |
| 1906 |
drevs, ancestordrevs = _prefetchdrevs(tree) |
| 1907 |
|
| 1908 |
# developer config: phabricator.batchsize |
| 1909 |
batchsize = ui.configint(b'phabricator', b'batchsize') |
| 1910 |
|
| 1911 |
# Prefetch Differential Revisions in batch |
| 1912 |
tofetch = set(drevs) |
| 1913 |
for r in ancestordrevs: |
| 1914 |
tofetch.update(range(max(1, r - batchsize), r + 1)) |
| 1915 |
if drevs: |
| 1916 |
fetch({b'ids': list(tofetch)}) |
| 1917 |
validids = sorted(set(getstack(list(ancestordrevs))) | set(drevs)) |
| 1918 |
|
| 1919 |
# Walk through the tree, return smartsets |
| 1920 |
def walk(tree): |
| 1921 |
op = tree[0] |
| 1922 |
if op == b'symbol': |
| 1923 |
drev = _parsedrev(tree[1]) |
| 1924 |
if drev: |
| 1925 |
return smartset.baseset([drev]) |
| 1926 |
elif tree[1] in _knownstatusnames: |
| 1927 |
drevs = [ |
| 1928 |
r |
| 1929 |
for r in validids |
| 1930 |
if _getstatusname(prefetched[r]) == tree[1] |
| 1931 |
] |
| 1932 |
return smartset.baseset(drevs) |
| 1933 |
else: |
| 1934 |
raise error.Abort(_(b'unknown symbol: %s') % tree[1]) |
| 1935 |
elif op in {b'and_', b'add', b'sub'}: |
| 1936 |
assert len(tree) == 3 |
| 1937 |
return getattr(operator, pycompat.sysstr(op))( |
| 1938 |
walk(tree[1]), walk(tree[2]) |
| 1939 |
) |
| 1940 |
elif op == b'group': |
| 1941 |
return walk(tree[1]) |
| 1942 |
elif op == b'ancestors': |
| 1943 |
return getstack(walk(tree[1])) |
| 1944 |
else: |
| 1945 |
raise error.ProgrammingError(b'illegal tree: %r' % tree) |
| 1946 |
|
| 1947 |
return [prefetched[r] for r in walk(tree)] |
| 1948 |
|
| 1949 |
|
| 1950 |
def getdescfromdrev(drev): |
| 1951 |
"""get description (commit message) from "Differential Revision" |
| 1952 |
|
| 1953 |
This is similar to differential.getcommitmessage API. But we only care |
| 1954 |
about limited fields: title, summary, test plan, and URL. |
| 1955 |
""" |
| 1956 |
title = drev[b'title'] |
| 1957 |
summary = drev[b'summary'].rstrip() |
| 1958 |
testplan = drev[b'testPlan'].rstrip() |
| 1959 |
if testplan: |
| 1960 |
testplan = b'Test Plan:\n%s' % testplan |
| 1961 |
uri = b'Differential Revision: %s' % drev[b'uri'] |
| 1962 |
return b'\n\n'.join(filter(None, [title, summary, testplan, uri])) |
| 1963 |
|
| 1964 |
|
| 1965 |
def get_amended_desc(drev, ctx, folded): |
| 1966 |
"""similar to ``getdescfromdrev``, but supports a folded series of commits |
| 1967 |
|
| 1968 |
This is used when determining if an individual commit needs to have its |
| 1969 |
message amended after posting it for review. The determination is made for |
| 1970 |
each individual commit, even when they were folded into one review. |
| 1971 |
""" |
| 1972 |
if not folded: |
| 1973 |
return getdescfromdrev(drev) |
| 1974 |
|
| 1975 |
uri = b'Differential Revision: %s' % drev[b'uri'] |
| 1976 |
|
| 1977 |
# Since the commit messages were combined when posting multiple commits |
| 1978 |
# with --fold, the fields can't be read from Phabricator here, or *all* |
| 1979 |
# affected local revisions will end up with the same commit message after |
| 1980 |
# the URI is amended in. Append in the DREV line, or update it if it |
| 1981 |
# exists. At worst, this means commit message or test plan updates on |
| 1982 |
# Phabricator aren't propagated back to the repository, but that seems |
| 1983 |
# reasonable for the case where local commits are effectively combined |
| 1984 |
# in Phabricator. |
| 1985 |
m = _differentialrevisiondescre.search(ctx.description()) |
| 1986 |
if not m: |
| 1987 |
return b'\n\n'.join([ctx.description(), uri]) |
| 1988 |
|
| 1989 |
return _differentialrevisiondescre.sub(uri, ctx.description()) |
| 1990 |
|
| 1991 |
|
| 1992 |
def getlocalcommits(diff): |
| 1993 |
"""get the set of local commits from a diff object |
| 1994 |
|
| 1995 |
See ``getdiffmeta()`` for an example diff object. |
| 1996 |
""" |
| 1997 |
props = diff.get(b'properties') or {} |
| 1998 |
commits = props.get(b'local:commits') or {} |
| 1999 |
if len(commits) > 1: |
| 2000 |
return {bin(c) for c in commits.keys()} |
| 2001 |
|
| 2002 |
# Storing the diff metadata predates storing `local:commits`, so continue |
| 2003 |
# to use that in the --no-fold case. |
| 2004 |
return {bin(getdiffmeta(diff).get(b'node', b'')) or None} |
| 2005 |
|
| 2006 |
|
| 2007 |
def getdiffmeta(diff): |
| 2008 |
"""get commit metadata (date, node, user, p1) from a diff object |
| 2009 |
|
| 2010 |
The metadata could be "hg:meta", sent by phabsend, like: |
| 2011 |
|
| 2012 |
"properties": { |
| 2013 |
"hg:meta": { |
| 2014 |
"branch": "default", |
| 2015 |
"date": "1499571514 25200", |
| 2016 |
"node": "98c08acae292b2faf60a279b4189beb6cff1414d", |
| 2017 |
"user": "Foo Bar <[email protected]>", |
| 2018 |
"parent": "6d0abad76b30e4724a37ab8721d630394070fe16" |
| 2019 |
} |
| 2020 |
} |
| 2021 |
|
| 2022 |
Or converted from "local:commits", sent by "arc", like: |
| 2023 |
|
| 2024 |
"properties": { |
| 2025 |
"local:commits": { |
| 2026 |
"98c08acae292b2faf60a279b4189beb6cff1414d": { |
| 2027 |
"author": "Foo Bar", |
| 2028 |
"authorEmail": "[email protected]" |
| 2029 |
"branch": "default", |
| 2030 |
"commit": "98c08acae292b2faf60a279b4189beb6cff1414d", |
| 2031 |
"local": "1000", |
| 2032 |
"message": "...", |
| 2033 |
"parents": ["6d0abad76b30e4724a37ab8721d630394070fe16"], |
| 2034 |
"rev": "98c08acae292b2faf60a279b4189beb6cff1414d", |
| 2035 |
"summary": "...", |
| 2036 |
"tag": "", |
| 2037 |
"time": 1499546314, |
| 2038 |
} |
| 2039 |
} |
| 2040 |
} |
| 2041 |
|
| 2042 |
Note: metadata extracted from "local:commits" will lose time zone |
| 2043 |
information. |
| 2044 |
""" |
| 2045 |
props = diff.get(b'properties') or {} |
| 2046 |
meta = props.get(b'hg:meta') |
| 2047 |
if not meta: |
| 2048 |
if props.get(b'local:commits'): |
| 2049 |
commit = sorted(props[b'local:commits'].values())[0] |
| 2050 |
meta = {} |
| 2051 |
if b'author' in commit and b'authorEmail' in commit: |
| 2052 |
meta[b'user'] = b'%s <%s>' % ( |
| 2053 |
commit[b'author'], |
| 2054 |
commit[b'authorEmail'], |
| 2055 |
) |
| 2056 |
if b'time' in commit: |
| 2057 |
meta[b'date'] = b'%d 0' % int(commit[b'time']) |
| 2058 |
if b'branch' in commit: |
| 2059 |
meta[b'branch'] = commit[b'branch'] |
| 2060 |
node = commit.get(b'commit', commit.get(b'rev')) |
| 2061 |
if node: |
| 2062 |
meta[b'node'] = node |
| 2063 |
if len(commit.get(b'parents', ())) >= 1: |
| 2064 |
meta[b'parent'] = commit[b'parents'][0] |
| 2065 |
else: |
| 2066 |
meta = {} |
| 2067 |
if b'date' not in meta and b'dateCreated' in diff: |
| 2068 |
meta[b'date'] = b'%s 0' % diff[b'dateCreated'] |
| 2069 |
if b'branch' not in meta and diff.get(b'branch'): |
| 2070 |
meta[b'branch'] = diff[b'branch'] |
| 2071 |
if b'parent' not in meta and diff.get(b'sourceControlBaseRevision'): |
| 2072 |
meta[b'parent'] = diff[b'sourceControlBaseRevision'] |
| 2073 |
return meta |
| 2074 |
|
| 2075 |
|
| 2076 |
def _getdrevs(ui, stack, specs): |
| 2077 |
"""convert user supplied DREVSPECs into "Differential Revision" dicts |
| 2078 |
|
| 2079 |
See ``hg help phabread`` for how to specify each DREVSPEC. |
| 2080 |
""" |
| 2081 |
if len(specs) > 0: |
| 2082 |
|
| 2083 |
def _formatspec(s): |
| 2084 |
if stack: |
| 2085 |
s = b':(%s)' % s |
| 2086 |
return b'(%s)' % s |
| 2087 |
|
| 2088 |
spec = b'+'.join(pycompat.maplist(_formatspec, specs)) |
| 2089 |
|
| 2090 |
drevs = querydrev(ui, spec) |
| 2091 |
if drevs: |
| 2092 |
return drevs |
| 2093 |
|
| 2094 |
raise error.Abort(_(b"empty DREVSPEC set")) |
| 2095 |
|
| 2096 |
|
| 2097 |
def readpatch(ui, drevs, write): |
| 2098 |
"""generate plain-text patch readable by 'hg import' |
| 2099 |
|
| 2100 |
write takes a list of (DREV, bytes), where DREV is the differential number |
| 2101 |
(as bytes, without the "D" prefix) and the bytes are the text of a patch |
| 2102 |
to be imported. drevs is what "querydrev" returns, results of |
| 2103 |
"differential.query". |
| 2104 |
""" |
| 2105 |
# Prefetch hg:meta property for all diffs |
| 2106 |
diffids = sorted({max(int(v) for v in drev[b'diffs']) for drev in drevs}) |
| 2107 |
diffs = callconduit(ui, b'differential.querydiffs', {b'ids': diffids}) |
| 2108 |
|
| 2109 |
patches = [] |
| 2110 |
|
| 2111 |
# Generate patch for each drev |
| 2112 |
for drev in drevs: |
| 2113 |
ui.note(_(b'reading D%s\n') % drev[b'id']) |
| 2114 |
|
| 2115 |
diffid = max(int(v) for v in drev[b'diffs']) |
| 2116 |
body = callconduit(ui, b'differential.getrawdiff', {b'diffID': diffid}) |
| 2117 |
desc = getdescfromdrev(drev) |
| 2118 |
header = b'# HG changeset patch\n' |
| 2119 |
|
| 2120 |
# Try to preserve metadata from hg:meta property. Write hg patch |
| 2121 |
# headers that can be read by the "import" command. See patchheadermap |
| 2122 |
# and extract in mercurial/patch.py for supported headers. |
| 2123 |
meta = getdiffmeta(diffs[b'%d' % diffid]) |
| 2124 |
for k in _metanamemap.keys(): |
| 2125 |
if k in meta: |
| 2126 |
header += b'# %s %s\n' % (_metanamemap[k], meta[k]) |
| 2127 |
|
| 2128 |
content = b'%s%s\n%s' % (header, desc, body) |
| 2129 |
patches.append((drev[b'id'], content)) |
| 2130 |
|
| 2131 |
# Write patches to the supplied callback |
| 2132 |
write(patches) |
| 2133 |
|
| 2134 |
|
| 2135 |
@vcrcommand( |
| 2136 |
b'phabread', |
| 2137 |
[(b'', b'stack', False, _(b'read dependencies'))], |
| 2138 |
_(b'DREVSPEC... [OPTIONS]'), |
| 2139 |
helpcategory=command.CATEGORY_IMPORT_EXPORT, |
| 2140 |
optionalrepo=True, |
| 2141 |
) |
| 2142 |
def phabread(ui, repo, *specs, **opts): |
| 2143 |
"""print patches from Phabricator suitable for importing |
| 2144 |
|
| 2145 |
DREVSPEC could be a Differential Revision identity, like ``D123``, or just |
| 2146 |
the number ``123``. It could also have common operators like ``+``, ``-``, |
| 2147 |
``&``, ``(``, ``)`` for complex queries. Prefix ``:`` could be used to |
| 2148 |
select a stack. If multiple DREVSPEC values are given, the result is the |
| 2149 |
union of each individually evaluated value. No attempt is currently made |
| 2150 |
to reorder the values to run from parent to child. |
| 2151 |
|
| 2152 |
``abandoned``, ``accepted``, ``closed``, ``needsreview``, ``needsrevision`` |
| 2153 |
could be used to filter patches by status. For performance reason, they |
| 2154 |
only represent a subset of non-status selections and cannot be used alone. |
| 2155 |
|
| 2156 |
For example, ``:D6+8-(2+D4)`` selects a stack up to D6, plus D8 and exclude |
| 2157 |
D2 and D4. ``:D9 & needsreview`` selects "Needs Review" revisions in a |
| 2158 |
stack up to D9. |
| 2159 |
|
| 2160 |
If --stack is given, follow dependencies information and read all patches. |
| 2161 |
It is equivalent to the ``:`` operator. |
| 2162 |
""" |
| 2163 |
opts = pycompat.byteskwargs(opts) |
| 2164 |
drevs = _getdrevs(ui, opts.get(b'stack'), specs) |
| 2165 |
|
| 2166 |
def _write(patches): |
| 2167 |
for drev, content in patches: |
| 2168 |
ui.write(content) |
| 2169 |
|
| 2170 |
readpatch(ui, drevs, _write) |
| 2171 |
|
| 2172 |
|
| 2173 |
@vcrcommand( |
| 2174 |
b'phabimport', |
| 2175 |
[(b'', b'stack', False, _(b'import dependencies as well'))], |
| 2176 |
_(b'DREVSPEC... [OPTIONS]'), |
| 2177 |
helpcategory=command.CATEGORY_IMPORT_EXPORT, |
| 2178 |
) |
| 2179 |
def phabimport(ui, repo, *specs, **opts): |
| 2180 |
"""import patches from Phabricator for the specified Differential Revisions |
| 2181 |
|
| 2182 |
The patches are read and applied starting at the parent of the working |
| 2183 |
directory. |
| 2184 |
|
| 2185 |
See ``hg help phabread`` for how to specify DREVSPEC. |
| 2186 |
""" |
| 2187 |
opts = pycompat.byteskwargs(opts) |
| 2188 |
|
| 2189 |
# --bypass avoids losing exec and symlink bits when importing on Windows, |
| 2190 |
# and allows importing with a dirty wdir. It also aborts instead of leaving |
| 2191 |
# rejects. |
| 2192 |
opts[b'bypass'] = True |
| 2193 |
|
| 2194 |
# Mandatory default values, synced with commands.import |
| 2195 |
opts[b'strip'] = 1 |
| 2196 |
opts[b'prefix'] = b'' |
| 2197 |
# Evolve 9.3.0 assumes this key is present in cmdutil.tryimportone() |
| 2198 |
opts[b'obsolete'] = False |
| 2199 |
|
| 2200 |
if ui.configbool(b'phabimport', b'secret'): |
| 2201 |
opts[b'secret'] = True |
| 2202 |
if ui.configbool(b'phabimport', b'obsolete'): |
| 2203 |
opts[b'obsolete'] = True # Handled by evolve wrapping tryimportone() |
| 2204 |
|
| 2205 |
def _write(patches): |
| 2206 |
parents = repo[None].parents() |
| 2207 |
|
| 2208 |
with repo.wlock(), repo.lock(), repo.transaction(b'phabimport'): |
| 2209 |
for drev, contents in patches: |
| 2210 |
ui.status(_(b'applying patch from D%s\n') % drev) |
| 2211 |
|
| 2212 |
with patch.extract(ui, io.BytesIO(contents)) as patchdata: |
| 2213 |
msg, node, rej = cmdutil.tryimportone( |
| 2214 |
ui, |
| 2215 |
repo, |
| 2216 |
patchdata, |
| 2217 |
parents, |
| 2218 |
opts, |
| 2219 |
[], |
| 2220 |
None, # Never update wdir to another revision |
| 2221 |
) |
| 2222 |
|
| 2223 |
if not node: |
| 2224 |
raise error.Abort(_(b'D%s: no diffs found') % drev) |
| 2225 |
|
| 2226 |
ui.note(msg + b'\n') |
| 2227 |
parents = [repo[node]] |
| 2228 |
|
| 2229 |
drevs = _getdrevs(ui, opts.get(b'stack'), specs) |
| 2230 |
|
| 2231 |
readpatch(repo.ui, drevs, _write) |
| 2232 |
|
| 2233 |
|
| 2234 |
@vcrcommand( |
| 2235 |
b'phabupdate', |
| 2236 |
[ |
| 2237 |
(b'', b'accept', False, _(b'accept revisions')), |
| 2238 |
(b'', b'reject', False, _(b'reject revisions')), |
| 2239 |
(b'', b'request-review', False, _(b'request review on revisions')), |
| 2240 |
(b'', b'abandon', False, _(b'abandon revisions')), |
| 2241 |
(b'', b'reclaim', False, _(b'reclaim revisions')), |
| 2242 |
(b'', b'close', False, _(b'close revisions')), |
| 2243 |
(b'', b'reopen', False, _(b'reopen revisions')), |
| 2244 |
(b'', b'plan-changes', False, _(b'plan changes for revisions')), |
| 2245 |
(b'', b'resign', False, _(b'resign as a reviewer from revisions')), |
| 2246 |
(b'', b'commandeer', False, _(b'commandeer revisions')), |
| 2247 |
(b'm', b'comment', b'', _(b'comment on the last revision')), |
| 2248 |
(b'r', b'rev', b'', _(b'local revision to update'), _(b'REV')), |
| 2249 |
], |
| 2250 |
_(b'[DREVSPEC...| -r REV...] [OPTIONS]'), |
| 2251 |
helpcategory=command.CATEGORY_IMPORT_EXPORT, |
| 2252 |
optionalrepo=True, |
| 2253 |
) |
| 2254 |
def phabupdate(ui, repo, *specs, **opts): |
| 2255 |
"""update Differential Revision in batch |
| 2256 |
|
| 2257 |
DREVSPEC selects revisions. See :hg:`help phabread` for its usage. |
| 2258 |
""" |
| 2259 |
opts = pycompat.byteskwargs(opts) |
| 2260 |
transactions = [ |
| 2261 |
b'abandon', |
| 2262 |
b'accept', |
| 2263 |
b'close', |
| 2264 |
b'commandeer', |
| 2265 |
b'plan-changes', |
| 2266 |
b'reclaim', |
| 2267 |
b'reject', |
| 2268 |
b'reopen', |
| 2269 |
b'request-review', |
| 2270 |
b'resign', |
| 2271 |
] |
| 2272 |
flags = [n for n in transactions if opts.get(n.replace(b'-', b'_'))] |
| 2273 |
if len(flags) > 1: |
| 2274 |
raise error.Abort(_(b'%s cannot be used together') % b', '.join(flags)) |
| 2275 |
|
| 2276 |
actions = [] |
| 2277 |
for f in flags: |
| 2278 |
actions.append({b'type': f, b'value': True}) |
| 2279 |
|
| 2280 |
revs = opts.get(b'rev') |
| 2281 |
if revs: |
| 2282 |
if not repo: |
| 2283 |
raise error.InputError(_(b'--rev requires a repository')) |
| 2284 |
|
| 2285 |
if specs: |
| 2286 |
raise error.InputError(_(b'cannot specify both DREVSPEC and --rev')) |
| 2287 |
|
| 2288 |
drevmap = getdrevmap(repo, logcmdutil.revrange(repo, [revs])) |
| 2289 |
specs = [] |
| 2290 |
unknown = [] |
| 2291 |
for r, d in drevmap.items(): |
| 2292 |
if d is None: |
| 2293 |
unknown.append(repo[r]) |
| 2294 |
else: |
| 2295 |
specs.append(b'D%d' % d) |
| 2296 |
if unknown: |
| 2297 |
raise error.InputError( |
| 2298 |
_(b'selected revisions without a Differential: %s') |
| 2299 |
% scmutil.nodesummaries(repo, unknown) |
| 2300 |
) |
| 2301 |
|
| 2302 |
drevs = _getdrevs(ui, opts.get(b'stack'), specs) |
| 2303 |
for i, drev in enumerate(drevs): |
| 2304 |
if i + 1 == len(drevs) and opts.get(b'comment'): |
| 2305 |
actions.append({b'type': b'comment', b'value': opts[b'comment']}) |
| 2306 |
if actions: |
| 2307 |
params = { |
| 2308 |
b'objectIdentifier': drev[b'phid'], |
| 2309 |
b'transactions': actions, |
| 2310 |
} |
| 2311 |
callconduit(ui, b'differential.revision.edit', params) |
| 2312 |
|
| 2313 |
|
| 2314 |
@eh.templatekeyword(b'phabreview', requires={b'ctx'}) |
| 2315 |
def template_review(context, mapping): |
| 2316 |
""":phabreview: Object describing the review for this changeset. |
| 2317 |
Has attributes `url` and `id`. |
| 2318 |
""" |
| 2319 |
ctx = context.resource(mapping, b'ctx') |
| 2320 |
m = _differentialrevisiondescre.search(ctx.description()) |
| 2321 |
if m: |
| 2322 |
return templateutil.hybriddict( |
| 2323 |
{ |
| 2324 |
b'url': m.group('url'), |
| 2325 |
b'id': b"D%s" % m.group('id'), |
| 2326 |
} |
| 2327 |
) |
| 2328 |
else: |
| 2329 |
tags = ctx.repo().nodetags(ctx.node()) |
| 2330 |
for t in tags: |
| 2331 |
if _differentialrevisiontagre.match(t): |
| 2332 |
url = ctx.repo().ui.config(b'phabricator', b'url') |
| 2333 |
if not url.endswith(b'/'): |
| 2334 |
url += b'/' |
| 2335 |
url += t |
| 2336 |
|
| 2337 |
return templateutil.hybriddict( |
| 2338 |
{ |
| 2339 |
b'url': url, |
| 2340 |
b'id': t, |
| 2341 |
} |
| 2342 |
) |
| 2343 |
return None |
| 2344 |
|
| 2345 |
|
| 2346 |
@eh.templatekeyword(b'phabstatus', requires={b'ctx', b'repo', b'ui'}) |
| 2347 |
def template_status(context, mapping): |
| 2348 |
""":phabstatus: String. Status of Phabricator differential.""" |
| 2349 |
ctx = context.resource(mapping, b'ctx') |
| 2350 |
repo = context.resource(mapping, b'repo') |
| 2351 |
ui = context.resource(mapping, b'ui') |
| 2352 |
|
| 2353 |
rev = ctx.rev() |
| 2354 |
try: |
| 2355 |
drevid = getdrevmap(repo, [rev])[rev] |
| 2356 |
except KeyError: |
| 2357 |
return None |
| 2358 |
drevs = callconduit(ui, b'differential.query', {b'ids': [drevid]}) |
| 2359 |
for drev in drevs: |
| 2360 |
if int(drev[b'id']) == drevid: |
| 2361 |
return templateutil.hybriddict( |
| 2362 |
{ |
| 2363 |
b'url': drev[b'uri'], |
| 2364 |
b'status': drev[b'statusName'], |
| 2365 |
} |
| 2366 |
) |
| 2367 |
return None |
| 2368 |
|
| 2369 |
|
| 2370 |
@show.showview(b'phabstatus', csettopic=b'work') |
| 2371 |
def phabstatusshowview(ui, repo, displayer): |
| 2372 |
"""Phabricator differiential status""" |
| 2373 |
revs = repo.revs('sort(_underway(), topo)') |
| 2374 |
drevmap = getdrevmap(repo, revs) |
| 2375 |
unknownrevs, drevids, revsbydrevid = [], set(), {} |
| 2376 |
for rev, drevid in drevmap.items(): |
| 2377 |
if drevid is not None: |
| 2378 |
drevids.add(drevid) |
| 2379 |
revsbydrevid.setdefault(drevid, set()).add(rev) |
| 2380 |
else: |
| 2381 |
unknownrevs.append(rev) |
| 2382 |
|
| 2383 |
drevs = callconduit(ui, b'differential.query', {b'ids': list(drevids)}) |
| 2384 |
drevsbyrev = {} |
| 2385 |
for drev in drevs: |
| 2386 |
for rev in revsbydrevid[int(drev[b'id'])]: |
| 2387 |
drevsbyrev[rev] = drev |
| 2388 |
|
| 2389 |
def phabstatus(ctx): |
| 2390 |
drev = drevsbyrev[ctx.rev()] |
| 2391 |
status = ui.label( |
| 2392 |
b'%(statusName)s' % drev, |
| 2393 |
b'phabricator.status.%s' % _getstatusname(drev), |
| 2394 |
) |
| 2395 |
ui.write(b"\n%s %s\n" % (drev[b'uri'], status)) |
| 2396 |
|
| 2397 |
revs -= smartset.baseset(unknownrevs) |
| 2398 |
revdag = graphmod.dagwalker(repo, revs) |
| 2399 |
|
| 2400 |
ui.setconfig(b'experimental', b'graphshorten', True) |
| 2401 |
displayer._exthook = phabstatus |
| 2402 |
nodelen = show.longestshortest(repo, revs) |
| 2403 |
logcmdutil.displaygraph( |
| 2404 |
ui, |
| 2405 |
repo, |
| 2406 |
revdag, |
| 2407 |
displayer, |
| 2408 |
graphmod.asciiedges, |
| 2409 |
props={b'nodelen': nodelen}, |
| 2410 |
) |