-
Notifications
You must be signed in to change notification settings - Fork 18
/
package_directory.nim
1748 lines (1493 loc) · 51.7 KB
/
package_directory.nim
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
#
# Nimble package directory
#
# Copyright 2016 Federico Ceratto <federico.ceratto@gmail.com>
# Released under GPLv3 License, see LICENSE file
#
import asyncdispatch,
deques,
httpclient,
httpcore,
json,
os,
osproc,
parseopt,
sequtils,
streams,
strutils,
tables,
times
from algorithm import sort, sorted, sortedByIt, reversed
from marshal import store, load
from posix import onSignal, SIGINT, SIGTERM, getpid
from times import epochTime
#from nimblepkg import getTagsListRemote, getVersionList
import jester,
morelogging,
sdnotify,
statsd_client,
zmq
import github,
signatures,
email,
friendly_timeinterval,
persist
const
template_path = "./templates"
build_timeout_seconds = 60 * 4
github_readme_tpl = "https://api.github.com/repos/$#/readme"
github_tags_tpl = "https://api.github.com/repos/$#/tags"
github_latest_version_tpl = "https://api.github.com/repos/$#/releases/latest"
github_doc_index_tpl = "https://$#.github.io/$#/index.html"
github_repository_search_tpl = "https://api.github.com/search/repositories?q=language:nim+pushed:>$#&per_page=$#sort=$#&page=$#"
github_caching_time = 600
github_packages_json_raw_url= "https://raw.githubusercontent.com/nim-lang/packages/master/packages.json"
github_packages_json_polling_time_s = 10 * 60
git_bin_path = "/usr/bin/git"
sdnotify_ping_time_s = 1
nim_bin_path = "/usr/bin/nim"
nimble_bin_path = "/usr/bin/nimble"
task_pubsub_port = 5583
build_expiry_time = (15 * 60).Time
cache_fn = ".cache.json"
xml_no_cache_headers = {
"Cache-Control": "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform",
"Expires": "0",
"Pragma": "no-cache",
"Content-Type": "image/svg+xml"
}
# init
let conf = load_conf()
let github_token_headers = newHttpHeaders({
"Authorization": "token $#" % conf.github_token})
let stats = newStatdClient(prefix="nim_package_directory")
let zmqsock = listen("tcp://*:" & $task_pubsub_port, mode=PUB)
when defined(systemd):
let log = newJournaldLogger()
else:
let log = newAsyncFileLogger()
proc log_debug(args: varargs[string, `$`]) =
log.debug(args.join(" "))
proc log_info(args: varargs[string, `$`]) =
log.info(args.join(" "))
proc log_req(request: Request) =
## Log request data
var path = ""
for c in request.path:
if len(path) > 300:
path.add "..."
break
let o = c.ord
if o < 32 or o > 126:
path.add o.toHex()
else:
path.add c
log_info "serving $# $# $#" % [request.ip, $request.reqMeth, path]
log_debug conf
type
ProcessError = object of Exception
Pkg* = JsonNode
Pkgs* = TableRef[string, Pkg]
strSeq = seq[string]
BuildStatus {.pure.} = enum OK, Failed, Timeout, Running
DocBuildOutItem = object
success_flag: bool
filename, desc, output: string
DocBuildOut = seq[DocBuildOutItem]
PkgDocMetadata = object of RootObj
fnames: strSeq
idx_fnames: strSeq
building: bool
build_time: Time
expire_time: Time
last_commitish: string
build_status: BuildStatus
build_output: string
doc_build_status: BuildStatus
doc_build_output: DocBuildOut
version: string
RssItem = object
title, desc, url, guid, pubDate: string
BuildHistoryItem = tuple
name: string
build_time: Time
build_status: BuildStatus
doc_build_status: BuildStatus
PkgSymbol = object
code, desc, itype, filepath: string
line, col: int
PkgSymbols = seq[PkgSymbol]
# the pkg name is normalized
var pkgs: Pkgs = newTable[string, Pkg]()
type PkgsDocFilesTable = Table[string, PkgDocMetadata]
# package name -> PkgDocMetadata
# initialized by scan_pkgs_dir
var pkgs_doc_files = newTable[string, PkgDocMetadata]()
# tag -> package name
# initialized/updated by load_packages
var packages_by_tag = newTable[string, seq[string]]()
# word -> package name
# word -> package name
# initialized/updated by load_packages
var packages_by_description_word = newTable[string, seq[string]]()
# symbol -> seq[PkgSymbol]
# initialized by scan_pkgs_dir
var jsondoc_symbols = newTable[string, PkgSymbols]()
# pname, symbol -> seq[PkgSymbol]
# initialized by scan_pkgs_dir
type PkgSymbolsIndexer = tuple[pname, symbol: string]
var jsondoc_symbols_by_pkg = newTable[PkgSymbolsIndexer, PkgSymbols]()
# package access statistics
# volatile
var most_queried_packages = initCountTable[string]()
# build history
# volatile
const build_history_size = 100
var build_history = initDeque[BuildHistoryItem]()
# disk-persisted cache
type
PkgHistoryItem = object
name: string
first_seen_time: Time
Cache = object of RootObj
# package creation/update history - new ones at bottom
pkgs_history: seq[PkgHistoryItem]
# pkgs list. Extra data from GH is embedded
#pkgs: TableRef[string, Pkg]
var cache: Cache
proc save(cache: Cache) =
let f = newFileStream(cache_fn, fmWrite)
f.store(cache)
f.close()
proc load_cache(): Cache =
## Load cache from disk or create empty cache
log_debug "loading cache at $#" % cache_fn
try:
# FIXME
#result.pkgs = newTable[string, Pkg]()
result.pkgs_history = @[]
load(newFileStream(cache_fn, fmRead), result)
log_debug "cache loaded"
except:
log_info "initializing new cache"
#result.pkgs = newTable[string, Pkg]()
result.pkgs_history = @[]
result.save()
log_debug "new cache created"
proc uniescape(inp: string): string =
result = ""
for c in inp:
let o = c.ord
if o < 32 or o > 126:
let q = "\\u00" & o.toHex()[^2..^1]
result.add q
else:
result.add c
proc save_pkg_metadata(j: PkgDocMetadata, fn: string) =
## Save package metadata
log_debug "Saving to $#" % fn
var k = PkgDocMetadata()
deepCopy[PkgDocMetadata](k, j)
let f = newFileStream(fn, fmWrite)
k.build_output = uniescape(j.build_output)
if k.version == nil:
k.version = "?"
k.version = k.version.strip(chars={'\0'})
f.store(k)
f.close()
proc load_metadata(fn: string): PkgDocMetadata =
## load package metadata
log_debug "Loading $#" % fn
load(newFileStream(fn, fmRead), result)
proc scan_pkgs_dir(pkgs_root: string) =
## scan all packages dirs, populate jsondoc_symbols,
## jsondoc_symbols_by_pkg and pkgs_doc_files
let pattern = pkgs_root / "*" / "nimpkgdir.json"
# e.g /var/lib/nim_package_directory/cache/*/nimpkgdir.json
log_info "scanning pattern '" & pattern & "'"
for x in walkPattern(pattern):
try:
let pm: PkgDocMetadata = load_metadata(x)
# TODO jsondoc_symbols, jsondoc_symbols_by_pkg
except:
# ignore metadata
log_info "Load error: " & getCurrentExceptionMsg()
log_info "----"
discard
# volatile caches
var volatile_cache_github_trending_last_update_time = 0
var volatile_cache_github_trending: seq[JsonNode] = @[]
# HTML templates
include "templates/base.tmpl"
include "templates/home.tmpl"
include "templates/pkg.tmpl"
include "templates/pkg_list.tmpl"
include "templates/loader.tmpl"
include "templates/rss.tmpl"
include "templates/build_output.tmpl"
const
build_success_badge = slurp "templates/success.svg"
build_fail_badge = slurp "templates/fail.svg"
build_running_badge = slurp "templates/build_running.svg"
doc_success_badge = slurp "templates/doc_success.svg"
doc_fail_badge = slurp "templates/doc_fail.svg"
doc_running_badge = slurp "templates/doc_running.svg"
version_badge_tpl = slurp template_path / "version-template-blue.svg"
# proc setup_seccomp() =
# ## Setup seccomp sandbox
# const syscalls = """accept,access,arch_prctl,bind,brk,close,connect,epoll_create,epoll_ctl,epoll_wait,execve,fcntl,fstat,futex,getcwd,getrlimit,getuid,ioctl,listen,lseek,mmap,mprotect,munmap,open,poll,read,readlink,recvfrom,rt_sigaction,rt_sigprocmask,sendto,set_robust_list,setsockopt,set_tid_address,socket,stat,uname,write"""
# let ctx = seccomp_ctx()
# for sc in syscalls.split(','):
# ctx.add_rule(Allow, sc)
# ctx.load()
proc load_packages*() =
## Load packages.json
## Rebuild packages_by_tag, packages_by_description_word
log_debug "loading $#" % conf.packages_list_fname
pkgs.clear()
let pkg_list = conf.packages_list_fname.parseFile
for pdata in pkg_list:
if not pdata.hasKey("name"):
continue
if not pdata.hasKey("tags"):
continue
# Normalize pkg name
pdata["name"].str = pdata["name"].str.normalize()
if pdata["name"].str in pkgs:
log.warn "Duplicate pkg name $#" % pdata["name"].str
continue
pkgs[pdata["name"].str] = pdata
for tag in pdata["tags"]:
if not packages_by_tag.hasKey(tag.str):
packages_by_tag[tag.str] = @[]
packages_by_tag[tag.str].add pdata["name"].str
# collect packages matching a word in their descriptions
let orig_words = pdata["description"].str.split({' ', ','})
for orig_word in orig_words:
if orig_word.len < 3:
continue # ignore short words
let word = orig_word.toLowerAscii
if not packages_by_description_word.hasKey(word):
packages_by_description_word[word] = @[]
packages_by_description_word[word].add pdata["name"].str
log_info "Loaded ", $pkgs.len, " packages"
#log_debug "writing $#" % conf.packages_list_fname
#conf.packages_list_fname.writeFile(conf.packages_list_fname.readFile)
proc cleanupWhitespace(s: string): string
proc save_packages() =
## Save packages.json
var new_pkgs = newJArray()
for pname in toSeq(pkgs.keys()).sorted(system.cmp):
new_pkgs.add pkgs[pname]
conf.packages_list_fname.writeFile(new_pkgs.pretty.cleanupWhitespace)
proc search_packages*(query: string): CountTable[string] =
## Search packages by name, tag and keyword
let query = query.strip.toLowerAscii.split({' ', ','})
var found_pkg_names = initCountTable[string]()
for item in query:
# matching by pkg name, weighted for full or partial match
for pn in pkgs.keys():
if item.normalize() == pn:
found_pkg_names.inc(pn, val=5)
elif pn.contains(item.normalize()):
found_pkg_names.inc(pn, val=3)
if packages_by_tag.has_key(item):
for pn in packages_by_tag[item]:
# matching by tags is weighted more than by word
found_pkg_names.inc(pn, val=3)
# matching by description, weighted 1
if packages_by_description_word.has_key(item.toLowerAscii):
for pn in packages_by_description_word[item.toLowerAscii]:
found_pkg_names.inc(pn, val=1)
# sort packages by best match
found_pkg_names.sort()
return found_pkg_names
proc getGHJson(url: string): Future[JsonNode] {.async.} =
## async get JSON from GH
let ac = newAsyncHttpClient()
ac.headers = github_token_headers
let r = await ac.getContent(url)
return parseJson(r)
proc fetch_github_readme*(pkg: Pkg, owner_repo_name: string) {.async.} =
## Fetch README.* from GitHub
log_debug "fetching GH readme ", github_readme_tpl % owner_repo_name
try:
let ac = newAsyncHttpClient()
ac.headers = github_token_headers
ac.headers["Accept"] = "application/vnd.github.v3.html"
let readme = await ac.getContent(github_readme_tpl % owner_repo_name)
pkg["github_readme"] = newJString readme
except:
log_debug "failed to fetch GH readme"
log_debug getCurrentExceptionMsg()
pkg["github_readme"] = newJString ""
proc fetch_github_doc_pages(pkg: Pkg, owner, repo_name: string) =
## Fetch documentation pages from GitHub
let url = github_doc_index_tpl % [owner.toLowerAscii, repo_name]
log_debug "Checking ", url
if get(url).status.startsWith("200"):
pkg["doc"] = newJString url
proc fetch_github_packages_json(): string =
## Fetch packages.json from GitHub
log_debug "fetching ", github_packages_json_raw_url
getContent(github_packages_json_raw_url)
proc append(build_history: var Deque[BuildHistoryItem], name: string,
build_time: Time, build_status, doc_build_status: BuildStatus) =
## Add BuildHistoryItem to build history
if build_history.len == build_history_size:
discard build_history.popLast
let i: BuildHistoryItem = (name, build_time, build_status, doc_build_status)
build_history.addFirst(i)
proc `+`(t1, t2: Time): Time {.borrow.}
type RunOutput = tuple[exit_code: int, elapsed: float, output: string]
proc strip_html*(html: string): string =
# Assumes that any < > that is not part of HTML tags has been escaped
# Everything that matches <.*> is removed, including invalid tags
result = newStringOfCap(html.len)
var inside_tag = false
for c in html:
if inside_tag == false:
if c == '<':
inside_tag = true
else:
result.add c
elif c == '>':
inside_tag = false
proc run_process(bin_path, desc, work_dir: string,
timeout: int, log_output: bool,
args: varargs[string, `$`]): (bool, string) {.discardable.} =
## Run command with timeout
# TODO: async
log_debug "running: <" & bin_path & " " & join(args, " ") & "> in " & work_dir
var p = startProcess(
bin_path, args=args,
workingDir=work_dir,
options={poStdErrToStdOut}
)
let exit_val = p.waitForExit(timeout=timeout * 1000)
let stdout_str = p.outputStream().readAll()
if log_output or (exit_val != 0):
if stdout_str.len > 0:
log_debug "Stdout: ---\n$#---" % stdout_str
if exit_val == 0:
log_debug "$# successful" % desc
else:
log.error "run_process: $# failed, exit value: $#" % [desc, $exit_val]
return ((exit_val == 0), stdout_str)
proc run_process2(bin_path, desc, work_dir: string,
timeout: int, log_output: bool,
args: seq[string]): Future[RunOutput] {.async.} =
## Run command asyncronously with timeout
let
t0 = epochTime()
p = startProcess(
bin_path,
args=args,
workingDir=work_dir,
options={poStdErrToStdOut}
)
pid = p.processID()
var exit_code = 0
var sleep_time_ms = 50
while true:
let elapsed = epochTime() - t0
if elapsed > timeout.float:
log_debug "timed out!"
p.kill()
exit_code = -2
break
exit_code = p.peekExitCode()
case exit_code:
of -1:
# -1: still running, wait
# log_debug "waiting command thread $#..." % $pid
await sleepAsync sleep_time_ms
if sleep_time_ms < 1000:
sleep_time_ms *= 2
of 0:
discard p.waitForExit()
break
else:
discard p.waitForExit()
break
let elapsed = epochTime() - t0
var output = ""
let new_output = p.outputStream().readAll()
output.add new_output
for line in new_output.splitLines():
log_debug "[$#] $#> $#" % [$pid, $exit_code, line]
return (exit_code, elapsed, output)
proc fetch_github_versions(pkg: Pkg, owner_repo_name: string) {.async.} =
## Fetch versions from GH from releases and tags
## Set github_versions, github_latest_version, github_latest_version_url
log_debug "fetching GH tags ", github_tags_tpl % owner_repo_name
var version_names = newJArray()
try:
let ac = newAsyncHttpClient()
ac.headers = github_token_headers
let rtags = await ac.getContent(github_tags_tpl % owner_repo_name)
let tags = parseJson(rtags)
for t in tags:
let name = t["name"].str.strip(trailing=false, chars={'v'})
if name.len > 0:
version_names.add newJString name
except:
log_info getCurrentExceptionMsg()
pkg["github_versions"] = version_names
pkg["github_latest_version"] = newJString "none"
pkg["github_latest_version_url"] = newJString ""
return
pkg["github_versions"] = version_names
log_debug "fetched $# GH versions" % $len(version_names)
log_debug "fetching GH latest vers ", github_latest_version_tpl % owner_repo_name
try:
let latest_version = await getGHJson(github_latest_version_tpl % owner_repo_name)
var latest_version_name = latest_version["name"].str.strip
if latest_version_name.startsWith("v"):
latest_version_name = latest_version_name.strip(trailing=false, chars={'v'})
pkg["github_latest_version"] = newJString latest_version_name
pkg["github_latest_version_url"] = newJString latest_version["tarball_url"].str
pkg["github_latest_version_time"] = newJString latest_version["published_at"].str
except:
log_debug getCurrentExceptionMsg()
log_debug "No releases - falling back to tags"
var latest = "0"
for v in version_names:
if v.str > latest:
latest = v.str
if latest == "0":
pkg["github_latest_version"] = newJString "none"
pkg["github_latest_version_url"] = newJString ""
else:
pkg["github_latest_version"] = newJString latest.strip
pkg["github_latest_version_url"] = newJString(
"https://github.com/$#/archive/v$#.tar.gz" % [owner_repo_name, latest]
)
pkg["github_latest_version_time"] = newJString ""
proc fetch_github_repository_stats(sorting="updated", pagenum=1, limit=200, initial_date: TimeInfo):
Future[seq[JsonNode]] {.async.} =
## Fetch projects on GitHub
let date = initial_date.format("yyyy-MM-dd")
let q = github_repository_search_tpl % [date, $limit, sorting, $pagenum]
log_info "Searching GH repos: '$#'" % q
let query_res = await getGHJson(q)
if sorting == "updated":
return query_res["items"].elems.sortedByIt(it["updated_at"].str).reversed()
return query_res["items"].elems
proc github_trending_packages(request: Request, pkgs: Pkgs): Future[seq[JsonNode]] {.async.} =
## Trending GitHub packages
# TODO: Dom: merge this into the procedure above ^
if volatile_cache_github_trending_last_update_time +
github_caching_time > epochTime().int:
return volatile_cache_github_trending
result = @[]
let pkgs_list = await fetch_github_repository_stats(
sorting="updated", pagenum=1, limit=20,
initial_date=utc(getTime() - 14.days)
)
var website_to_name = initTable[string, string]()
for it in pkgs.values:
if it.hasKey("web"):
website_to_name[it["web"].str] = it["name"].str
for p in pkgs_list:
try:
# 2017-07-21T12:48:35Z
let t = p["pushed_at"].str.parse("yyyy-MM-ddTHH:mm:ss")
let d = toFriendlyInterval(t.toTime, getTime(), approx=2)
p["update_age"] = newJString d
except:
p["update_age"] = newJString ""
let url = p["html_url"].str
if website_to_name.hasKey url:
# The package is known to Nimble - set the "official" package name
p["name"].str = website_to_name[url]
result.add p
volatile_cache_github_trending = result
volatile_cache_github_trending_last_update_time = epochTime().int
# proc fetch_using_git(pname, url: string): bool =
# let repo_dir = conf.tmp_nimble_root_dir / pname
# if not repo_dir.existsDir():
# log_debug "checking out $#" % url
# run_process_old(git_bin_path, "git clone", conf.tmp_nimble_root_dir, 60, false,
# "clone", url, pname)
# else:
# log_debug "git pull-ing $#" % url
# run_process_old(git_bin_path, "git pull", repo_dir, 60, false,
# "pull")
#
# let commitish = run_process_old(git_bin_path, "git rev-parse", repo_dir,
# 1, false,
# "rev-parse", "--verify", "HEAD")
#
# if commitish == pkgs_doc_files[pname].last_commitish:
# pkgs_doc_files[pname].expire_time = getTime() + build_expiry_time
# #pkgs_doc_files[pname].building = false # unlock
# log_debug "no changes to repo"
# return false
#
# return true
proc fetch_and_build_pkg_using_nimble_old(pname: string) {.async.} =
## Run nimble install for a package using a dedicated directory
let tmp_dir = conf.tmp_nimble_root_dir / pname
log_debug "Starting nimble install $# --verbose --nimbleDir=$# -y" % [pname, tmp_dir]
let po = await run_process2(
nimble_bin_path,
"nimble",
".",
build_timeout_seconds,
true,
@["install", $pname, "--verbose", "--nimbleDir=$#" % tmp_dir, "-y", "--debug"],
)
let build_status: BuildStatus =
if po.exit_code == 0:
BuildStatus.OK
elif po.exit_code == -2:
BuildStatus.Timeout
else:
BuildStatus.Failed
log_debug "Setting status ", build_status
pkgs_doc_files[pname].build_status = build_status
if build_status == BuildStatus.Timeout:
pkgs_doc_files[pname].build_output = "** Install test timed out after " & $build_timeout_seconds & " seconds **\n\n" & po.output
else:
pkgs_doc_files[pname].build_output = po.output
pkgs_doc_files[pname].build_time = getTime()
pkgs_doc_files[pname].expire_time = getTime() + build_expiry_time
# proc fetch_pkg_using_nimble(pname: string): bool =
# let pkg_install_dir = conf.tmp_nimble_root_dir / pname
#
# var outp = run_process_old(nimble_bin_path, "nimble update",
# conf.tmp_nimble_root_dir, 10, true,
# "update", " --nimbleDir=" & conf.tmp_nimble_root_dir)
# assert outp.contains("Done")
#
# #if not conf.tmp_nimble_root_dir.existsDir():
# outp = ""
# if true:
# # First install
# log_debug conf.tmp_nimble_root_dir, " is not existing"
# outp = run_process_old(nimble_bin_path, "nimble install", conf.tmp_nimble_root_dir,
# 60, true,
# "install", pname, " --nimbleDir=./nyan", "-y")
# log_debug "Install successful"
#
# else:
# # Update pkg
# #outp = run_process_old(nimble_bin_path, "nimble install", "/", 60, true,
# # "install", pname, " --nimbleDir=" & conf.tmp_nimble_root_dir, "-y")
# # FIXME
# log_debug "Update successful"
#
# pkgs_doc_files[pname].build_output = outp
# return true
proc package_parent_dir(pname: string): string =
## Generate pkg parent dir
# Full path example:
# /var/lib/nim_package_dir/nimgame2
conf.tmp_nimble_root_dir / pname
proc locate_pkg_root_dir(pname: string): string =
## Locate installed pkg root dir
# Full path example:
# /dev/shm/nim_package_dir/nimgame2/pkgs/nimgame2-0.1.0
let pkgs_dir = conf.tmp_nimble_root_dir / pname / "pkgs"
log_debug "scanning dir $#" % pkgs_dir
for kind, path in walkDir(pkgs_dir, relative=true):
log_debug "scanning $#" % path
# FIXME: better heuristic
if path.contains('-'):
let chunks = path.split('-', maxsplit=1)
if chunks[0].normalize() == pname:
result = pkgs_dir / path
log_debug "Found pkg root: ", result
return
raise newException(Exception, "Root dir for $# not found" % pname)
proc build_docs(pname: string) {.async.} =
## Build docs
let pkg_root_dir = locate_pkg_root_dir(pname)
log_debug "Walking ", pkg_root_dir
#for fname in pkg_root_dir.walkDirRec(filter={pcFile}): # Bug in walkDirRec
var all_output: DocBuildOut = @[]
var generated_doc_fnames: seq[string] = @[]
var generated_idx_fnames: seq[string] = @[]
var input_fnames: seq[string] = @[]
for fname in pkg_root_dir.walkDirRec():
if fname.endswith(".nim"):
input_fnames.add fname
for fname in input_fnames:
log_debug "running nim doc for $#" % fname
# TODO: enable --docSeeSrcUrl:<url>
let desc = "nim doc --index:on $#" % fname
let run_dir = fname.splitPath.head
let po = await run_process2(
nim_bin_path,
desc,
run_dir,
10,
true,
@["doc", "--index:on", fname],
)
let success = (po.exit_code == 0)
all_output.add DocBuildOutItem(
success_flag:success,
filename:fname,
desc:desc,
output:po.output
)
if success:
# trim away <pkg_root_dir> and ".nim"
let basename = fname[pkg_root_dir.len..^5]
generated_doc_fnames.add basename & ".html"
log_debug "adding ", basename & ".html"
for kind, path in walkDir(pkg_root_dir, relative=true):
if path.endswith(".idx"):
#generated_idx_fnames.add basename & ".idx"
#idx_filenames.add path
log_debug "adding ", pkg_root_dir & " > " & path
#let chunks = path.split('-', maxsplit=1)
#if chunks[0].normalize() == pname:
# result = pkgs_dir / path
pkgs_doc_files[pname].doc_build_output = all_output
pkgs_doc_files[pname].fnames = generated_doc_fnames
pkgs_doc_files[pname].idx_fnames = generated_idx_fnames
pkgs_doc_files[pname].doc_build_status =
if (input_fnames.len == generated_doc_fnames.len): BuildStatus.OK
else: BuildStatus.Failed
proc generate_jsondoc(pname: string) {.async.} =
## Generate jsondoc items, add them to the global `jsondoc_symbols`
## and `jsondoc_symbols_by_pkg`
let pkg_root_dir = locate_pkg_root_dir(pname)
log_debug "Walking ", pkg_root_dir
var input_fnames: seq[string] = @[]
for fname in pkg_root_dir.walkDirRec():
if fname.endswith(".nim"):
input_fnames.add fname
for fname in input_fnames:
let desc = "nim jsondoc $#" % fname
log_debug "running " & desc
let run_dir = fname.splitPath.head
let po = await run_process2(
nim_bin_path,
desc,
run_dir,
10,
true,
@["jsondoc", fname],
)
let success = (po.exit_code == 0)
if success:
# replace ".nim" with ".json"
let json_fn = fname[0..^5] & ".json"
try:
let j = parseJson(readFile(json_fn))
for chunk in j:
let symbol_name = chunk["name"].getStr()
let description = chunk{"description"}.getStr().strip_html()
let symbol = PkgSymbol(
itype:chunk["type"].getStr(),
desc:description,
code:chunk["code"].getStr(),
filepath:fname[pkg_root_dir.len..^1],
line:chunk["line"].getInt(),
col:chunk["col"].getInt(),
)
try:
if not jsondoc_symbols[symbol_name].contains symbol:
jsondoc_symbols[symbol_name].add(symbol)
except KeyError:
jsondoc_symbols[symbol_name] = @[symbol]
let i:PkgSymbolsIndexer = (pname, symbol_name)
try:
if not jsondoc_symbols_by_pkg[i].contains symbol:
jsondoc_symbols_by_pkg[i].add(symbol)
except KeyError:
jsondoc_symbols_by_pkg[i] = @[symbol]
except:
log_debug "failed to read and parse " & json_fn & " : " & getCurrentExceptionMsg()
proc fetch_and_build_pkg_if_needed(pname: string, force_rebuild=false) {.async.} =
## Fetch package and build docs
## Modifies pkgs_doc_files
# PkgDocMetadata state machine: nothing -> building:true <-> building:false
if pkgs_doc_files.hasKey(pname):
# A build has been already done or is currently running.
if pkgs_doc_files[pname].building == true:
# Build already running
return
if not force_rebuild and pkgs_doc_files[pname].expire_time > getTime():
# No need to rebuild yet
return
else:
# The package has never been built before: create PkgDocMetadata
let pm = PkgDocMetadata(
fnames: @[],
idx_fnames: @[],
)
pkgs_doc_files[pname] = pm
pkgs_doc_files[pname].building = true # lock
pkgs_doc_files[pname].build_time = getTime()
pkgs_doc_files[pname].expire_time = getTime() + build_expiry_time
pkgs_doc_files[pname].build_status = BuildStatus.Running
pkgs_doc_files[pname].doc_build_status = BuildStatus.Running
# Fetch or update pkg
let url = pkgs[pname]["url"].str
zmqsock.send("build:start " & pname)
try:
let t0 = epochTime()
await fetch_and_build_pkg_using_nimble_old(pname)
let elapsed = epochTime() - t0
stats.gauge("build_time", elapsed)
except:
pkgs_doc_files[pname].building = false # unlock
raise
if pkgs_doc_files[pname].build_status != BuildStatus.OK:
pkgs_doc_files[pname].building = false # unlock
log_debug "fetch_and_build_pkg_if_needed failed - skipping doc generation"
stats.incr("build_failed")
build_history.append(
pname,
pkgs_doc_files[pname].build_time,
pkgs_doc_files[pname].build_status,
pkgs_doc_files[pname].doc_build_status
)
let fn = package_parent_dir(pname) & "/nimpkgdir.json"
save_pkg_metadata(pkgs_doc_files[pname], fn)
return # install failed
stats.incr("build_succeded")
try:
let t1 = epochTime()
await build_docs(pname) # this can raise
let elapsed = epochTime() - t1
stats.gauge("doc_build_time", elapsed)
finally:
pkgs_doc_files[pname].building = false # unlock
build_history.append(
pname,
pkgs_doc_files[pname].build_time,
pkgs_doc_files[pname].build_status,
pkgs_doc_files[pname].doc_build_status
)
if pkgs[pname].hasKey("github_latest_version"):
pkgs_doc_files[pname].version = pkgs[pname]["github_latest_version"].str.strip
else:
log_debug "FIXME github_latest_version"
pkgs_doc_files[pname].version = "?"
try:
let t2 = epochTime()
await generate_jsondoc(pname) # this can raise
let elapsed = epochTime() - t2
stats.gauge("jsondoc_build_time", elapsed)
except:
log.error("jsondoc failed for " & pname)
let fn = package_parent_dir(pname) & "/nimpkgdir.json"
save_pkg_metadata(pkgs_doc_files[pname], fn)
try:
let pm: PkgDocMetadata = load_metadata(fn)
except:
log.error("JSON: created broken file: " & fn)
proc wait_build_completion(pname: string) {.async.} =
let t0 = epochTime()
while pkgs_doc_files[pname].building == true:
let elapsed = epochTime() - t0
if elapsed > build_timeout_seconds:
log_debug "wait timed out!"
stats.incr("build_timed_out")
break
log_debug "waiting already running build for $# $#s..." % [pname, $int(elapsed)]
await sleepAsync 1000
proc translate_term_colors*(outp: string): string =
## Translate terminal colors
const sequences = @[
("[36m[2m", "<span>"),
("[32m[1m", """<span class="success">"""),
("[33m[1m", """<span class="red">"""),
("[31m[1m", """<span class="red">"""),
("[36m[1m", """<span class="blue">"""),
("[0m[31m[0m", "</span>"),
("[0m[32m[0m", "</span>"),
("[0m[33m[0m", "</span>"),
("[0m[36m[0m", "</span>"),
("[0m[0m", "</span>"),
("[2m", "<span>"),
("[36m", "<span>"),
("[33m", """<span class="blue">"""),
]
result = outp
for s in sequences:
result = result.replace(s[0], s[1])
proc sorted*[T](t: CountTable[T]): CountTable[T] =
## Return sorted CountTable
var tcopy = t
tcopy.sort()
tcopy
proc top_keys*[T](t: CountTable[T], n: int): seq[T] =
## Return CountTable most common keys
result = @[]
var tcopy = t
tcopy.sort()
for k in keys(tcopy):
result.add k
if result.len == n:
return
# Jester settings
settings:
port = conf.port
# routes
routes:
get "/about.html":
include "templates/about.tmpl"
resp base_page(request, generate_about_page())
get "/":
log_req request
stats.incr("views")
try:
var top_pkgs: seq[Pkg] = @[]
for pname in top_keys(most_queried_packages, 5):
if pkgs.hasKey(pname):
top_pkgs.add pkgs[pname]
log_debug "pkgs history len: $#" % $cache.pkgs_history.len
# List 5 newest packages
var new_pkgs: seq[Pkg] = @[]
for n in 1..min(cache.pkgs_history.len, 5):
let pname = cache.pkgs_history[^n].name.normalize()
if pkgs.hasKey(pname):
new_pkgs.add pkgs[pname]