-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
backend.tsx
585 lines (548 loc) · 21.2 KB
/
backend.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import { from, Observable, of, throwError } from 'rxjs'
import { map, mapTo, switchMap, catchError } from 'rxjs/operators'
import { dataOrThrowErrors, gql } from '../../../../shared/src/graphql/graphql'
import * as GQL from '../../../../shared/src/graphql/schema'
import { PlatformContext } from '../../../../shared/src/platform/context'
import { memoizeObservable } from '../../../../shared/src/util/memoizeObservable'
import { storage } from '../../browser/storage'
import { isExtension } from '../../context'
import { resolveRepo } from '../../shared/repo/backend'
import { normalizeRepoName } from './util'
import { ajax } from 'rxjs/ajax'
import { EREPONOTFOUND } from '../../../../shared/src/backend/errors'
import { RepoSpec, FileSpec, ResolvedRevSpec } from '../../../../shared/src/util/url'
import { RevisionSpec, DiffSpec, BaseDiffSpec } from '.'
interface PhabEntity {
id: string // e.g. "48"
type: string // e.g. "RHURI"
phid: string // e.g. "PHID-RHURI-..."
}
interface ConduitURI extends PhabEntity {
fields: {
uri: {
raw: string // e.g. https://secure.phabricator.com/source/phabricator.git",
display: string // e.g. https://secure.phabricator.com/source/phabricator.git",
effective: string // e.g. https://secure.phabricator.com/source/phabricator.git",
normalized: string // e.g. secure.phabricator.com/source/phabricator",
}
}
}
interface ConduitRepo extends PhabEntity {
fields: {
name: string
vcs: string // e.g. 'git'
callsign: string
shortName: string
status: 'active' | 'inactive'
}
attachments: {
uris: {
uris: ConduitURI[]
}
}
}
export interface ConduitReposResponse {
data: ConduitRepo[]
}
interface ConduitRef {
ref: string
type: 'base' | 'diff'
commit: string // a SHA
remote: {
uri: string
}
}
interface ConduitDiffChange {
oldPath: string
currentPath: string
}
interface ConduitDiffDetails {
branch: string
sourceControlBaseRevision: string // the merge base commit
description: string // e.g. 'rNZAP9bee3bc2cd3068dd97dfa87068c4431c5d6093ef'
changes: ConduitDiffChange[]
dateCreated: string
authorName: string
authorEmail: string
properties: {
'arc.staging': {
status: string
refs: ConduitRef[]
}
'local:commits': string[]
}
}
interface ConduitDiffDetailsResponse {
[id: string]: ConduitDiffDetails
}
/**
* Creates the `FormData` used to pass parameters along with Conduit API requests,
* including the CSRF token.
*/
function createConduitRequestForm(): FormData {
const searchForm = document.querySelector('.phabricator-search-menu form')
if (!searchForm) {
throw new Error('cannot create conduit request form')
}
const form = new FormData()
form.set('__csrf__', searchForm.querySelector<HTMLInputElement>('input[name=__csrf__]')!.value)
form.set('__form__', searchForm.querySelector<HTMLInputElement>('input[name=__form__]')!.value)
return form
}
/**
* Native installation of the Phabricator extension does not allow for us to fetch the style.bundle from a script element.
* To get around this we fetch the bundled CSS contents and append it to the DOM.
*/
export async function getPhabricatorCSS(sourcegraphURL: string): Promise<string> {
const bundleUID = process.env.BUNDLE_UID
const resp = await fetch(sourcegraphURL + `/.assets/extension/css/style.bundle.css?v=${bundleUID}`, {
method: 'GET',
credentials: 'include',
headers: new Headers({ Accept: 'text/html' }),
})
return resp.text()
}
type ConduitResponse<T> =
| { error_code: null; error_info: null; result: T }
| { error_code: string; error_info: string; result: null }
export type QueryConduitHelper<T> = (endpoint: string, params: {}) => Observable<T>
/**
* Generic helper to query the Phabricator Conduit API.
*/
export function queryConduitHelper<T>(endpoint: string, params: {}): Observable<T> {
const form = createConduitRequestForm()
for (const [key, value] of Object.entries(params)) {
form.set(`params[${key}]`, JSON.stringify(value))
}
return ajax({
url: window.location.origin + endpoint,
method: 'POST',
body: form,
withCredentials: true,
headers: {
Accept: 'application/json',
},
}).pipe(
map(({ response }: { response: ConduitResponse<T> }) => {
if (response.error_code !== null) {
throw new Error(`error ${response.error_code}: ${response.error_info}`)
}
return response.result
})
)
}
/**
* Queries the Phabricator Conduit API for the {@link ConduitDiffDetails} matching the given
* revision and diff IDs. {@link ConduitDiffDetails} notably contain the staging details for the diff,
* including the base and head commit IDs on the staging repository.
*/
function getDiffDetailsFromConduit(
{ diffID, revisionID }: RevisionSpec & DiffSpec,
queryConduit = queryConduitHelper
): Observable<ConduitDiffDetails> {
return queryConduit<ConduitDiffDetailsResponse>('/api/differential.querydiffs', {
ids: [diffID],
revisionIDs: [revisionID],
}).pipe(map(diffDetails => diffDetails[String(diffID)]))
}
function getRawDiffFromConduit(diffID: number, queryConduit = queryConduitHelper): Observable<string> {
return queryConduit<string>('/api/differential.getrawdiff', { diffID })
}
interface ConduitDifferentialQueryResponse {
[index: string]: {
repositoryPHID: string | null
}
}
/**
* Queries the Phabricator Conduit API for the PHID (Phabricator's opaque unique ID)
* of the repository matching the given revisionID.
*/
function getRepoPHIDForRevisionID(revisionID: number, queryConduit = queryConduitHelper): Observable<string> {
return queryConduit<ConduitDifferentialQueryResponse>('/api/differential.query', { ids: [revisionID] }).pipe(
map(result => {
const phid = result['0'].repositoryPHID
if (!phid) {
// This happens for revisions that were created without an associated repository
throw new Error(`no repositoryPHID for revision ${revisionID}`)
}
return phid
})
)
}
interface CreatePhabricatorRepoOptions extends Pick<PlatformContext, 'requestGraphQL'> {
callsign: string
repoName: string
phabricatorURL: string
}
const createPhabricatorRepo = memoizeObservable(
({ requestGraphQL, ...variables }: CreatePhabricatorRepoOptions): Observable<void> =>
requestGraphQL<GQL.IMutation>({
request: gql`
mutation addPhabricatorRepo($callsign: String!, $repoName: String!, $phabricatorURL: String!) {
addPhabricatorRepo(callsign: $callsign, uri: $repoName, url: $phabricatorURL) {
alwaysNil
}
}
`,
variables,
mightContainPrivateInfo: true,
}).pipe(mapTo(undefined)),
({ callsign }) => callsign
)
interface PhabricatorRepoDetails {
callsign: string
rawRepoName: string
}
/**
* Queries the Phabricator Conduit API for a repository matching the given callsign,
* and emits the {@link PhabricatorRepoDetails} if found.
*/
export function getRepoDetailsFromCallsign(
callsign: string,
requestGraphQL: PlatformContext['requestGraphQL'],
queryConduit: QueryConduitHelper<ConduitReposResponse>
): Observable<PhabricatorRepoDetails> {
return queryConduit('/api/diffusion.repository.search', {
constraints: { callsigns: [callsign] },
attachments: { uris: true },
}).pipe(
switchMap(({ data }) => {
const repo = data[0]
if (!repo) {
throw new Error(`could not locate repo with callsign ${callsign}`)
}
if (!repo.attachments || !repo.attachments.uris) {
throw new Error(`could not locate git uri for repo with callsign ${callsign}`)
}
return convertConduitRepoToRepoDetails(repo)
}),
switchMap((details: PhabricatorRepoDetails | null) => {
if (!details) {
return throwError(new Error('could not parse repo details'))
}
return createPhabricatorRepo({
callsign,
repoName: details.rawRepoName,
phabricatorURL: window.location.origin,
requestGraphQL,
}).pipe(mapTo(details))
})
)
}
/**
* Queries the Phabricator Conduit API sourcegraph.configuration endpoint.
*
* The Phabricator extension updates the window object automatically, but in the
* case it fails we query the conduit API.
*/
export function getSourcegraphURLFromConduit(): Promise<string> {
return queryConduitHelper<{ url: string }>('/api/sourcegraph.configuration', {})
.pipe(map(({ url }) => url))
.toPromise()
}
function getRepoDetailsFromRepoPHID(
phid: string,
requestGraphQL: PlatformContext['requestGraphQL'],
queryConduit = queryConduitHelper
): Observable<PhabricatorRepoDetails> {
return queryConduit<ConduitReposResponse>('/api/diffusion.repository.search', {
constraints: {
phids: [phid],
},
attachments: {
uris: true,
},
}).pipe(
switchMap(({ data }) => {
const repo = data[0]
if (!repo) {
throw new Error(`could not locate repo with phid ${phid}`)
}
if (!repo.attachments || !repo.attachments.uris) {
throw new Error(`could not locate git uri for repo with phid ${phid}`)
}
return from(convertConduitRepoToRepoDetails(repo)).pipe(
switchMap((details: PhabricatorRepoDetails | null) => {
if (!details) {
return throwError(new Error('could not parse repo details'))
}
if (!repo.fields || !repo.fields.callsign) {
return throwError(new Error('callsign not found'))
}
return createPhabricatorRepo({
callsign: repo.fields.callsign,
repoName: details.rawRepoName,
phabricatorURL: window.location.origin,
requestGraphQL,
}).pipe(mapTo(details))
})
)
})
)
}
/**
* Queries the Phabricator Conduit API for a repository matching the given revisionID,
* and emits the {@link PhabricatorRepoDetails} for that repository if found.
*/
export function getRepoDetailsFromRevisionID(
revisionID: number,
requestGraphQL: PlatformContext['requestGraphQL'],
queryConduit = queryConduitHelper
): Observable<PhabricatorRepoDetails> {
return getRepoPHIDForRevisionID(revisionID, queryConduit).pipe(
switchMap(repositoryPHID => getRepoDetailsFromRepoPHID(repositoryPHID, requestGraphQL, queryConduit))
)
}
async function convertConduitRepoToRepoDetails(repo: ConduitRepo): Promise<PhabricatorRepoDetails | null> {
if (isExtension) {
const items = await storage.sync.get()
if (items.phabricatorMappings) {
for (const mapping of items.phabricatorMappings) {
if (mapping.callsign === repo.fields.callsign) {
return {
callsign: repo.fields.callsign,
rawRepoName: mapping.path,
}
}
}
}
return convertToDetails(repo)
}
// The path to a phabricator repository on a Sourcegraph instance may differ than it's URI / name from the
// phabricator conduit API. Since we do not currently send the PHID with the Phabricator repository this a
// backwards work around configuration setting to ensure mappings are correct. This logic currently exists
// in the browser extension options menu.
type Mappings = { callsign: string; path: string }[]
const mappingsString = window.localStorage.getItem('PHABRICATOR_CALLSIGN_MAPPINGS')
const callsignMappings = mappingsString
? (JSON.parse(mappingsString) as Mappings)
: window.PHABRICATOR_CALLSIGN_MAPPINGS || []
const details = convertToDetails(repo)
if (callsignMappings) {
for (const mapping of callsignMappings) {
if (mapping.callsign === repo.fields.callsign) {
return {
callsign: repo.fields.callsign,
rawRepoName: mapping.path,
}
}
}
}
return details
}
function convertToDetails(repo: ConduitRepo): PhabricatorRepoDetails | null {
let uri: ConduitURI | undefined
for (const u of repo.attachments.uris.uris) {
const normalPath = u.fields.uri.normalized.replace('\\', '')
if (normalPath.startsWith(window.location.host + '/')) {
continue
}
uri = u
break
}
if (!uri) {
return null
}
const rawURI = uri.fields.uri.raw
const rawRepoName = normalizeRepoName(rawURI)
return { callsign: repo.fields.callsign, rawRepoName }
}
interface ResolveStagingOptions extends Pick<PlatformContext, 'requestGraphQL'>, RepoSpec, DiffSpec {
baseRev: string
patch?: string
date?: string
authorName?: string
authorEmail?: string
description?: string
}
/**
* Returns the commit ID of the one-off commit created on the Sourcegraph instance for the given
* repo/diffID/patch, creating that commit if needed.
*/
const resolveStagingRev = ({ requestGraphQL, ...variables }: ResolveStagingOptions): Observable<ResolvedRevSpec> =>
requestGraphQL<GQL.IMutation>({
request: gql`
mutation ResolveStagingRev(
$repoName: String!
$diffID: ID!
$baseRev: String!
$patch: String
$date: String
$authorName: String
$authorEmail: String
$description: String
) {
resolvePhabricatorDiff(
repoName: $repoName
diffID: $diffID
baseRev: $baseRev
patch: $patch
date: $date
authorName: $authorName
authorEmail: $authorEmail
description: $description
) {
oid
}
}
`,
variables,
mightContainPrivateInfo: true,
}).pipe(
map(dataOrThrowErrors),
map(({ resolvePhabricatorDiff }) => {
if (!resolvePhabricatorDiff) {
throw new Error('Empty resolvePhabricatorDiff')
}
const { oid } = resolvePhabricatorDiff
if (!oid) {
throw new Error('Could not resolve staging rev: empty oid')
}
return { commitID: oid }
})
)
function hasThisFileChanged(filePath: string, changes: ConduitDiffChange[]): boolean {
for (const change of changes) {
if (change.currentPath === filePath) {
return true
}
}
return false
}
interface ResolveDiffOpt extends RepoSpec, FileSpec, RevisionSpec, DiffSpec, BaseDiffSpec {
isBase: boolean
useDiffForBase: boolean // indicates whether the base should use the diff commit
useBaseForDiff: boolean // indicates whether the diff should use the base commit
}
interface PropsWithDiffDetails extends ResolveDiffOpt {
diffDetails: ConduitDiffDetails
}
function getPropsWithDiffDetails(
props: ResolveDiffOpt,
queryConduit: QueryConduitHelper<any>
): Observable<PropsWithDiffDetails> {
return getDiffDetailsFromConduit(props, queryConduit).pipe(
switchMap(diffDetails => {
if (props.isBase || !props.baseDiffID || hasThisFileChanged(props.filePath, diffDetails.changes)) {
// no need to update props
return of({
...props,
diffDetails,
})
}
return getDiffDetailsFromConduit(props, queryConduit).pipe(
map(
(diffDetails): PropsWithDiffDetails => ({
...props,
diffDetails,
diffID: props.baseDiffID!,
useBaseForDiff: true,
})
)
)
})
)
}
function getStagingDetails(
propsWithInfo: PropsWithDiffDetails
): { repoName: string; ref: ConduitRef; unconfigured: boolean } | undefined {
const stagingInfo = propsWithInfo.diffDetails.properties['arc.staging']
if (!stagingInfo) {
return undefined
}
let key: string
if (propsWithInfo.isBase) {
const type = propsWithInfo.useDiffForBase ? 'diff' : 'base'
key = `refs/tags/phabricator/${type}/${propsWithInfo.diffID}`
} else {
const type = propsWithInfo.useBaseForDiff ? 'base' : 'diff'
key = `refs/tags/phabricator/${type}/${propsWithInfo.diffID}`
}
for (const ref of propsWithInfo.diffDetails.properties['arc.staging'].refs) {
if (ref.ref === key) {
const remote = ref.remote.uri
if (remote) {
return {
repoName: normalizeRepoName(remote),
ref,
unconfigured: stagingInfo.status === 'repository.unconfigured',
}
}
}
}
return undefined
}
interface ResolvedDiff extends ResolvedRevSpec {
/**
* The name of the staging repository, if it is synced to the Sourcegraph instance.
*/
stagingRepoName?: string
}
/**
* Emits the {@link ResolvedDiff} for the base or head commit of a Phabricator diff.
* - If possible, the base commit from the source control repository will be used.
* - If a staging repository is configured and is synced to the Sourcegraph instance,
* the commit ID on the staging repository will be returned, and the {@link ResolvedDiff}
* will include the `stagingRepoName`.
* - If a staging repository is configured but it isn't synced to the Sourcegraph instance,
* a one-off staging commit will be created from the raw diff on the Sourcegraph instance,
* and its commit ID will be returned ({@see resolveStagingRev}).
* - If no staging repository is configured, and the commit doesn't exist on the Sourcegraph instance
* (for example in the case of a revision created through the Phabricator UI from a raw diff), a one-off
* staging commit will be created from the raw diff on the Sourcegraph instance, and its commit ID will
* be returned ({@see resolveStagingRev}).
*
*/
export function resolveDiffRev(
props: ResolveDiffOpt,
requestGraphQL: PlatformContext['requestGraphQL'],
queryConduit: QueryConduitHelper<any>
): Observable<ResolvedDiff> {
return getPropsWithDiffDetails(props, queryConduit).pipe(
switchMap(({ diffDetails, ...props }) => {
const stagingDetails = getStagingDetails({ diffDetails, ...props })
const conduitProps = {
repoName: props.repoName,
diffID: props.diffID,
baseRev: diffDetails.sourceControlBaseRevision,
date: diffDetails.dateCreated,
authorName: diffDetails.authorName,
authorEmail: diffDetails.authorEmail,
description: diffDetails.description,
}
// When resolving the base, use the commit ID from the diff details.
if (props.isBase && !props.useDiffForBase) {
return of({
commitID: diffDetails.sourceControlBaseRevision,
})
}
if (!stagingDetails || stagingDetails.unconfigured) {
// If there are no staging details, get the patch from the conduit API,
// create a one-off commit on the Sourcegraph instance from the patch,
// and resolve to the commit ID returned by the Sourcegraph instance.
return getRawDiffFromConduit(props.diffID, queryConduit).pipe(
switchMap(patch => resolveStagingRev({ ...conduitProps, patch, requestGraphQL }))
)
}
// If staging details are configured, first check if the repo is present on the Sourcegraph instance.
return resolveRepo({ rawRepoName: stagingDetails.repoName, requestGraphQL }).pipe(
// If the repo is present on the Sourcegraph instance,
// use the commitID and repo name from the staging details.
mapTo({
commitID: stagingDetails.ref.commit,
stagingRepoName: stagingDetails.repoName,
}),
// Otherwise, create a one-off commit containing the patch on the Sourcegraph instance,
// and resolve to the commit ID returned by the Sourcegraph instance.
catchError(error => {
if (error.code !== EREPONOTFOUND) {
throw error
}
return getRawDiffFromConduit(props.diffID, queryConduit).pipe(
switchMap(patch => resolveStagingRev({ ...conduitProps, patch, requestGraphQL }))
)
})
)
})
)
}