-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
travisGo.ts
328 lines (311 loc) · 13.3 KB
/
travisGo.ts
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
import { flatten } from 'lodash'
import { from, Observable, of, Subscription, Unsubscribable } from 'rxjs'
import {
map,
publishReplay,
refCount,
startWith,
switchMap,
toArray,
tap,
first,
delay,
debounceTime,
filter,
} from 'rxjs/operators'
import * as sourcegraph from 'sourcegraph'
import { combineLatestOrDefault } from '../../../../shared/src/util/rxjs/combineLatestOrDefault'
import { isDefined } from '../../../../shared/src/util/types'
import { MAX_RESULTS, OTHER_CODE_ACTIONS, REPO_INCLUDE } from './misc'
import { memoizedFindTextInFiles } from './util'
const TAG_TRAVIS_GO = 'travis-go'
const diagnosticCollection = sourcegraph.languages.createDiagnosticCollection('demo0')
export function registerTravisGo(): Unsubscribable {
const subscriptions = new Subscription()
subscriptions.add(startDiagnostics())
subscriptions.add(registerStatusProvider(diagnostics, diagnosticCollection))
subscriptions.add(sourcegraph.languages.registerCodeActionProvider(['*'], createCodeActionProvider()))
return subscriptions
}
function startDiagnostics(): Unsubscribable {
const subscriptions = new Subscription()
subscriptions.add(diagnosticCollection)
subscriptions.add(
diagnostics.subscribe(entries => {
diagnosticCollection.set(entries)
})
)
return subscriptions
}
const FIX_GO_VERSION_COMMAND_ID = 'travis-ci.fixGoVersion'
interface FixGoVersionParams {}
function registerStatusProvider(
diagnostics: Observable<[URL, sourcegraph.Diagnostic[]][]>,
diagnosticCollection: sourcegraph.DiagnosticCollection
): Unsubscribable {
const subscriptions = new Subscription()
subscriptions.add(
sourcegraph.status.registerStatusProvider('travis-ci', {
provideStatus: (scope): sourcegraph.Subscribable<sourcegraph.Status | null> => {
// TODO!(sqs): dont ignore scope
return diagnostics.pipe(
switchMap<[URL, sourcegraph.Diagnostic[]][], Promise<sourcegraph.Status>>(async diagnostics => ({
title: 'Travis CI',
state: {
completion: sourcegraph.CheckResult.Completed,
result: sourcegraph.CheckResult.Success,
message: 'All builds passing, all repository configuration valid and up-to-date',
},
sections: {
settings: {
kind: sourcegraph.MarkupKind.Markdown,
value: `Require all projects to configure Travis CI`,
},
notifications: {
kind: sourcegraph.MarkupKind.Markdown,
value: `Notify **@sourcegraph/devops** of changes to Travis CI configuration`,
},
},
diagnostics: diagnosticCollection,
})),
startWith<sourcegraph.Status>({
title: 'Travis CI',
state: { completion: sourcegraph.CheckResult.InProgress },
})
)
},
})
)
subscriptions.add(
sourcegraph.notifications.registerNotificationProvider('travis-ci', {
provideNotifications: scope =>
// TODO!(sqs): dont ignore scope
diagnostics.pipe(
switchMap(async diagnostics => [
{
message: 'Build failures on default branch',
type: sourcegraph.NotificationType.Error,
actions: [
{
command: {
command: 'TODO!(sqs)',
title: 'sourcegraph/codeintellify (31 minutes ago)',
},
},
{
command: {
command: 'TODO!(sqs)',
title: 'sourcegraph/go-diff (7 hours ago)',
},
},
{
command: {
command: 'TODO!(sqs)',
title: 'sourcegraph/syntect_server (1 day ago)',
},
},
],
},
...((diagnostics.length > 0
? [
{
message: 'Outdated Go version specified in Travis CI configuration',
type: sourcegraph.NotificationType.Info,
actions: [
{
plan: {
title: 'Use latest Go version in all .travis.yml files',
operations: [
{
command: {
command: FIX_GO_VERSION_COMMAND_ID,
},
},
],
},
},
{
command: {
command: 'TODO!(sqs)',
title: 'Change preferred Go version (1.13)',
},
},
],
},
]
: []) as sourcegraph.Notification[]),
{
message: 'Missing Travis CI configuration',
type: sourcegraph.NotificationType.Warning,
actions: [
{
plan: {
title: 'Infer .travis.yml (best-effort) for repositories lacking it',
operations: [
{
command: {
command: 'TODO!(sqs)',
},
},
],
},
},
],
},
])
),
})
)
subscriptions.add(
sourcegraph.commands.registerActionEditCommand(
FIX_GO_VERSION_COMMAND_ID,
async (diagnostic: sourcegraph.Diagnostic) => {
const { edit } = await computeFixAllActionsFromDiagnostics([diagnostic])
return edit
}
)
)
return subscriptions
}
const diagnostics: Observable<[URL, sourcegraph.Diagnostic[]][]> = from(sourcegraph.workspace.rootChanges).pipe(
startWith(void 0),
map(() => sourcegraph.workspace.roots),
switchMap(async roots => {
if (roots.length > 0) {
return of<[URL, sourcegraph.Diagnostic[]][]>([]) // TODO!(sqs): dont run in comparison mode
}
const results = flatten(
await from(
memoizedFindTextInFiles(
{ pattern: '', type: 'regexp' },
{
repositories: {
includes: [REPO_INCLUDE],
type: 'regexp',
},
files: {
includes: ['\\.travis\\.yml$'],
type: 'regexp',
},
maxResults: MAX_RESULTS,
}
)
)
.pipe(toArray())
.toPromise()
)
return combineLatestOrDefault(
results.map(async ({ uri }) => {
const { text } = await sourcegraph.workspace.openTextDocument(new URL(uri))
const diagnostics: sourcegraph.Diagnostic[] = flatten(
findMatchRanges(text, /(^go:)|(^language: go)/g)
.slice(0, 1)
.map(
range =>
({
message: 'Outdated Go version used in Travis CI',
range,
severity: sourcegraph.DiagnosticSeverity.Warning,
tags: [TAG_TRAVIS_GO],
} as sourcegraph.Diagnostic)
)
)
return [new URL(uri), diagnostics] as [URL, sourcegraph.Diagnostic[]]
})
).pipe(map(items => items.filter(isDefined)))
}),
switchMap(results => results),
publishReplay(),
refCount() //TODO!(sqs): or just share()?
)
function createCodeActionProvider(): sourcegraph.CodeActionProvider {
return {
provideCodeActions: async (doc, _rangeOrSelection, context): Promise<sourcegraph.Action[]> => {
const diag = context.diagnostics.find(isTravisGoDiagnostic)
if (!diag) {
return []
}
const fixAllAction = await computeFixAllAction()
return [
{
title: 'Use current Go version',
edit: computeFixEdit(diag, doc),
diagnostics: [diag],
},
fixAllAction.edit && Array.from(fixAllAction.edit.textEdits()).length > 1
? {
title: `Fix in all ${Array.from(fixAllAction.edit.textEdits()).length} repositories`,
...fixAllAction,
}
: null,
{
title: `View Travis CI docs`,
command: {
title: '',
command: 'open',
arguments: ['https://docs.travis-ci.com/user/languages/go/'],
},
diagnostics: [diag],
},
...OTHER_CODE_ACTIONS,
].filter(isDefined)
},
}
}
function isTravisGoDiagnostic(diag: sourcegraph.Diagnostic): boolean {
return diag.tags && diag.tags.includes(TAG_TRAVIS_GO)
}
function computeFixEdit(
diag: sourcegraph.Diagnostic,
doc: sourcegraph.TextDocument,
edit = new sourcegraph.WorkspaceEdit()
): sourcegraph.WorkspaceEdit {
if (!doc.text.includes('1.13.x')) {
const ranges = findMatchRanges(doc.text, /^go:/g)
if (ranges.length > 0) {
for (const range of ranges) {
edit.insert(new URL(doc.uri), range.end, `\n - "1.13.x"`)
}
} else {
edit.insert(new URL(doc.uri), doc.positionAt(doc.text.length), `\n\ngo:\n - "1.13.x"\n`)
}
}
return edit
}
async function computeFixAllAction(): Promise<Pick<sourcegraph.Action, 'edit' | 'diagnostics'>> {
// TODO!(sqs): Make this listen for new diagnostics and include those too, but that might be
// super inefficient because it's n^2, so maybe an altogether better/different solution is
// needed.
const allTravisGoDiags = sourcegraph.languages
.getDiagnostics()
.map(([uri, diagnostics]) => {
const matchingDiags = diagnostics.filter(isTravisGoDiagnostic)
return matchingDiags.length > 0
? ([uri, matchingDiags] as ReturnType<typeof sourcegraph.languages.getDiagnostics>[0])
: null
})
.filter(isDefined)
return computeFixAllActionsFromDiagnostics(allTravisGoDiags)
}
async function computeFixAllActionsFromDiagnostics(
diagnostics: sourcegraph.Diagnostic[]
): Promise<Pick<sourcegraph.Action, 'edit' | 'diagnostics'>> {
const edit = new sourcegraph.WorkspaceEdit()
for (const diag of diagnostics) {
const doc = await sourcegraph.workspace.openTextDocument(diag.resource)
computeFixEdit(diag, doc, edit)
}
return { edit, diagnostics: diagnostics }
}
function findMatchRanges(text: string, pattern: RegExp): sourcegraph.Range[] {
const lines = text.split('\n')
const ranges: sourcegraph.Range[] = []
for (const [i, line] of lines.entries()) {
pattern.lastIndex = 0
const match = pattern.exec(line)
if (match) {
ranges.push(new sourcegraph.Range(i, match.index, i, match.index + match[0].length))
}
}
return ranges
}