-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathding.ts
1770 lines (1656 loc) · 65.3 KB
/
ding.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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let rootElem: HTMLElement
let crumbElem = dom.span()
let updateElem = dom.span()
let pageElem = dom.div(style({padding: '1em'}))
const client = new api.Client()
const colors = {
green: '#66ac4c',
blue: 'rgb(70, 158, 211)',
red: 'rgb(228, 77, 52)',
gray: 'rgb(138, 138, 138)',
}
let favicon = dom.link(attr.rel('icon'), attr.href('favicon.ico')) // attr.href changed for some build states
let favicons = {
default: 'favicon.ico', // blue
green: 'favicon-green.png',
red: 'favicon-red.png',
gray: 'favicon-gray.png',
}
const setFavicon = (href: string) => {
favicon.setAttribute('href', href)
}
const buildSetFavicon = (b: api.Build) => {
if (!b.Finish) {
setFavicon(favicons.gray)
} else if (b.Status !== api.BuildStatus.StatusSuccess) {
setFavicon(favicons.red)
} else {
setFavicon(favicons.green)
}
}
const link = (href: string, anchor: string) => dom.a(attr.href(href), anchor)
interface TargetDisableable {
target: {
disabled: boolean
}
}
class Stream<T> {
subscribers: ((e: T) => void)[] = []
send(e: T) {
this.subscribers.forEach(fn => fn(e))
}
subscribe(fn: (e: T) => void): (() => void) {
this.subscribers.push(fn)
return () => {
this.subscribers = this.subscribers.filter(s => s !== fn)
}
}
}
const streams = {
repo: new Stream<api.EventRepo>(),
removeRepo: new Stream<api.EventRemoveRepo>(),
build: new Stream<api.EventBuild>(),
removeBuild: new Stream<api.EventRemoveBuild>(),
output: new Stream<api.EventOutput>(),
}
let sseElem = dom.span('Disconnected from live updates.') // Shown in UI next to logout button.
let eventSource: EventSource // We initialize it after first success API call.
let allowReconnect = false
const initEventSource = () => {
// todo: update ui that we are busy connecting
dom._kids(sseElem, 'Connecting...')
eventSource = new window.EventSource('events?password='+encodeURIComponent(password))
eventSource.addEventListener('open', function() {
allowReconnect = true
dom._kids(sseElem)
})
eventSource.addEventListener('error', function(event: Event) {
console.log('sse connection error', event)
if (allowReconnect) {
allowReconnect = false
initEventSource()
} else {
// todo: on window focus, we could do another reconnect attempt, timethrottled.
dom._kids(sseElem,
'Connection error for live updates. ',
dom.clickbutton('Reconnect', function click() {
dom._kids(sseElem)
initEventSource()
}),
)
}
})
eventSource.addEventListener('repo', (e: MessageEvent) => streams.repo.send(api.parser.EventRepo(JSON.parse(e.data))))
eventSource.addEventListener('removeRepo', (e: MessageEvent) => streams.removeRepo.send(api.parser.EventRemoveRepo(JSON.parse(e.data))))
eventSource.addEventListener('build', (e: MessageEvent) => streams.build.send(api.parser.EventBuild(JSON.parse(e.data))))
eventSource.addEventListener('removeBuild', (e: MessageEvent) => streams.removeBuild.send(api.parser.EventRemoveBuild(JSON.parse(e.data))))
eventSource.addEventListener('output', (e: MessageEvent) => streams.output.send(api.parser.EventOutput(JSON.parse(e.data))))
}
// Atexit helps run cleanup code when a page is unloaded. A page has an atexit to
// which functions can be added. Pages that can rerender parts of their contents
// can create a new atexit for a part, register the cleanup function with their
// page (or higher level atexit), and call run to cleanup before rerendering.
class Atexit {
fns: (() => void)[] = []
run() {
for (const fn of this.fns) {
fn()
}
this.fns = []
}
add(fn: () => void) {
this.fns.push(fn)
}
age(start: Date, end?: Date) {
const [elem, close] = age0(false, start, end)
this.add(close)
return elem
}
ageMins(start: Date, end?: Date) {
const [elem, close] = age0(true,start, end)
this.add(close)
return elem
}
}
// Page is a loaded page, used to clean up references to event streams and timers.
class Page {
atexit = new Atexit()
updateRoot?: HTMLElement // Box holding status about SSE connection.
newAtexit(): Atexit {
const atexit = new Atexit()
this.atexit.add(() => atexit.run())
return atexit
}
cleanup() {
this.atexit.run()
}
subscribe<T>(s: Stream<T>, fn: (e: T) => void) {
this.atexit.add(s.subscribe(fn))
}
}
let loginPromise: Promise<void> | undefined
let password = ''
// authed calls fn and awaits the promise it returns. If the promise fails with an
// error object with .code 'user:badAuth', it shows a popup for a password, then
// calls the function again through authed for any password retries.
const authed = async <T>(fn: () => Promise<T>, elem?: {disabled: boolean}): Promise<T> => {
const overlay = dom.div(style({position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 2, backgroundColor: '#ffffff00'}))
document.body.append(overlay)
pageElem.classList.toggle('loading', true)
if (elem) {
elem.disabled = true
}
const done = () => {
overlay.remove()
pageElem.classList.toggle('loading', false)
if (elem) {
elem.disabled = false
}
}
try {
const r = await fn()
done()
if (!eventSource) {
initEventSource()
}
return r
} catch (err: any) {
done()
if (err.code !== 'user:noAuth') {
alert('Error: '+err.message)
}
if (err.code === 'user:badAuth' || err.code === 'user:noAuth') {
if (!loginPromise) {
let passwordElem: HTMLInputElement
loginPromise = new Promise((resolve) => {
const close = popupOpts(true,
dom.h1('Login'),
dom.form(
function submit(e: SubmitEvent) {
e.stopPropagation()
e.preventDefault()
password = passwordElem.value
try {
window.localStorage.setItem('dingpassword', password)
} catch (err) {
console.log('setting session storage', err)
}
resolve()
close()
},
dom.fieldset(
dom.div(
dom.label(
dom.div('Password'),
passwordElem=dom.input(attr.type('password'), attr.required('')),
),
),
dom.br(),
dom.div(dom.submitbutton('Login')),
),
),
)
passwordElem.focus()
})
await loginPromise
loginPromise = undefined
} else {
await loginPromise
}
return await authed(fn, elem)
}
throw err
}
}
const formatCoverage = (repo: api.Repo, b: api.Build) => {
const anchor = b.Coverage ? (Math.round(b.Coverage)+'%') : 'report'
if (b.CoverageReportFile && !b.BuilddirRemoved) {
return dom.a(attr.href('dl/file/'+encodeURIComponent(repo.Name)+'/'+b.ID + '/' + b.CoverageReportFile), anchor)
}
return anchor === 'report' ? '' : anchor
}
const age0 = (mins: boolean, start: Date, end?: Date | undefined): [HTMLElement, () => void] => {
const second = 1
const minute = 60*second
const hour = 60*minute
const day = 24*hour
const week = 7*day
const year = 365*day
const periods = [year, week, day, hour, minute, second]
const suffix = ['y', 'w', 'd', 'h', 'm', 's']
const elem = dom.span(attr.title(start.toString()))
let id = 0
const cleanup = () => {
if (id) {
window.clearTimeout(id)
id = 0
}
}
const set = () => {
const e = (end || new Date()).getTime()/1000
let t = e - start.getTime()/1000
let nextSecs = 0
let s = ''
for (let i = 0; i < periods.length; i++) {
const p = periods[i]
if (t >= 2*p || i === periods.length-1 || mins && p === minute) {
if (p == second && t < 10*second) {
nextSecs = 0.1
s = t.toFixed(1)+'s'
break
}
const n = Math.round(t/p)
s = '' + n + suffix[i]
const prev = Math.floor(t/p)
nextSecs = Math.ceil((prev+1)*p - t)
break
}
}
if (!mins && !end) {
s += '...'
}
dom._kids(elem, s)
// note: Cannot have delays longer than 24.8 days due to storage as 32 bit in
// browsers. Session is likely closed/reloaded/refreshed before that time anyway.
return Math.min(nextSecs, 14*24*3600)
}
if (end) {
set()
return [elem, cleanup]
}
const refresh = () => {
const nextSecs = set()
id = window.setTimeout(refresh, nextSecs*1000)
}
refresh()
return [elem, cleanup]
}
const formatSize = (size: number) => (size/(1024*1024)).toFixed(1) + 'm'
const formatBuildSize = (b: api.Build) =>
dom.span(
attr.title('Disk usage of build directory (including checkout directory), and optional difference in size of (reused) home directory'),
formatSize(b.DiskUsage) + (b.HomeDiskUsageDelta ? (b.HomeDiskUsageDelta > 0 ? '+' : '')+formatSize(b.HomeDiskUsageDelta) : '')
)
const statusColor = (b: api.Build) => {
if (b.ErrorMessage || b.Finish && b.Status !== api.BuildStatus.StatusSuccess) {
return colors.red
} else if (b.Released) {
return colors.blue
} else if (b.Finish) {
return colors.green
} else {
return colors.gray
}
}
const buildStatus = (b: api.Build) => {
let s: string = b.Status
if (b.Status === api.BuildStatus.StatusNew && b.LowPrio) {
s += '↓'
}
return dom.span(s, style({fontSize: '.9em', color: 'white', backgroundColor: statusColor(b), padding: '0 .2em', borderRadius: '.15em'}))
}
const buildErrmsg = (b: api.Build) => {
let msg = b.ErrorMessage
if (b.ErrorMessage && b.LastLine) {
msg += ', "'+b.LastLine+'"'
}
return msg ? dom.span(style({maxWidth: '40em', display: 'inline-block'}), msg) : []
}
const popupOpts = (opaque: boolean, ...kids: ElemArg[]) => {
const origFocus = document.activeElement
const close = () => {
if (!root.parentNode) {
return
}
root.remove()
if (origFocus && origFocus instanceof HTMLElement && origFocus.parentNode) {
origFocus.focus()
}
}
let content: HTMLElement
const root = dom.div(
style({position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: opaque ? '#ffffff' : 'rgba(0, 0, 0, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: opaque ? 3 : 1}),
opaque ? [] : [
function keydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation()
close()
}
},
function click(e: MouseEvent) {
e.stopPropagation()
close()
},
],
content=dom.div(
attr.tabindex('0'),
style({backgroundColor: 'white', borderRadius: '.25em', padding: '1em', boxShadow: '0 0 20px rgba(0, 0, 0, 0.1)', border: '1px solid #ddd', maxWidth: '95vw', overflowX: 'auto', maxHeight: '95vh', overflowY: 'auto'}),
function click(e: MouseEvent) {
e.stopPropagation()
},
kids,
)
)
document.body.appendChild(root)
content.focus()
return close
}
const popup = (...kids: ElemArg[]) => popupOpts(false, ...kids)
const popupRepoAdd = async (haveBubblewrap: boolean, haveGoToolchainDir: boolean) => {
let vcs: HTMLSelectElement
let origin: HTMLInputElement | HTMLTextAreaElement
let originBox: HTMLElement
let originInput: HTMLInputElement
let originTextarea: HTMLTextAreaElement
let name: HTMLInputElement
let defaultBranch: HTMLInputElement
let reuseUID: HTMLInputElement
let bubblewrap: HTMLInputElement
let bubblewrapNoNet: HTMLInputElement
let buildOnUpdatedToolchain: HTMLInputElement
let goauto: HTMLInputElement
let gocur: HTMLInputElement
let goprev: HTMLInputElement
let gonext: HTMLInputElement
let fieldset: HTMLFieldSetElement
let branchChanged = false
let nameChanged = false
const originTextareaBox = dom.div(
originTextarea=dom.textarea(attr.required(''), attr.rows('5'), style({width: '100%'})),
dom.div('Script that clones a repository into checkout/$DING_CHECKOUTPATH.'),
dom.div('Typically starts with "#!/bin/sh".'),
dom.div('It must print a line of the form "commit: ...".'),
dom.br(),
)
const vcsChanged = function change() {
if (!branchChanged) {
if (vcs.value === 'git') {
defaultBranch.value = 'main'
} else if (vcs.value === 'mercurial') {
defaultBranch.value = 'default'
} else if (vcs.value === 'command') {
defaultBranch.value = ''
}
}
if (vcs.value !== 'command') {
const n = dom.div(originInput)
originBox.replaceWith(n)
originBox = n
origin = originInput
} else {
originBox.replaceWith(originTextareaBox)
originBox = originTextareaBox
origin = originTextarea
}
}
const close = popup(
dom.h1('New repository'),
dom.form(
async function submit(e: SubmitEvent) {
e.stopPropagation()
e.preventDefault()
const repo: api.Repo = {
Name: name.value,
VCS: vcs.value as api.VCS,
Origin: origin.value,
DefaultBranch: defaultBranch.value,
UID: reuseUID.checked ? 1 : null,
CheckoutPath: name.value,
Bubblewrap: bubblewrap.checked,
BubblewrapNoNet: bubblewrapNoNet.checked,
BuildOnUpdatedToolchain: buildOnUpdatedToolchain.checked,
WebhookSecret: '',
AllowGlobalWebhookSecrets: false,
BuildScript: '',
HomeDiskUsage: 0,
GoAuto: goauto.checked,
GoCur: gocur.checked,
GoPrev: goprev.checked,
GoNext: gonext.checked,
}
const r = await authed(() => client.RepoCreate(password, repo), fieldset)
location.hash = '#repo/'+encodeURIComponent(r.Name)
close()
},
fieldset=dom.fieldset(
dom.div(
style({display: 'grid', columnGap: '1em', rowGap: '.5ex', gridTemplateColumns: 'min-content 1fr', alignItems: 'top'}),
dom.span('VCS', attr.title('Clones are run as the configured ding user, not under a unique/reused UID. After cloning, file permissions are fixed up. Configure an .ssh/config and/or ssh keys in the home directory of the ding user.')),
vcs=dom.select(
dom.option('git'),
dom.option('mercurial'),
dom.option('command'),
vcsChanged,
),
'Origin',
originBox=dom.div(originInput=origin=dom.input(attr.required(''), attr.placeholder('https://... or ssh://... or user@host:path.git'), style({width: '100%'}), function keyup() {
if (nameChanged) {
return
}
let t = origin.value.split('/')
let s = t[t.length-1] || t[t.length-2] || ''
s = s.replace(/\.git$/, '')
name.value = s
})),
'Name',
name=dom.input(attr.required(''), function change() { nameChanged = true }),
dom.div('Default branch', style({whiteSpace: 'nowrap'})),
defaultBranch=dom.input(attr.value('main'), attr.placeholder('main, master, default'), function change() { branchChanged = true }),
dom.div(),
dom.label(
reuseUID=dom.input(attr.type('checkbox'), attr.checked('')),
' Reuse $HOME and UID for builds for this repo',
attr.title('By reusing $HOME and running builds for this repository under the same UID, build caches can be used. This typically leads to faster builds but reduces isolation of builds.'),
),
dom.div(),
dom.label(
bubblewrap=dom.input(attr.type('checkbox'), haveBubblewrap ? attr.checked('') : []),
' Run build script in bubblewrap, with limited system access',
attr.title('Only available on Linux, with bubblewrap (bwrap) installed. Commands are run in a new mount namespace with access to system directories like /bin /lib /usr, and to the ding build, home and toolchain directories.'),
),
dom.div(),
dom.label(
bubblewrapNoNet=dom.input(attr.type('checkbox'), haveBubblewrap ? attr.checked('') : []),
' Prevent network access from build script. Only active if bubblewrap is active.',
attr.title('Hide network interfaces from the build script. Only a loopback device is available.'),
),
dom.div('Build for Go toolchains', style({whiteSpace: 'nowrap'}), attr.title('The build script will be run for each of the selected Go toolchains. The short name (go, goprev, gonext) is set in $DING_GOTOOLCHAIN. If this build was triggered due to a new Go toolchain being installed, the variable $DING_NEWGOTOOLCHAIN is set.')),
dom.div(
dom.label(
goauto=dom.input(attr.type('checkbox'), haveGoToolchainDir ? attr.checked('') : '', function change() {
if (goauto.checked) {
gocur.checked = false
goprev.checked = false
gonext.checked = false
}
}),
' Automatic',
attr.title('Build for each of the available Go toolchains, go/goprev/gonext. At least one must be found or the build will fail.'),
), ' ',
dom.label(
gocur=dom.input(attr.type('checkbox'), function change() { goauto.checked = false }),
' Go latest',
attr.title('Latest patch version of latest stable Go toolchain version.'),
), ' ',
dom.label(
goprev=dom.input(attr.type('checkbox'), function change() { goauto.checked = false }),
' Go previous',
attr.title('Latest patch version of Go toolchain minor version before the latest stable.'),
), ' ',
dom.label(
gonext=dom.input(attr.type('checkbox'), function change() { goauto.checked = false }),
' Go next',
attr.title('Release candidate of Go toolchain, if available.'),
), ' ',
),
dom.div(),
dom.label(
buildOnUpdatedToolchain=dom.input(attr.type('checkbox'), attr.checked('')),
' Schedule a low-priority build when new toolchains are automatically installed.',
),
),
dom.br(),
dom.p('The build script can be configured after creating.'),
dom.div(
style({textAlign: 'right'}),
dom.submitbutton('Add'),
),
),
),
)
originInput.focus()
}
const pageHome = async (): Promise<Page> => {
const page = new Page()
let [rbl0, [, , , , haveBubblewrap]] = await authed(() =>
Promise.all([
client.RepoBuilds(password),
client.Version(password),
])
)
let rbl = rbl0 || []
const rblFavicon = () => {
let busy = false
for (const rb of rbl) {
for (const b of (rb.Builds || [])) {
if (!b.Finish) {
busy = true
break
}
}
}
setFavicon(busy ? favicons.gray : favicons.default)
}
dom._kids(crumbElem, 'Home')
document.title = 'Ding - Repos'
rblFavicon()
const atexit = page.newAtexit()
const render = () => {
atexit.run()
dom._kids(pageElem,
dom.div(
style({marginBottom: '1ex'}),
link('#gotoolchains', 'Go Toolchains'), ' ',
link('#settings', 'Settings'), ' ',
),
dom.div(
dom.clickbutton('Add repo', attr.title('Add new repository, to build.'), async function click() {
const [, , haveGoToolchainDir] = await authed(() => client.Settings(password))
popupRepoAdd(haveBubblewrap, haveGoToolchainDir)
}), ' ',
dom.clickbutton('Clear homedirs', attr.title('Remove home directories for all repositories that reuse home directories across builds. Cache in such directories can grow over time, consuming quite some disk space.'), async function click(e: MouseEvent & TargetDisableable) {
if (!confirm('Are you sure?')) {
return
}
await authed(() => client.ClearRepoHomedirs(password), e.target)
}), ' ',
dom.clickbutton('Build all lowprio', attr.title('Schedule builds for all repositories, but at low priority.'), async function click(e: MouseEvent & TargetDisableable) {
await authed(() => client.BuildsCreateLowPrio(password), e.target)
})
),
dom.table(
dom._class('striped', 'wide'),
dom.thead(
dom.tr(
['Repo', 'Build ID', 'Status', 'Duration', 'Branch', 'Version', 'Coverage', 'Disk usage', 'Home disk usage', 'Age'].map(s => dom.th(s)),
dom.th(style({textAlign: 'left'}), 'Error'),
),
),
dom.tbody(
rbl.length === 0 ? dom.tr(dom.td(attr.colspan('10'), 'No repositories', style({textAlign: 'left'}))) : [],
rbl.map(rb => {
if ((rb.Builds || []).length === 0) {
return dom.tr(
dom.td(link('#repo/'+encodeURIComponent(rb.Repo.Name), rb.Repo.Name))
)
}
return (rb.Builds || []).map((b, i) =>
dom.tr(
i === 0 ? dom.td(link('#repo/'+encodeURIComponent(rb.Repo.Name), rb.Repo.Name), attr.rowspan(''+(rb.Builds || []).length)) : [],
dom.td(link('#repo/'+encodeURIComponent(rb.Repo.Name)+'/build/'+b.ID, ''+b.ID)),
dom.td(buildStatus(b)),
dom.td(b.Start ? atexit.age(b.Start, b.Finish || undefined) : ''),
dom.td(b.Branch),
dom.td(b.Version, b.CommitHash ? attr.title('Commit '+b.CommitHash) : []),
dom.td(formatCoverage(rb.Repo, b)),
dom.td(formatBuildSize(b)),
dom.td(rb.Repo.UID ? dom.span(formatSize(rb.Repo.HomeDiskUsage), attr.title('Of reused home directory')) : []),
dom.td(atexit.ageMins(b.Created, undefined)),
dom.td(style({textAlign: 'left'}), buildErrmsg(b)),
)
)
}),
),
)
)
}
render()
page.subscribe(streams.build, (e: api.EventBuild) => {
const rb = rbl.find(rb => rb.Repo.Name === e.Build.RepoName)
if (!rb) {
return
}
const builds = rb.Builds || []
const i = builds.findIndex(b => b.ID === e.Build.ID)
if (i < 0) {
builds.unshift(e.Build)
} else {
builds[i] = e.Build
}
rb.Builds = builds
rblFavicon()
render()
})
page.subscribe(streams.removeBuild, (e: api.EventRemoveBuild) => {
const rb = rbl.find(rb => rb.Repo.Name === e.RepoName)
if (!rb) {
return
}
rb.Builds = (rb.Builds || []).filter(b => b.ID !== e.BuildID)
rblFavicon()
render()
})
page.subscribe(streams.repo, (ev: api.EventRepo) => {
for (const rb of rbl) {
if (rb.Repo.Name == ev.Repo.Name) {
rb.Repo = ev.Repo
render()
return
}
}
rbl.unshift({Repo: ev.Repo, Builds: []})
render()
})
page.subscribe(streams.removeRepo, (ev: api.EventRemoveRepo) => {
rbl = rbl.filter(rb => rb.Repo.Name !== ev.RepoName)
rblFavicon()
render()
})
return page
}
const pageGoToolchains = async (): Promise<Page> => {
const page = new Page()
const [available0, [installed0, active0]] = await authed(() =>
Promise.all([
client.GoToolchainsListReleased(password),
client.GoToolchainsListInstalled(password),
])
)
let available = available0 || []
let installed = installed0 || []
let active = active0 || []
dom._kids(crumbElem, link('#', 'Home'), ' / ', 'Go Toolchains')
document.title = 'Ding - Go Toolchains'
setFavicon(favicons.default)
const render = () => {
const groups: string[][] = []
for (const s of available) {
const t = s.split('.')
if (t.length === 1) {
groups.push([s])
continue
}
const minor = parseInt(t[1])
const prefix = t[0]+'.'+minor
if (groups.length > 0 && groups[groups.length-1][0].startsWith(prefix)) {
groups[groups.length-1].push(s)
} else {
groups.push([s])
}
}
let gocur: HTMLSelectElement
let goprev: HTMLSelectElement
let gonext: HTMLSelectElement
dom._kids(pageElem,
dom.p('Go toolchains can easily be installed in the toolchains directory set in the configuration file. Build scripts can add $DING_TOOLCHAINDIR/<goversion>/bin to their $PATH.'),
dom.h1('Current and previous Go toolchains'),
dom.p('The current/previous/next (release candidate) Go toolchains are available through $DING_TOOLCHAINDIR/{go,goprev,gonext}/bin.'),
dom.table(
dom.tr(
dom.td('Current'),
dom.td(
dom.form(
async function submit(e: SubmitEvent) {
e.stopPropagation()
e.preventDefault()
await authed(() => client.GoToolchainActivate(password, gocur.value, 'go'))
active.Go = gocur.value
render()
},
dom.fieldset(
gocur=dom.select(
dom.option('(none)', attr.value('')),
installed.map(s => dom.option(s, active.Go === s ? attr.selected('') : [])),
),
' ',
dom.submitbutton('Set', attr.title('Set Go toolchain as "go"')),
)
),
),
),
dom.tr(
dom.td('Previous'),
dom.td(
dom.form(
async function submit(e: SubmitEvent) {
e.stopPropagation()
e.preventDefault()
await authed(() => client.GoToolchainActivate(password, goprev.value, 'goprev'))
active.GoPrev = goprev.value
render()
},
dom.fieldset(
goprev=dom.select(
dom.option('(none)', attr.value('')),
installed.map(s => dom.option(s, active.GoPrev === s ? attr.selected('') : [])),
),
' ',
dom.submitbutton('Set', attr.title('Set Go toolchain as "goprev"')),
)
),
),
),
dom.tr(
dom.td('Next'),
dom.td(
dom.form(
async function submit(e: SubmitEvent) {
e.stopPropagation()
e.preventDefault()
await authed(() => client.GoToolchainActivate(password, gonext.value, 'gonext'))
active.GoNext = gonext.value
render()
},
dom.fieldset(
gonext=dom.select(
dom.option('(none)', attr.value('')),
installed.map(s => dom.option(s, active.GoNext === s ? attr.selected('') : [])),
),
' ',
dom.submitbutton('Set', attr.title('Set Go toolchain as "gonext"')),
)
),
),
),
),
dom.br(),
dom.div(
dom.clickbutton('Automatically update toolchains', attr.title('If new toolchains are installed, low prio builds are automatically scheduled for repositories that have opted in.'), async function click(e: TargetDisableable) {
await authed(() => client.GoToolchainAutomatic(password), e.target)
const [available0, [installed0, active0]] = await authed(() =>
Promise.all([
client.GoToolchainsListReleased(password),
client.GoToolchainsListInstalled(password),
])
)
available = available0 || []
installed = installed0 || []
active = active0 || []
render()
}),
),
dom.br(),
dom.h1('Released and installed toolchains'),
dom.div(
dom.ul(
style({lineHeight: '1.75'}),
groups.map(g =>
dom.li(
g.map(s =>
[
installed.includes(s) ? dom.span(
s, ' ',
dom.clickbutton('-', attr.title('Remove toolchain'), async function click(e: MouseEvent & TargetDisableable) {
await authed(() => client.GoToolchainRemove(password, s), e.target)
installed = installed.filter(i => i !== s)
render()
}),
) : dom.clickbutton(s, attr.title('Install this toolchain'), async function click(e: MouseEvent & TargetDisableable) {
await authed(() => client.GoToolchainInstall(password, s, ''), e.target)
installed.unshift(s)
render()
}),
' ',
]
),
)
),
),
),
)
}
render()
return page
}
const pageSettings = async (): Promise<Page> => {
const page = new Page()
const [loglevel, [isolationEnabled, mailEnabled, haveGoToolchainDir, settings]] = await authed(() =>
Promise.all([
client.LogLevel(password),
client.Settings(password),
])
)
let loglevelElem: HTMLSelectElement
let loglevelFieldset: HTMLFieldSetElement
let notifyEmailAddrs: HTMLInputElement
let runPrefix: HTMLInputElement
let environment: HTMLTextAreaElement
let automaticGoToolchains: HTMLInputElement
let githubSecret: HTMLInputElement
let giteaSecret: HTMLInputElement
let bitbucketSecret: HTMLInputElement
let fieldset: HTMLFieldSetElement
dom._kids(crumbElem, link('#', 'Home'), ' / ', 'Settings')
document.title = 'Ding - Settings'
setFavicon(favicons.default)
dom._kids(pageElem,
isolationEnabled ? dom.p('Each repository and potentially build is isolated to run under a unique uid.') : dom.p('NOTE: Repositories and builds are NOT isolated to run under a unique uid. You may want to enable isolated builds in the configuration file (requires restart).'),
mailEnabled ? [] : dom.p('NOTE: No SMTP server is configured for outgoing emails, no email will be sent for broken/fixed builds.'),
dom.div(
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
await authed(() => client.LogLevelSet(password, loglevelElem.value as api.LogLevel), loglevelFieldset)
},
loglevelFieldset=dom.fieldset(
dom.label(
'Log level ',
loglevelElem=dom.select(
['debug', 'info', 'warn', 'error'].map(s => dom.option(s, loglevel == s ? attr.selected('') : [])),
), ' ',
dom.submitbutton('Set'),
),
),
),
),
dom.br(),
dom.form(
async function submit(e: SubmitEvent) {
e.preventDefault()
e.stopPropagation()
settings.NotifyEmailAddrs = notifyEmailAddrs.value.split(',').map(s => s.trim()).filter(s => !!s)
settings.RunPrefix = runPrefix.value.split(' ').map(s => s.trim()).filter(s => !!s)
settings.Environment = environment.value.split('\n').map(s => s.trim()).filter(s => !!s)
settings.AutomaticGoToolchains = automaticGoToolchains.checked
settings.GithubWebhookSecret = githubSecret.value
settings.GiteaWebhookSecret = giteaSecret.value
settings.BitbucketWebhookSecret = bitbucketSecret.value
await authed(() => client.SettingsSave(password, settings), fieldset)
},
// autocomplete=off seems to be ignored by firefox, which also isn't smart enough
// to realize it doesn't make sense to store a password when there are 3 present in
// a form...
attr.autocomplete('off'),
fieldset=dom.fieldset(
dom.div(
style({display: 'grid', columnGap: '1em', rowGap: '.5ex', gridTemplateColumns: 'min-content 1fr', alignItems: 'top', maxWidth: '50em'}),
dom.div('Notify email addresses', style({whiteSpace: 'nowrap'}), attr.title('Comma-separated list of email address that will receive notifications when a build breaks or is fixed and a repository does not have its own addresses to notify configured.')),
notifyEmailAddrs=dom.input(attr.value((settings.NotifyEmailAddrs || []).join(', ')), attr.placeholder('[email protected], [email protected]')),
dom.div('Clone and build command prefix', style({whiteSpace: 'nowrap'}), attr.title('Can be used to run at lower priority and with timeout, e.g. "nice ionice -c 3 timeout 300s"')),
runPrefix=dom.input(attr.value((settings.RunPrefix || []).join(' '))),
dom.div('Additional environment variables', style({whiteSpace: 'nowrap'}), attr.title('Of the form key=value, one per line.')),
environment=dom.textarea((settings.Environment || []).map(s => s+'\n').join(''), attr.placeholder('key=value\nkey=value\n...'), attr.rows(''+Math.max(8, (settings.Environment || []).length+1))),
dom.div(),
dom.label(
automaticGoToolchains=dom.input(attr.type('checkbox'), settings.AutomaticGoToolchains ? attr.checked('') : []),
' Automatic Go toolchain management',
attr.title('Check once per day if new Go toolchains have been released, and automatically install them and update the go/goprev/gonext symlinks, and schedule low priority builds for repositories that have opted in.' + !haveGoToolchainDir ? ' Warning: No Go toolchain directory is configured in the configuration file.' : ''),
),
dom.div(
style({gridColumn: '1 / 3'}),
'Global webhook secrets (deprecated)',
dom.p('For new repositories, unique webhooks are assigned to each repository. While global secrets are still configured, they will be accepted to start builds on all older repositories.'),
),
dom.div('Github webhook secret', style({whiteSpace: 'nowrap'})),
githubSecret=dom.input(attr.value(settings.GithubWebhookSecret), attr.type('password'), attr.autocomplete('off')),
dom.div('Gitea webhook secret', style({whiteSpace: 'nowrap'})),
giteaSecret=dom.input(attr.value(settings.GiteaWebhookSecret), attr.type('password'), attr.autocomplete('off')),
dom.div('Bitbucket webhook secret', style({whiteSpace: 'nowrap'})),
bitbucketSecret=dom.input(attr.value(settings.BitbucketWebhookSecret), attr.type('password'), attr.autocomplete('off')),
),
dom.br(),
dom.submitbutton('Save'),
),
),
)
return page
}
const pageDocs = async (): Promise<Page> => {
const page = new Page()
const [version, goos, goarch, goversion] = await authed(() => client.Version(password))
dom._kids(crumbElem, link('#', 'Home'), ' / Docs')
document.title = 'Ding - Docs'
setFavicon(favicons.default)
dom._kids(pageElem,
dom.h1('Introduction'),
dom.p("Ding is a minimalistic build server for internal use. The goal is to make it easy to build software projects in an isolated environment, ensuring it also works on other people's machines. Ding clones a git or mercurial repository, or runs a custom shell script to clone a project, and runs a shell script to build the software. The shell script should output certain lines that ding recognizes, to find build results, test coverage, etc."),
dom.h1('Notifications'),
dom.p('Ding can be configured to send a notification email if a repo breaks (failed build) or is repaired again (successful build after previous failure)'),
dom.h1('Webhooks'),
dom.p('For each project to build, first configure a repository and a build script. Optionally configure the code repository to call a ding webhook to start a build. For git, this can be done with post-receive shell script in .git/hooks, or through various settings in web apps like gitea, github and bitbucket. For custom scripts, run ', dom.tt('ding kick baseURL repoName branch commit < password-file'), ' to start a build, where baseURL could be http://localhost:6084 (for default settings), and password is what you use for logging in. For externally-defined webhook formats, ensure the ding webhook listener is publicly accessible (e.g. through a reverse proxy), and configure these paths for the respective services: ', dom.tt('https://.../gitea/<repo>'), ', ', dom.tt('https://.../github/<repo>'), ' or ', dom.tt('https://.../bitbucket/<repo>/<secret>'), '. Gitea includes a "secret" in an Authorization header, github signs its request payload, for bitbucket you must include a secret value in the URL they send the webhook too. These secrets must be configured in the ding configuration file.'),
dom.h1('Authentication'),
dom.p('Ding only has simple password-based authentication, with a single password for the entire system. Everyone with the password can see all repositories, builds and scripts, and modify all data.'),
dom.h1('Go toolchains'),
dom.p('Ding has builtin functionality for downloading Go toolchains for use in builds.'),
dom.h1('API'),
dom.p('Ding has a simple HTTP/JSON-based API, see ', link('ding/', 'Ding API'), '.'),
dom.h1('Files and directories'),
dom.p('Ding stores all files for repositories, builds, releases and home directories in its "data" directory:'),
dom.pre(`
data/
build/<repoName>/<buildID>/ ($DING_BUILDDIR during builds)
checkout/$DING_CHECKOUTPATH/ (working directory for build.sh)
scripts/
build.sh (copied from database before build)
output/
{clone,build}.{stdout,stderr,output,nsec}
home/ (for builds with unique $HOME/uid)
dl/ (files stored here are available at /dl/file/<repoName>/<buildID>/)
release/<repoName>/<buildID>/
<result-filename>
home/<repoName>/ (for builds with reused $HOME/uid)
`),
dom.br(),
docsBuildScript(),
dom.h1('Licenses'),
dom.p('Ding is open source software. See ', link('licenses', 'licenses'), '.'),
dom.h1('Version'),
dom.p('This is version ', version, ', ', goversion, ' running on ', goos, '/', goarch, '.'),
)
return page
}
const docsBuildScript = (): HTMLElement => {
return dom.div(
dom.h1('Clone'),
dom.p('Clones are run as the configured ding user, not under a unique/reused UID. After cloning, file permissions are fixed up. Configure an .ssh/config and/or ssh keys in the home directory of the ding user.'),
dom.h1('Build script environment'),
dom.p('The build script is run in a clean environment. It should exit with status 0 only when successful. Patterns in the output indicate where build results can be found, such as files and test coverage, see below.'),
dom.p('The working directory is set to $DING_BUILDDIR/checkout/$DING_CHECKOUTPATH.'),
dom.p('Only a single build will be run for a repository.'),
dom.h2('Example'),
dom.h3('Basic'),
dom.p('Basic build for building ding from github, using the "Build for Go toolchain" setting.'),
dom.pre(`#!/usr/bin/env bash
set -eu