forked from fedora-ci/ciboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.tsx
More file actions
571 lines (525 loc) · 17.4 KB
/
utils.tsx
File metadata and controls
571 lines (525 loc) · 17.4 KB
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
/*
* This file is part of ciboard
* Copyright (c) 2021, 2022, 2023, 2024 Andrei Stepanov <astepano@redhat.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'lodash';
import moment from 'moment';
import Linkify from 'linkify-react';
import { CSSProperties } from 'react';
import {
InfoIcon,
GhostIcon,
UnlinkIcon,
HistoryIcon,
InProgressIcon,
TimesCircleIcon,
CheckCircleIcon,
TrafficLightIcon,
ExclamationTriangleIcon,
OutlinedQuestionCircleIcon,
} from '@patternfly/react-icons';
import { SVGIconProps } from '@patternfly/react-icons/dist/esm/createIcon';
import { IntermediateRepresentation } from 'linkifyjs';
import { config } from '../config';
import {
AChild,
MSG_V_1,
Artifact,
MSG_V_0_1,
AChildTest,
KojiInstance,
ArtifactType,
isArtifactMbs,
isArtifactRpm,
AChildGreenwave,
DistGitInstance,
MbsInstanceType,
isAChildGreenwave,
BrokerSchemaMsgBody,
GreenwaveRequirementTypes,
isAChildGreenwaveAndTestMsg,
isArtifactRedhatContainerImage,
} from '../types';
import { Icon } from '@patternfly/react-core';
/**
* Typescript guards
*/
// XXX
// ETA + Test -> are all children
// states_eta: StateErrataToolAutomationType[];
const knownAidMeaning: Record<ArtifactType, string> = {
'brew-build': 'Task ID',
'copr-build': 'ID',
'koji-build': 'Task ID',
'koji-build-cs': 'Task ID',
'redhat-module': 'MBS ID',
'productmd-compose': 'Compose',
'redhat-container-image': 'Task ID',
};
export const aidMeaningForType = (type: ArtifactType) => {
const includes = _.includes(_.keys(knownAidMeaning), type);
if (!includes) {
return 'id';
}
return knownAidMeaning[type];
};
export const convertNsvcToNvr = (nsvc: string) => {
const splited = nsvc.split(':');
if (_.size(splited) !== 4) {
console.error(`Encountered invalid NSVC ${nsvc}`);
return null;
}
/**
* Convert NSVC to Koji NVR
*/
return `${splited[0]}-${splited[1].replace(/-/g, '_')}-${splited[2]}.${
splited[3]
}`;
};
export const getReleaseFromNvr = (nvr: string) => {
/**
* Input: foo-1.0-1.el9 or virt-8.3-8030020200812155519.30b713e6
* Release: 1.el9 or 8030020200812155519.30b713e6
* Do steps:
* 1. cut from left to the latest `-`
*/
const cut_from_left = _.lastIndexOf(nvr, '-') + 1;
return nvr.substring(cut_from_left);
};
export const getOSVersionFromNvr = (nvr: string, artifactType: string) => {
/**
* This is not realiable.
* From discussion with dcantrell@: no strict mapping between koji-tag/taget <-> dist-tag
* Return first number from release
* Knowns releases:
* Look for 'el', 'fc' prefix:
* rust-yaml-rust-0.4.4-2.el9 -> Release: 2.el9 -> RHEL: 9
* Modules: first number from release:
* libreoffice-flatpak-8030020201013063128.306be773 -> Release: 8030020201013063128.306be773 -> RHEL: 8
* flatpak-runtime-f33-3320201014073228.eb6bdfed -> Release: 3320201014073228.eb6bdfed -> 33
* kmod-redhat-mlx5_core-5.0_0_dup8.2-1.el8_2 -> Release: 1.el8_2
* Release can have many dots.
*/
const release = getReleaseFromNvr(nvr);
let osVersion;
if (artifactType === 'redhat-module') {
if (/-f\d\d-/.test(nvr)) {
/** Fedora module - take 2 digits. */
osVersion = release.substring(0, 2);
} else {
/** RHEL based. Take 1 digit. */
osVersion = release.substring(0, 1);
}
} else {
/**
* Release : 1.fc32_2
* We discussed with dcantrell@ : and for now solution is to search for pattern: \.(el|fc)[0-9]+
*/
const distTag = release.match(/\.(el|fc)[0-9]+/g)?.toString();
osVersion = distTag?.replace(/\.(el|fc)/, '');
}
console.log('nvr: %s, has os version: %s', nvr, osVersion);
return osVersion;
};
export const getMessageError = (brokerMsgBody: BrokerSchemaMsgBody) => {
if (MSG_V_0_1.isMsg(brokerMsgBody) && 'reason' in brokerMsgBody) {
return {
issue_url: brokerMsgBody.issue_url,
reason: brokerMsgBody.reason,
};
}
if (MSG_V_1.isMsg(brokerMsgBody) && 'error' in brokerMsgBody) {
return brokerMsgBody.error;
}
};
export const getMsgTestNote = (brokerMsgBody: BrokerSchemaMsgBody) => {
let note: string | undefined;
if (MSG_V_0_1.isMsg(brokerMsgBody)) {
note = brokerMsgBody.note;
} else if (MSG_V_1.isMsg(brokerMsgBody)) {
note = brokerMsgBody.test.note;
}
return note;
};
export interface IconProps {
className: string;
icon: React.ComponentClass<SVGIconProps, any>;
label: string;
}
export function mapTypeToIconsProps(type: string): IconProps | null {
const icons = {
missing: {
pick: type === 'missing' || type === 'test-result-missing',
className: 'pf-v5-u-disabled-color-100',
icon: GhostIcon,
label: 'Result is missing.',
},
ok: {
pick:
type === 'complete' ||
type === 'passed' ||
type === 'pass' ||
type === 'test-result-passed' ||
type === 'fetched-gating-yaml' ||
type === 'true',
className: 'pf-v5-u-success-color-100',
icon: CheckCircleIcon,
label: 'Result is OK.',
},
error: {
pick:
type === 'failed' ||
type === 'fail' ||
type === 'failed-fetch-gating-yaml' ||
type === 'test-result-failed' ||
type === 'invalid-gating-yaml' ||
type === 'missing-gating-yaml' ||
type === 'false',
className: 'pf-v5-u-danger-color-100',
icon: TimesCircleIcon,
label: 'Test has failed.',
},
warning: {
pick:
type === 'error' ||
type === 'needs_inspection' ||
type === 'invalid-gating-yaml-waived' ||
type === 'missing-gating-yaml-waived' ||
type === 'test-result-errored' ||
type === 'test-result-failed-waived' ||
type === 'test-result-missing-waived' ||
type === 'test-result-errored-waived' ||
type === 'failed-fetch-gating-yaml-waived',
className: 'pf-v5-u-warning-color-100',
icon: ExclamationTriangleIcon,
label: 'Test run resulted in an error.',
},
progress: {
pick: type === 'running',
className: 'pf-v5-u-link-color',
icon: InProgressIcon,
label: 'Test is in progress.',
},
history: {
pick: type === 'queued',
className: 'pf-v5-u-warning-color-100',
icon: HistoryIcon,
label: 'Test is queued.',
},
info: {
pick:
type === 'info' ||
type === 'excluded' ||
type === 'blacklisted',
className: 'pf-v5-u-info-color-100',
icon: InfoIcon,
label: 'Result has additinal info.',
},
skip: {
pick: type === 'skip',
className: 'pf-v5-u-warning-color-100',
icon: UnlinkIcon,
label: 'Test was skipped.',
},
not_applicable: {
pick: type === 'not_applicable',
className: 'pf-v5-u-info-color-100',
icon: InfoIcon,
label: 'Test was skipped.',
},
};
type KnownIconsType = keyof typeof icons;
const name = _.findKey(icons, (i) => i.pick);
if (!name) return null;
return _.pick(icons[name as KnownIconsType], [
'className',
'icon',
'label',
]);
}
export const isGatingArtifact = (artifact: Artifact): boolean => {
if (
(isArtifactRpm(artifact) || isArtifactMbs(artifact)) &&
_.endsWith(artifact.hit_source.gateTag, '-gate')
) {
return true;
} else if (isArtifactRedhatContainerImage(artifact)) {
/* Container builds are gated by Errata Tool */
return true;
}
return false;
};
export interface TestStatusIconProps {
/**
* String indicating the status/outcome of the test.
* Examples: 'pass', 'failed', 'error', 'info'.
*/
status: string;
/** Additional styling for the icon. */
style?: CSSProperties;
}
export function TestStatusIcon(props: TestStatusIconProps) {
const statusLower = props.status.toLowerCase();
const iconProps = mapTypeToIconsProps(statusLower);
if (!iconProps) {
console.warn('Asked to render icon with unknown status:', props.status);
return (
<OutlinedQuestionCircleIcon aria-label="Result is unknown type." />
);
}
let SelectedIcon = iconProps.icon;
return (
<Icon size="sm">
<SelectedIcon
style={props.style}
title={iconProps.label}
aria-label={iconProps.label}
className={iconProps.className}
/>
</Icon>
);
}
export interface GatingStatusIconProps {
/** Boolean indicating whether gating has passed. The default is false. */
status?: boolean;
/** Additional styling for the icon. */
style?: CSSProperties;
}
export function GatingStatusIcon(props: GatingStatusIconProps) {
let className = 'pf-v5-u-danger-color-100';
let label = 'Gating is blocked';
if (props.status) {
className = 'pf-v5-u-success-color-100';
label = 'Gating has passed';
}
return (
<Icon size="sm">
<TrafficLightIcon
style={props.style}
title={label}
aria-label={label}
className={className}
/>
</Icon>
);
}
const SCM_COMMIT_URL_REGEX =
/\/(rpms|modules)\/([\w-]+)(?:\.git)?\/?\??#([0-9a-fA-F]+)$/;
export interface ScmUrlComponents {
commit: string;
name: string;
namespace: string;
}
export const parseScmUrl = (source: string): ScmUrlComponents | undefined => {
const match = SCM_COMMIT_URL_REGEX.exec(source);
if (!match) {
console.error(`Could not parse SCM URL: ${source}`);
return;
}
const [, namespace, name, commit] = match;
return { namespace, name, commit };
};
export const mkCommitHashFromSource = (source: string): string | undefined => {
const components = parseScmUrl(source);
if (!components) return;
return components.commit;
};
/**
* Transforms
*
* from:
* git://pkgs.devel.redhat.com/rpms/bash#4cbab69537d8401a4c9b3c326f25fa95c5f6f6ee
*
* to:
* http://pkgs.devel.redhat.com/cgit/rpms/bash/commit/?id=4cbab69537d8401a4c9b3c326f25fa95c5f6f6ee
*/
export const mkLinkPkgsDevelFromSource = (
source: string,
instance: KojiInstance,
) => {
const components = parseScmUrl(source);
if (!components) return '';
const { namespace, name, commit } = components;
switch (instance) {
case 'cs':
return `https://gitlab.com/redhat/centos-stream/${namespace}/${name}/-/commit/${commit}`;
case 'pn':
return `https://gitlab.com/redhat/rhel/${namespace}/${name}/-/commit/${commit}`;
case 'fp':
return `https://src.fedoraproject.org/${namespace}/${name}/c/${commit}`;
case 'rh':
return `https://pkgs.devel.redhat.com/cgit/${namespace}/${name}/commit/?id=${commit}`;
default:
console.warn(`Unknown Koji instance: ${instance}`);
return '';
}
};
export const mkLinkFileInGit = (
repoName: string,
namespace: 'rpms' | 'modules',
commit: string,
fileName: string,
instance: DistGitInstance,
) => {
switch (instance) {
case 'cs':
return `https://gitlab.com/redhat/centos-stream/${namespace}/${repoName}/-/blob/${commit}/${fileName}`;
case 'pn':
return `https://gitlab.com/redhat/rhel/${namespace}/${repoName}/-/blob/${commit}/${fileName}`;
case 'fp':
return `https://src.fedoraproject.org/${namespace}/${repoName}/blob/${commit}/f/${fileName}`;
case 'rh':
return `https://pkgs.devel.redhat.com/cgit/${namespace}/${repoName}/tree/${fileName}?h=${commit}`;
default:
console.warn(`Unknown Dist-Git instance: ${instance}`);
return '';
}
};
export const mkLinkMbsBuild = (
buildId: number | string,
instance: MbsInstanceType,
) => {
if (!_.has(config.mbs, instance)) {
console.warn(`Unknown MBS instance: ${instance}`);
return;
}
const mbsUrlPrefix = config.mbs[instance].webUrl;
if (!mbsUrlPrefix) {
console.warn(`MBS web UI not available for ${instance}`);
return;
}
return `${mbsUrlPrefix}/module/${buildId}`;
};
export const mkLinkKojiWebBuildId = (
buildId: number | string,
instance: KojiInstance,
) => {
if (!_.has(config.koji, instance)) {
console.error(`Unknown Koji instance: ${instance}`);
return '';
}
const kojiUrlPrefix = config.koji[instance].webUrl;
return `${kojiUrlPrefix}/buildinfo?buildID=${buildId}`;
};
export const mkLinkKojiWebTask = (
taskId: number | string,
instance: KojiInstance,
) => {
if (!_.has(config.koji, instance)) {
console.error(`Unknown Koji instance: ${instance}`);
return '';
}
const kojiUrlPrefix = config.koji[instance].webUrl;
return `${kojiUrlPrefix}/taskinfo?taskID=${taskId}`;
};
export const mkLinkKojiWebUserId = (
userId: number | string,
instance: KojiInstance,
) => {
if (!_.has(config.koji, instance)) {
console.error(`Unknown Koji instance: ${instance}`);
return '';
}
const kojiUrlPrefix = config.koji[instance].webUrl;
return `${kojiUrlPrefix}/userinfo?userID=${userId}`;
};
export const mkLinkKojiWebTagId = (
tagId: number | string,
instance: KojiInstance,
) => {
if (!_.has(config.koji, instance)) {
console.error(`Unknown Koji instance: ${instance}`);
return '';
}
const kojiUrlPrefix = config.koji[instance].webUrl;
return `${kojiUrlPrefix}/taginfo?tagID=${tagId}`;
};
/**
* List of Greenwave requirement types that are considered as satisfied.
* See [Greenwave documentation](https://gating-greenwave.readthedocs.io/en/latest/decision_requirements.html)
* for details.
*/
const SATISFIED_REQUIREMENT_TYPES: GreenwaveRequirementTypes[] = [
'blacklisted',
'excluded',
'fetched-gating-yaml',
'test-result-passed',
];
const isRequirementSatisfied = (aChild: AChildGreenwave): boolean => {
if (!aChild.requirement) {
return true;
}
return _.includes(SATISFIED_REQUIREMENT_TYPES, aChild.requirement?.type);
};
/**
* Should we display a waive button for this result in the dashboard?
* Show the button only if the test is blocking gating.
* Greenwave shows all known tests from ResultsDB.
* @param aChild The state object of the test result in question.
*/
export const isResultWaivable = (aChild: AChild): boolean => {
if (isAChildGreenwaveAndTestMsg(aChild))
return !isRequirementSatisfied(aChild.gs);
if (isAChildGreenwave(aChild)) return !isRequirementSatisfied(aChild);
return false;
};
/**
* List of Greenwave requirement types that we consider as missing.
*/
const MISSING_REQUIREMENT_TYPES: GreenwaveRequirementTypes[] = [
'missing-gating-yaml',
'missing-gating-yaml-waived',
'test-result-missing',
'test-result-missing-waived',
];
const isRequirementMissing = (aChild: AChildGreenwave): boolean =>
_.includes(MISSING_REQUIREMENT_TYPES, aChild.requirement?.type);
/**
* Check if the Greenwave state is missing the required test result.
* @param child The Greenwave state to check.
* @returns `true` if the required result is missing in Greenwave, `false` otherwise.
*/
export const isResultMissing = (aChild: AChildTest): boolean => {
if (isAChildGreenwaveAndTestMsg(aChild))
return isRequirementMissing(aChild.gs);
if (isAChildGreenwave(aChild)) return isRequirementMissing(aChild);
return false;
};
export const timestampForUser = (
timestamp: string,
includeRelative = false,
): string => {
const localTime = moment.utc(timestamp).local();
const timestampWithTz = localTime.format('YYYY-MM-DD HH:mm Z');
if (!includeRelative) {
return timestampWithTz;
}
const fromNow = localTime.fromNow();
return `${timestampWithTz} (${fromNow})`;
};
const renderNewTabLink: (ir: IntermediateRepresentation) => React.ReactNode = ({
attributes,
content,
}) => (
<a {...attributes} rel="noopener noreferrer" target="_blank">
{content}
</a>
);
export type LinkifyNewTabProps = React.PropsWithChildren<{}>;
export const LinkifyNewTab = (props: LinkifyNewTabProps) => (
<Linkify options={{ render: renderNewTabLink }}>{props.children}</Linkify>
);