Show More
@@ -1,378 +1,433 b'' | |||||
1 | # phabricator.py - simple Phabricator integration |
|
1 | # phabricator.py - simple Phabricator integration | |
2 | # |
|
2 | # | |
3 | # Copyright 2017 Facebook, Inc. |
|
3 | # Copyright 2017 Facebook, Inc. | |
4 | # |
|
4 | # | |
5 | # This software may be used and distributed according to the terms of the |
|
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. |
|
6 | # GNU General Public License version 2 or any later version. | |
7 | """simple Phabricator integration |
|
7 | """simple Phabricator integration | |
8 |
|
8 | |||
9 | This extension provides a ``phabsend`` command which sends a stack of |
|
9 | This extension provides a ``phabsend`` command which sends a stack of | |
10 | changesets to Phabricator without amending commit messages, and a ``phabread`` |
|
10 | changesets to Phabricator without amending commit messages, and a ``phabread`` | |
11 | command which prints a stack of revisions in a format suitable |
|
11 | command which prints a stack of revisions in a format suitable | |
12 | for :hg:`import`. |
|
12 | for :hg:`import`. | |
13 |
|
13 | |||
14 | By default, Phabricator requires ``Test Plan`` which might prevent some |
|
14 | By default, Phabricator requires ``Test Plan`` which might prevent some | |
15 | changeset from being sent. The requirement could be disabled by changing |
|
15 | changeset from being sent. The requirement could be disabled by changing | |
16 | ``differential.require-test-plan-field`` config server side. |
|
16 | ``differential.require-test-plan-field`` config server side. | |
17 |
|
17 | |||
18 | Config:: |
|
18 | Config:: | |
19 |
|
19 | |||
20 | [phabricator] |
|
20 | [phabricator] | |
21 | # Phabricator URL |
|
21 | # Phabricator URL | |
22 | url = https://phab.example.com/ |
|
22 | url = https://phab.example.com/ | |
23 |
|
23 | |||
24 | # API token. Get it from https://$HOST/conduit/login/ |
|
24 | # API token. Get it from https://$HOST/conduit/login/ | |
25 | token = cli-xxxxxxxxxxxxxxxxxxxxxxxxxxxx |
|
25 | token = cli-xxxxxxxxxxxxxxxxxxxxxxxxxxxx | |
26 |
|
26 | |||
27 | # Repo callsign. If a repo has a URL https://$HOST/diffusion/FOO, then its |
|
27 | # Repo callsign. If a repo has a URL https://$HOST/diffusion/FOO, then its | |
28 | # callsign is "FOO". |
|
28 | # callsign is "FOO". | |
29 | callsign = FOO |
|
29 | callsign = FOO | |
30 |
|
30 | |||
31 | """ |
|
31 | """ | |
32 |
|
32 | |||
33 | from __future__ import absolute_import |
|
33 | from __future__ import absolute_import | |
34 |
|
34 | |||
35 | import json |
|
35 | import json | |
36 | import re |
|
36 | import re | |
37 |
|
37 | |||
38 | from mercurial.i18n import _ |
|
38 | from mercurial.i18n import _ | |
39 | from mercurial import ( |
|
39 | from mercurial import ( | |
40 | encoding, |
|
40 | encoding, | |
41 | error, |
|
41 | error, | |
42 | mdiff, |
|
42 | mdiff, | |
43 | obsolete, |
|
43 | obsolete, | |
44 | patch, |
|
44 | patch, | |
45 | registrar, |
|
45 | registrar, | |
46 | scmutil, |
|
46 | scmutil, | |
47 | tags, |
|
47 | tags, | |
48 | url as urlmod, |
|
48 | url as urlmod, | |
49 | util, |
|
49 | util, | |
50 | ) |
|
50 | ) | |
51 |
|
51 | |||
52 | cmdtable = {} |
|
52 | cmdtable = {} | |
53 | command = registrar.command(cmdtable) |
|
53 | command = registrar.command(cmdtable) | |
54 |
|
54 | |||
55 | def urlencodenested(params): |
|
55 | def urlencodenested(params): | |
56 | """like urlencode, but works with nested parameters. |
|
56 | """like urlencode, but works with nested parameters. | |
57 |
|
57 | |||
58 | For example, if params is {'a': ['b', 'c'], 'd': {'e': 'f'}}, it will be |
|
58 | For example, if params is {'a': ['b', 'c'], 'd': {'e': 'f'}}, it will be | |
59 | flattened to {'a[0]': 'b', 'a[1]': 'c', 'd[e]': 'f'} and then passed to |
|
59 | flattened to {'a[0]': 'b', 'a[1]': 'c', 'd[e]': 'f'} and then passed to | |
60 | urlencode. Note: the encoding is consistent with PHP's http_build_query. |
|
60 | urlencode. Note: the encoding is consistent with PHP's http_build_query. | |
61 | """ |
|
61 | """ | |
62 | flatparams = util.sortdict() |
|
62 | flatparams = util.sortdict() | |
63 | def process(prefix, obj): |
|
63 | def process(prefix, obj): | |
64 | items = {list: enumerate, dict: lambda x: x.items()}.get(type(obj)) |
|
64 | items = {list: enumerate, dict: lambda x: x.items()}.get(type(obj)) | |
65 | if items is None: |
|
65 | if items is None: | |
66 | flatparams[prefix] = obj |
|
66 | flatparams[prefix] = obj | |
67 | else: |
|
67 | else: | |
68 | for k, v in items(obj): |
|
68 | for k, v in items(obj): | |
69 | if prefix: |
|
69 | if prefix: | |
70 | process('%s[%s]' % (prefix, k), v) |
|
70 | process('%s[%s]' % (prefix, k), v) | |
71 | else: |
|
71 | else: | |
72 | process(k, v) |
|
72 | process(k, v) | |
73 | process('', params) |
|
73 | process('', params) | |
74 | return util.urlreq.urlencode(flatparams) |
|
74 | return util.urlreq.urlencode(flatparams) | |
75 |
|
75 | |||
76 | def readurltoken(repo): |
|
76 | def readurltoken(repo): | |
77 | """return conduit url, token and make sure they exist |
|
77 | """return conduit url, token and make sure they exist | |
78 |
|
78 | |||
79 | Currently read from [phabricator] config section. In the future, it might |
|
79 | Currently read from [phabricator] config section. In the future, it might | |
80 | make sense to read from .arcconfig and .arcrc as well. |
|
80 | make sense to read from .arcconfig and .arcrc as well. | |
81 | """ |
|
81 | """ | |
82 | values = [] |
|
82 | values = [] | |
83 | section = 'phabricator' |
|
83 | section = 'phabricator' | |
84 | for name in ['url', 'token']: |
|
84 | for name in ['url', 'token']: | |
85 | value = repo.ui.config(section, name) |
|
85 | value = repo.ui.config(section, name) | |
86 | if not value: |
|
86 | if not value: | |
87 | raise error.Abort(_('config %s.%s is required') % (section, name)) |
|
87 | raise error.Abort(_('config %s.%s is required') % (section, name)) | |
88 | values.append(value) |
|
88 | values.append(value) | |
89 | return values |
|
89 | return values | |
90 |
|
90 | |||
91 | def callconduit(repo, name, params): |
|
91 | def callconduit(repo, name, params): | |
92 | """call Conduit API, params is a dict. return json.loads result, or None""" |
|
92 | """call Conduit API, params is a dict. return json.loads result, or None""" | |
93 | host, token = readurltoken(repo) |
|
93 | host, token = readurltoken(repo) | |
94 | url, authinfo = util.url('/'.join([host, 'api', name])).authinfo() |
|
94 | url, authinfo = util.url('/'.join([host, 'api', name])).authinfo() | |
95 | urlopener = urlmod.opener(repo.ui, authinfo) |
|
95 | urlopener = urlmod.opener(repo.ui, authinfo) | |
96 | repo.ui.debug('Conduit Call: %s %s\n' % (url, params)) |
|
96 | repo.ui.debug('Conduit Call: %s %s\n' % (url, params)) | |
97 | params = params.copy() |
|
97 | params = params.copy() | |
98 | params['api.token'] = token |
|
98 | params['api.token'] = token | |
99 | request = util.urlreq.request(url, data=urlencodenested(params)) |
|
99 | request = util.urlreq.request(url, data=urlencodenested(params)) | |
100 | body = urlopener.open(request).read() |
|
100 | body = urlopener.open(request).read() | |
101 | repo.ui.debug('Conduit Response: %s\n' % body) |
|
101 | repo.ui.debug('Conduit Response: %s\n' % body) | |
102 | parsed = json.loads(body) |
|
102 | parsed = json.loads(body) | |
103 | if parsed.get(r'error_code'): |
|
103 | if parsed.get(r'error_code'): | |
104 | msg = (_('Conduit Error (%s): %s') |
|
104 | msg = (_('Conduit Error (%s): %s') | |
105 | % (parsed[r'error_code'], parsed[r'error_info'])) |
|
105 | % (parsed[r'error_code'], parsed[r'error_info'])) | |
106 | raise error.Abort(msg) |
|
106 | raise error.Abort(msg) | |
107 | return parsed[r'result'] |
|
107 | return parsed[r'result'] | |
108 |
|
108 | |||
109 | @command('debugcallconduit', [], _('METHOD')) |
|
109 | @command('debugcallconduit', [], _('METHOD')) | |
110 | def debugcallconduit(ui, repo, name): |
|
110 | def debugcallconduit(ui, repo, name): | |
111 | """call Conduit API |
|
111 | """call Conduit API | |
112 |
|
112 | |||
113 | Call parameters are read from stdin as a JSON blob. Result will be written |
|
113 | Call parameters are read from stdin as a JSON blob. Result will be written | |
114 | to stdout as a JSON blob. |
|
114 | to stdout as a JSON blob. | |
115 | """ |
|
115 | """ | |
116 | params = json.loads(ui.fin.read()) |
|
116 | params = json.loads(ui.fin.read()) | |
117 | result = callconduit(repo, name, params) |
|
117 | result = callconduit(repo, name, params) | |
118 | s = json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')) |
|
118 | s = json.dumps(result, sort_keys=True, indent=2, separators=(',', ': ')) | |
119 | ui.write('%s\n' % s) |
|
119 | ui.write('%s\n' % s) | |
120 |
|
120 | |||
121 | def getrepophid(repo): |
|
121 | def getrepophid(repo): | |
122 | """given callsign, return repository PHID or None""" |
|
122 | """given callsign, return repository PHID or None""" | |
123 | # developer config: phabricator.repophid |
|
123 | # developer config: phabricator.repophid | |
124 | repophid = repo.ui.config('phabricator', 'repophid') |
|
124 | repophid = repo.ui.config('phabricator', 'repophid') | |
125 | if repophid: |
|
125 | if repophid: | |
126 | return repophid |
|
126 | return repophid | |
127 | callsign = repo.ui.config('phabricator', 'callsign') |
|
127 | callsign = repo.ui.config('phabricator', 'callsign') | |
128 | if not callsign: |
|
128 | if not callsign: | |
129 | return None |
|
129 | return None | |
130 | query = callconduit(repo, 'diffusion.repository.search', |
|
130 | query = callconduit(repo, 'diffusion.repository.search', | |
131 | {'constraints': {'callsigns': [callsign]}}) |
|
131 | {'constraints': {'callsigns': [callsign]}}) | |
132 | if len(query[r'data']) == 0: |
|
132 | if len(query[r'data']) == 0: | |
133 | return None |
|
133 | return None | |
134 | repophid = encoding.strtolocal(query[r'data'][0][r'phid']) |
|
134 | repophid = encoding.strtolocal(query[r'data'][0][r'phid']) | |
135 | repo.ui.setconfig('phabricator', 'repophid', repophid) |
|
135 | repo.ui.setconfig('phabricator', 'repophid', repophid) | |
136 | return repophid |
|
136 | return repophid | |
137 |
|
137 | |||
138 | _differentialrevisiontagre = re.compile('\AD([1-9][0-9]*)\Z') |
|
138 | _differentialrevisiontagre = re.compile('\AD([1-9][0-9]*)\Z') | |
139 | _differentialrevisiondescre = re.compile( |
|
139 | _differentialrevisiondescre = re.compile( | |
140 | '^Differential Revision:.*D([1-9][0-9]*)$', re.M) |
|
140 | '^Differential Revision:.*D([1-9][0-9]*)$', re.M) | |
141 |
|
141 | |||
142 | def getmapping(ctx): |
|
142 | def getmapping(ctx): | |
143 | """return (node, associated Differential Revision ID) or (None, None) |
|
143 | """return (node, associated Differential Revision ID) or (None, None) | |
144 |
|
144 | |||
145 | Examines all precursors and their tags. Tags with format like "D1234" are |
|
145 | Examines all precursors and their tags. Tags with format like "D1234" are | |
146 | considered a match and the node with that tag, and the number after "D" |
|
146 | considered a match and the node with that tag, and the number after "D" | |
147 | (ex. 1234) will be returned. |
|
147 | (ex. 1234) will be returned. | |
148 |
|
148 | |||
149 | If tags are not found, examine commit message. The "Differential Revision:" |
|
149 | If tags are not found, examine commit message. The "Differential Revision:" | |
150 | line could associate this changeset to a Differential Revision. |
|
150 | line could associate this changeset to a Differential Revision. | |
151 | """ |
|
151 | """ | |
152 | unfi = ctx.repo().unfiltered() |
|
152 | unfi = ctx.repo().unfiltered() | |
153 | nodemap = unfi.changelog.nodemap |
|
153 | nodemap = unfi.changelog.nodemap | |
154 |
|
154 | |||
155 | # Check tags like "D123" |
|
155 | # Check tags like "D123" | |
156 | for n in obsolete.allprecursors(unfi.obsstore, [ctx.node()]): |
|
156 | for n in obsolete.allprecursors(unfi.obsstore, [ctx.node()]): | |
157 | if n in nodemap: |
|
157 | if n in nodemap: | |
158 | for tag in unfi.nodetags(n): |
|
158 | for tag in unfi.nodetags(n): | |
159 | m = _differentialrevisiontagre.match(tag) |
|
159 | m = _differentialrevisiontagre.match(tag) | |
160 | if m: |
|
160 | if m: | |
161 | return n, int(m.group(1)) |
|
161 | return n, int(m.group(1)) | |
162 |
|
162 | |||
163 | # Check commit message |
|
163 | # Check commit message | |
164 | m = _differentialrevisiondescre.search(ctx.description()) |
|
164 | m = _differentialrevisiondescre.search(ctx.description()) | |
165 | if m: |
|
165 | if m: | |
166 | return None, int(m.group(1)) |
|
166 | return None, int(m.group(1)) | |
167 |
|
167 | |||
168 | return None, None |
|
168 | return None, None | |
169 |
|
169 | |||
170 | def getdiff(ctx, diffopts): |
|
170 | def getdiff(ctx, diffopts): | |
171 | """plain-text diff without header (user, commit message, etc)""" |
|
171 | """plain-text diff without header (user, commit message, etc)""" | |
172 | output = util.stringio() |
|
172 | output = util.stringio() | |
173 | for chunk, _label in patch.diffui(ctx.repo(), ctx.p1().node(), ctx.node(), |
|
173 | for chunk, _label in patch.diffui(ctx.repo(), ctx.p1().node(), ctx.node(), | |
174 | None, opts=diffopts): |
|
174 | None, opts=diffopts): | |
175 | output.write(chunk) |
|
175 | output.write(chunk) | |
176 | return output.getvalue() |
|
176 | return output.getvalue() | |
177 |
|
177 | |||
178 | def creatediff(ctx): |
|
178 | def creatediff(ctx): | |
179 | """create a Differential Diff""" |
|
179 | """create a Differential Diff""" | |
180 | repo = ctx.repo() |
|
180 | repo = ctx.repo() | |
181 | repophid = getrepophid(repo) |
|
181 | repophid = getrepophid(repo) | |
182 | # Create a "Differential Diff" via "differential.createrawdiff" API |
|
182 | # Create a "Differential Diff" via "differential.createrawdiff" API | |
183 | params = {'diff': getdiff(ctx, mdiff.diffopts(git=True, context=32767))} |
|
183 | params = {'diff': getdiff(ctx, mdiff.diffopts(git=True, context=32767))} | |
184 | if repophid: |
|
184 | if repophid: | |
185 | params['repositoryPHID'] = repophid |
|
185 | params['repositoryPHID'] = repophid | |
186 | diff = callconduit(repo, 'differential.createrawdiff', params) |
|
186 | diff = callconduit(repo, 'differential.createrawdiff', params) | |
187 | if not diff: |
|
187 | if not diff: | |
188 | raise error.Abort(_('cannot create diff for %s') % ctx) |
|
188 | raise error.Abort(_('cannot create diff for %s') % ctx) | |
189 | return diff |
|
189 | return diff | |
190 |
|
190 | |||
191 | def writediffproperties(ctx, diff): |
|
191 | def writediffproperties(ctx, diff): | |
192 | """write metadata to diff so patches could be applied losslessly""" |
|
192 | """write metadata to diff so patches could be applied losslessly""" | |
193 | params = { |
|
193 | params = { | |
194 | 'diff_id': diff[r'id'], |
|
194 | 'diff_id': diff[r'id'], | |
195 | 'name': 'hg:meta', |
|
195 | 'name': 'hg:meta', | |
196 | 'data': json.dumps({ |
|
196 | 'data': json.dumps({ | |
197 | 'user': ctx.user(), |
|
197 | 'user': ctx.user(), | |
198 | 'date': '%d %d' % ctx.date(), |
|
198 | 'date': '%d %d' % ctx.date(), | |
199 | 'node': ctx.hex(), |
|
199 | 'node': ctx.hex(), | |
200 | 'parent': ctx.p1().hex(), |
|
200 | 'parent': ctx.p1().hex(), | |
201 | }), |
|
201 | }), | |
202 | } |
|
202 | } | |
203 | callconduit(ctx.repo(), 'differential.setdiffproperty', params) |
|
203 | callconduit(ctx.repo(), 'differential.setdiffproperty', params) | |
204 |
|
204 | |||
205 | def createdifferentialrevision(ctx, revid=None, parentrevid=None, oldnode=None): |
|
205 | def createdifferentialrevision(ctx, revid=None, parentrevid=None, oldnode=None): | |
206 | """create or update a Differential Revision |
|
206 | """create or update a Differential Revision | |
207 |
|
207 | |||
208 | If revid is None, create a new Differential Revision, otherwise update |
|
208 | If revid is None, create a new Differential Revision, otherwise update | |
209 | revid. If parentrevid is not None, set it as a dependency. |
|
209 | revid. If parentrevid is not None, set it as a dependency. | |
210 |
|
210 | |||
211 | If oldnode is not None, check if the patch content (without commit message |
|
211 | If oldnode is not None, check if the patch content (without commit message | |
212 | and metadata) has changed before creating another diff. |
|
212 | and metadata) has changed before creating another diff. | |
213 | """ |
|
213 | """ | |
214 | repo = ctx.repo() |
|
214 | repo = ctx.repo() | |
215 | if oldnode: |
|
215 | if oldnode: | |
216 | diffopts = mdiff.diffopts(git=True, context=1) |
|
216 | diffopts = mdiff.diffopts(git=True, context=1) | |
217 | oldctx = repo.unfiltered()[oldnode] |
|
217 | oldctx = repo.unfiltered()[oldnode] | |
218 | neednewdiff = (getdiff(ctx, diffopts) != getdiff(oldctx, diffopts)) |
|
218 | neednewdiff = (getdiff(ctx, diffopts) != getdiff(oldctx, diffopts)) | |
219 | else: |
|
219 | else: | |
220 | neednewdiff = True |
|
220 | neednewdiff = True | |
221 |
|
221 | |||
222 | transactions = [] |
|
222 | transactions = [] | |
223 | if neednewdiff: |
|
223 | if neednewdiff: | |
224 | diff = creatediff(ctx) |
|
224 | diff = creatediff(ctx) | |
225 | writediffproperties(ctx, diff) |
|
225 | writediffproperties(ctx, diff) | |
226 | transactions.append({'type': 'update', 'value': diff[r'phid']}) |
|
226 | transactions.append({'type': 'update', 'value': diff[r'phid']}) | |
227 |
|
227 | |||
228 | # Use a temporary summary to set dependency. There might be better ways but |
|
228 | # Use a temporary summary to set dependency. There might be better ways but | |
229 | # I cannot find them for now. But do not do that if we are updating an |
|
229 | # I cannot find them for now. But do not do that if we are updating an | |
230 | # existing revision (revid is not None) since that introduces visible |
|
230 | # existing revision (revid is not None) since that introduces visible | |
231 | # churns (someone edited "Summary" twice) on the web page. |
|
231 | # churns (someone edited "Summary" twice) on the web page. | |
232 | if parentrevid and revid is None: |
|
232 | if parentrevid and revid is None: | |
233 | summary = 'Depends on D%s' % parentrevid |
|
233 | summary = 'Depends on D%s' % parentrevid | |
234 | transactions += [{'type': 'summary', 'value': summary}, |
|
234 | transactions += [{'type': 'summary', 'value': summary}, | |
235 | {'type': 'summary', 'value': ' '}] |
|
235 | {'type': 'summary', 'value': ' '}] | |
236 |
|
236 | |||
237 | # Parse commit message and update related fields. |
|
237 | # Parse commit message and update related fields. | |
238 | desc = ctx.description() |
|
238 | desc = ctx.description() | |
239 | info = callconduit(repo, 'differential.parsecommitmessage', |
|
239 | info = callconduit(repo, 'differential.parsecommitmessage', | |
240 | {'corpus': desc}) |
|
240 | {'corpus': desc}) | |
241 | for k, v in info[r'fields'].items(): |
|
241 | for k, v in info[r'fields'].items(): | |
242 | if k in ['title', 'summary', 'testPlan']: |
|
242 | if k in ['title', 'summary', 'testPlan']: | |
243 | transactions.append({'type': k, 'value': v}) |
|
243 | transactions.append({'type': k, 'value': v}) | |
244 |
|
244 | |||
245 | params = {'transactions': transactions} |
|
245 | params = {'transactions': transactions} | |
246 | if revid is not None: |
|
246 | if revid is not None: | |
247 | # Update an existing Differential Revision |
|
247 | # Update an existing Differential Revision | |
248 | params['objectIdentifier'] = revid |
|
248 | params['objectIdentifier'] = revid | |
249 |
|
249 | |||
250 | revision = callconduit(repo, 'differential.revision.edit', params) |
|
250 | revision = callconduit(repo, 'differential.revision.edit', params) | |
251 | if not revision: |
|
251 | if not revision: | |
252 | raise error.Abort(_('cannot create revision for %s') % ctx) |
|
252 | raise error.Abort(_('cannot create revision for %s') % ctx) | |
253 |
|
253 | |||
254 | return revision |
|
254 | return revision | |
255 |
|
255 | |||
256 | @command('phabsend', |
|
256 | @command('phabsend', | |
257 | [('r', 'rev', [], _('revisions to send'), _('REV'))], |
|
257 | [('r', 'rev', [], _('revisions to send'), _('REV'))], | |
258 | _('REV [OPTIONS]')) |
|
258 | _('REV [OPTIONS]')) | |
259 | def phabsend(ui, repo, *revs, **opts): |
|
259 | def phabsend(ui, repo, *revs, **opts): | |
260 | """upload changesets to Phabricator |
|
260 | """upload changesets to Phabricator | |
261 |
|
261 | |||
262 | If there are multiple revisions specified, they will be send as a stack |
|
262 | If there are multiple revisions specified, they will be send as a stack | |
263 | with a linear dependencies relationship using the order specified by the |
|
263 | with a linear dependencies relationship using the order specified by the | |
264 | revset. |
|
264 | revset. | |
265 |
|
265 | |||
266 | For the first time uploading changesets, local tags will be created to |
|
266 | For the first time uploading changesets, local tags will be created to | |
267 | maintain the association. After the first time, phabsend will check |
|
267 | maintain the association. After the first time, phabsend will check | |
268 | obsstore and tags information so it can figure out whether to update an |
|
268 | obsstore and tags information so it can figure out whether to update an | |
269 | existing Differential Revision, or create a new one. |
|
269 | existing Differential Revision, or create a new one. | |
270 | """ |
|
270 | """ | |
271 | revs = list(revs) + opts.get('rev', []) |
|
271 | revs = list(revs) + opts.get('rev', []) | |
272 | revs = scmutil.revrange(repo, revs) |
|
272 | revs = scmutil.revrange(repo, revs) | |
273 |
|
273 | |||
274 | if not revs: |
|
274 | if not revs: | |
275 | raise error.Abort(_('phabsend requires at least one changeset')) |
|
275 | raise error.Abort(_('phabsend requires at least one changeset')) | |
276 |
|
276 | |||
277 | # Send patches one by one so we know their Differential Revision IDs and |
|
277 | # Send patches one by one so we know their Differential Revision IDs and | |
278 | # can provide dependency relationship |
|
278 | # can provide dependency relationship | |
279 | lastrevid = None |
|
279 | lastrevid = None | |
280 | for rev in revs: |
|
280 | for rev in revs: | |
281 | ui.debug('sending rev %d\n' % rev) |
|
281 | ui.debug('sending rev %d\n' % rev) | |
282 | ctx = repo[rev] |
|
282 | ctx = repo[rev] | |
283 |
|
283 | |||
284 | # Get Differential Revision ID |
|
284 | # Get Differential Revision ID | |
285 | oldnode, revid = getmapping(ctx) |
|
285 | oldnode, revid = getmapping(ctx) | |
286 | if oldnode != ctx.node(): |
|
286 | if oldnode != ctx.node(): | |
287 | # Create or update Differential Revision |
|
287 | # Create or update Differential Revision | |
288 | revision = createdifferentialrevision(ctx, revid, lastrevid, |
|
288 | revision = createdifferentialrevision(ctx, revid, lastrevid, | |
289 | oldnode) |
|
289 | oldnode) | |
290 | newrevid = int(revision[r'object'][r'id']) |
|
290 | newrevid = int(revision[r'object'][r'id']) | |
291 | if revid: |
|
291 | if revid: | |
292 | action = _('updated') |
|
292 | action = _('updated') | |
293 | else: |
|
293 | else: | |
294 | action = _('created') |
|
294 | action = _('created') | |
295 |
|
295 | |||
296 | # Create a local tag to note the association |
|
296 | # Create a local tag to note the association | |
297 | tagname = 'D%d' % newrevid |
|
297 | tagname = 'D%d' % newrevid | |
298 | tags.tag(repo, tagname, ctx.node(), message=None, user=None, |
|
298 | tags.tag(repo, tagname, ctx.node(), message=None, user=None, | |
299 | date=None, local=True) |
|
299 | date=None, local=True) | |
300 | else: |
|
300 | else: | |
301 | # Nothing changed. But still set "newrevid" so the next revision |
|
301 | # Nothing changed. But still set "newrevid" so the next revision | |
302 | # could depend on this one. |
|
302 | # could depend on this one. | |
303 | newrevid = revid |
|
303 | newrevid = revid | |
304 | action = _('skipped') |
|
304 | action = _('skipped') | |
305 |
|
305 | |||
306 | ui.write(_('D%s: %s - %s: %s\n') % (newrevid, action, ctx, |
|
306 | ui.write(_('D%s: %s - %s: %s\n') % (newrevid, action, ctx, | |
307 | ctx.description().split('\n')[0])) |
|
307 | ctx.description().split('\n')[0])) | |
308 | lastrevid = newrevid |
|
308 | lastrevid = newrevid | |
309 |
|
309 | |||
310 | _summaryre = re.compile('^Summary:\s*', re.M) |
|
310 | _summaryre = re.compile('^Summary:\s*', re.M) | |
311 |
|
311 | |||
312 | # Map from "hg:meta" keys to header understood by "hg import". The order is |
|
312 | # Map from "hg:meta" keys to header understood by "hg import". The order is | |
313 | # consistent with "hg export" output. |
|
313 | # consistent with "hg export" output. | |
314 | _metanamemap = util.sortdict([(r'user', 'User'), (r'date', 'Date'), |
|
314 | _metanamemap = util.sortdict([(r'user', 'User'), (r'date', 'Date'), | |
315 | (r'node', 'Node ID'), (r'parent', 'Parent ')]) |
|
315 | (r'node', 'Node ID'), (r'parent', 'Parent ')]) | |
316 |
|
316 | |||
317 |
def |
|
317 | def querydrev(repo, params, stack=False): | |
|
318 | """return a list of "Differential Revision" dicts | |||
|
319 | ||||
|
320 | params is the input of "differential.query" API, and is expected to match | |||
|
321 | just a single Differential Revision. | |||
|
322 | ||||
|
323 | A "Differential Revision dict" looks like: | |||
|
324 | ||||
|
325 | { | |||
|
326 | "id": "2", | |||
|
327 | "phid": "PHID-DREV-672qvysjcczopag46qty", | |||
|
328 | "title": "example", | |||
|
329 | "uri": "https://phab.example.com/D2", | |||
|
330 | "dateCreated": "1499181406", | |||
|
331 | "dateModified": "1499182103", | |||
|
332 | "authorPHID": "PHID-USER-tv3ohwc4v4jeu34otlye", | |||
|
333 | "status": "0", | |||
|
334 | "statusName": "Needs Review", | |||
|
335 | "properties": [], | |||
|
336 | "branch": null, | |||
|
337 | "summary": "", | |||
|
338 | "testPlan": "", | |||
|
339 | "lineCount": "2", | |||
|
340 | "activeDiffPHID": "PHID-DIFF-xoqnjkobbm6k4dk6hi72", | |||
|
341 | "diffs": [ | |||
|
342 | "3", | |||
|
343 | "4", | |||
|
344 | ], | |||
|
345 | "commits": [], | |||
|
346 | "reviewers": [], | |||
|
347 | "ccs": [], | |||
|
348 | "hashes": [], | |||
|
349 | "auxiliary": { | |||
|
350 | "phabricator:projects": [], | |||
|
351 | "phabricator:depends-on": [ | |||
|
352 | "PHID-DREV-gbapp366kutjebt7agcd" | |||
|
353 | ] | |||
|
354 | }, | |||
|
355 | "repositoryPHID": "PHID-REPO-hub2hx62ieuqeheznasv", | |||
|
356 | "sourcePath": null | |||
|
357 | } | |||
|
358 | ||||
|
359 | If stack is True, return a list of "Differential Revision dict"s in an | |||
|
360 | order that the latter ones depend on the former ones. Otherwise, return a | |||
|
361 | list of a unique "Differential Revision dict". | |||
|
362 | """ | |||
|
363 | result = [] | |||
|
364 | queue = [params] | |||
|
365 | while queue: | |||
|
366 | params = queue.pop() | |||
|
367 | drevs = callconduit(repo, 'differential.query', params) | |||
|
368 | if len(drevs) != 1: | |||
|
369 | raise error.Abort(_('cannot get Differential Revision %r') % params) | |||
|
370 | drev = drevs[0] | |||
|
371 | result.append(drev) | |||
|
372 | if stack: | |||
|
373 | auxiliary = drev.get(r'auxiliary', {}) | |||
|
374 | depends = auxiliary.get(r'phabricator:depends-on', []) | |||
|
375 | for phid in depends: | |||
|
376 | queue.append({'phids': [phid]}) | |||
|
377 | result.reverse() | |||
|
378 | return result | |||
|
379 | ||||
|
380 | def readpatch(repo, params, write, stack=False): | |||
318 | """generate plain-text patch readable by 'hg import' |
|
381 | """generate plain-text patch readable by 'hg import' | |
319 |
|
382 | |||
320 |
params is passed to "differential.query". If |
|
383 | write is usually ui.write. params is passed to "differential.query". If | |
321 | dependent patches. |
|
384 | stack is True, also write dependent patches. | |
322 | """ |
|
385 | """ | |
323 | # Differential Revisions |
|
386 | # Differential Revisions | |
324 | drevs = callconduit(repo, 'differential.query', params) |
|
387 | drevs = querydrev(repo, params, stack) | |
325 | if len(drevs) == 1: |
|
|||
326 | drev = drevs[0] |
|
|||
327 | else: |
|
|||
328 | raise error.Abort(_('cannot get Differential Revision %r') % params) |
|
|||
329 |
|
||||
330 | repo.ui.note(_('reading D%s\n') % drev[r'id']) |
|
|||
331 |
|
388 | |||
332 | diffid = max(int(v) for v in drev[r'diffs']) |
|
389 | # Prefetch hg:meta property for all diffs | |
333 | body = callconduit(repo, 'differential.getrawdiff', {'diffID': diffid}) |
|
390 | diffids = sorted(set(max(int(v) for v in drev[r'diffs']) for drev in drevs)) | |
334 |
d |
|
391 | diffs = callconduit(repo, 'differential.querydiffs', {'ids': diffids}) | |
335 | {'revision_id': drev[r'id']}) |
|
|||
336 | header = '# HG changeset patch\n' |
|
|||
337 |
|
392 | |||
338 | # Remove potential empty "Summary:" |
|
393 | # Generate patch for each drev | |
339 | desc = _summaryre.sub('', desc) |
|
394 | for drev in drevs: | |
|
395 | repo.ui.note(_('reading D%s\n') % drev[r'id']) | |||
340 |
|
396 | |||
341 | # Try to preserve metadata from hg:meta property. Write hg patch headers |
|
397 | diffid = max(int(v) for v in drev[r'diffs']) | |
342 | # that can be read by the "import" command. See patchheadermap and extract |
|
398 | body = callconduit(repo, 'differential.getrawdiff', {'diffID': diffid}) | |
343 | # in mercurial/patch.py for supported headers. |
|
399 | desc = callconduit(repo, 'differential.getcommitmessage', | |
344 | diffs = callconduit(repo, 'differential.querydiffs', {'ids': [diffid]}) |
|
400 | {'revision_id': drev[r'id']}) | |
345 | props = diffs[str(diffid)][r'properties'] # could be empty list or dict |
|
401 | header = '# HG changeset patch\n' | |
346 | if props and r'hg:meta' in props: |
|
402 | ||
347 | meta = props[r'hg:meta'] |
|
403 | # Remove potential empty "Summary:" | |
348 | for k in _metanamemap.keys(): |
|
404 | desc = _summaryre.sub('', desc) | |
349 | if k in meta: |
|
|||
350 | header += '# %s %s\n' % (_metanamemap[k], meta[k]) |
|
|||
351 |
|
405 | |||
352 | patch = ('%s%s\n%s') % (header, desc, body) |
|
406 | # Try to preserve metadata from hg:meta property. Write hg patch | |
|
407 | # headers that can be read by the "import" command. See patchheadermap | |||
|
408 | # and extract in mercurial/patch.py for supported headers. | |||
|
409 | props = diffs[str(diffid)][r'properties'] # could be empty list or dict | |||
|
410 | if props and r'hg:meta' in props: | |||
|
411 | meta = props[r'hg:meta'] | |||
|
412 | for k in _metanamemap.keys(): | |||
|
413 | if k in meta: | |||
|
414 | header += '# %s %s\n' % (_metanamemap[k], meta[k]) | |||
353 |
|
415 | |||
354 | # Check dependencies |
|
416 | write(('%s%s\n%s') % (header, desc, body)) | |
355 | if recursive: |
|
|||
356 | auxiliary = drev.get(r'auxiliary', {}) |
|
|||
357 | depends = auxiliary.get(r'phabricator:depends-on', []) |
|
|||
358 | for phid in depends: |
|
|||
359 | patch = readpatch(repo, {'phids': [phid]}, recursive=True) + patch |
|
|||
360 | return patch |
|
|||
361 |
|
417 | |||
362 | @command('phabread', |
|
418 | @command('phabread', | |
363 | [('', 'stack', False, _('read dependencies'))], |
|
419 | [('', 'stack', False, _('read dependencies'))], | |
364 | _('REVID [OPTIONS]')) |
|
420 | _('REVID [OPTIONS]')) | |
365 | def phabread(ui, repo, revid, **opts): |
|
421 | def phabread(ui, repo, revid, **opts): | |
366 | """print patches from Phabricator suitable for importing |
|
422 | """print patches from Phabricator suitable for importing | |
367 |
|
423 | |||
368 | REVID could be a Differential Revision identity, like ``D123``, or just the |
|
424 | REVID could be a Differential Revision identity, like ``D123``, or just the | |
369 | number ``123``, or a full URL like ``https://phab.example.com/D123``. |
|
425 | number ``123``, or a full URL like ``https://phab.example.com/D123``. | |
370 |
|
426 | |||
371 | If --stack is given, follow dependencies information and read all patches. |
|
427 | If --stack is given, follow dependencies information and read all patches. | |
372 | """ |
|
428 | """ | |
373 | try: |
|
429 | try: | |
374 | revid = int(revid.split('/')[-1].replace('D', '')) |
|
430 | revid = int(revid.split('/')[-1].replace('D', '')) | |
375 | except ValueError: |
|
431 | except ValueError: | |
376 | raise error.Abort(_('invalid Revision ID: %s') % revid) |
|
432 | raise error.Abort(_('invalid Revision ID: %s') % revid) | |
377 |
|
|
433 | readpatch(repo, {'ids': [revid]}, ui.write, opts.get('stack')) | |
378 | ui.write(patch) |
|
General Comments 0
You need to be logged in to leave comments.
Login now