-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslicer_wiki_extension_module_listing.py
executable file
·1725 lines (1442 loc) · 69.8 KB
/
slicer_wiki_extension_module_listing.py
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
#!/usr/bin/env python
import codecs
import ConfigParser
import fnmatch
import glob
import git
import io
import itertools
import json
import os
import platform
import re
import subprocess
import sys
import tempfile
import urllib
import urllib2
#---------------------------------------------------------------------------
# Module global variables
class ModuleGlobals(object): pass
__m = ModuleGlobals()
__m.persistent_cache_enabled = False
__m.persistent_cache = {}
__m.cache = {}
#---------------------------------------------------------------------------
def setCacheEntry(key, value):
__m.cache[key] = value
return value
#---------------------------------------------------------------------------
def cacheEntry(key):
return __m.cache[key]
#---------------------------------------------------------------------------
def clearCache():
__m.cache = {}
#---------------------------------------------------------------------------
def persistentCacheEnabled():
return __m.persistent_cache_enabled
#---------------------------------------------------------------------------
def setPersistentCacheEnabled(value):
__m.persistent_cache_enabled = value
#---------------------------------------------------------------------------
def persistentCacheEntry(key):
if persistentCacheEnabled():
return __m.persistent_cache[key]
else:
raise KeyError
#---------------------------------------------------------------------------
def setPersistentCacheEntry(key, value):
__m.persistent_cache[key] = value
savePersistentCache()
return value
#---------------------------------------------------------------------------
def clearPersistentCache():
__m.cache = {}
#---------------------------------------------------------------------------
def getPersistentCacheFilePath():
return os.path.join(tempfile.gettempdir(), os.path.basename(os.path.splitext(__file__)[0])+"-cache")
#---------------------------------------------------------------------------
def savePersistentCache():
with open(getPersistentCacheFilePath(), 'w') as fileContents:
fileContents.write(json.dumps(__m.persistent_cache, sort_keys=True, indent=4))
#---------------------------------------------------------------------------
def loadPersistentCache():
setPersistentCacheEnabled(True)
if not os.path.exists(getPersistentCacheFilePath()):
return
with open(getPersistentCacheFilePath()) as fileContents:
__m.persistent_cache = json.load(fileContents)
#---------------------------------------------------------------------------
def connectToSlicerWiki(username='UpdateBot', password=None):
"""
:param username:
Username to login to Slicer wiki. The user should be granted right to use the wiki API.
:type username:
:class:`basestring`
:param password:
Password to login to Slicer wiki.
:type username:
:class:`basestring`
:returns: Site object allowing to interact with the wiki.
:rtype: :class:`mwclient.Site <mwclient:mwclient.client.Site>`
"""
return connectToWiki(username, password, 'www.slicer.org', '/w/')
#---------------------------------------------------------------------------
def connectToWikiByName(name):
try:
wiki = cacheEntry('wiki-{0}'.format(name))
except KeyError:
username = cacheEntry("wiki-{0}-username".format(name))
password = cacheEntry("wiki-{0}-password".format(name))
host = cacheEntry("wiki-{0}-host".format(name))
path = cacheEntry("wiki-{0}-path".format(name))
wiki = setCacheEntry('wiki-{0}'.format(name),
connectToWiki(username, password, host, path))
return wiki
#---------------------------------------------------------------------------
def connectToWiki(username, password, host, path):
"""
:returns: Site object allowing to interact with the wiki.
:rtype: :class:`mwclient.Site <mwclient:mwclient.client.Site>`
"""
import mwclient
site = mwclient.Site(host, path=path)
site.login(username, password)
print("\nConnected to '{host}{path}' as user '{username}'".format(
host=site.host, path=site.path, username=username))
return site
#---------------------------------------------------------------------------
def convertTitleToWikiAnchor(title):
"""Convert section title into a identifier that can be used to reference
the section in link.
:param title:
Section title
:type title:
:class:`basestring`
:returns: Anchor that can be used to reference the associated section.
:rtype: :class:`basestring`
"""
# Following snippet has been adapted from mediawiki code base
# 1) normalize
title = re.sub(r'[ _]+', ' ', title)
# 2) See Title::newFromText in mediawiki
title = title.replace(' ', '_')
# * decodeCharReferencesAndNormalize: Convert things like é ā or 〗 into normalized text
# XXX title = decodeCharReferencesAndNormalize(title)
# * Strip Unicode bidi override characters.
title = re.sub(r'\xE2\x80[\x8E\x8F\xAA-\xAE]', '', title)
# * Clean up whitespace
# XXX title = re.sub(r'[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]', '_', title)
title = title.strip('_')
# 2) See Title::getFragmentForURL -> Title::escapeFragmentForURL -> Sanitized::escapeId
title = re.sub(r'[ \t\n\r\f_\'"&#%]', '_', title)
title = title.strip('_')
title = urllib.quote_plus(title)
# * HTML4-style escaping
title = title.replace('%3A', ':')
title = title.replace('%', '.')
return title
#---------------------------------------------------------------------------
def extractExtensionName(descriptionFile):
return os.path.basename(os.path.splitext(descriptionFile)[0])
#---------------------------------------------------------------------------
def prettify(name):
"""Source: http://stackoverflow.com/questions/5020906/python-convert-camel-case-to-space-delimited-using-regex-and-taking-acronyms-in
"""
name = re.sub(r'^Slicer(Extension)?[\-\_]', "", name)
#return re.sub("([a-z])([A-Z])","\g<1> \g<2>", name).replace('_', ' ')
return name
#---------------------------------------------------------------------------
def getDescriptionFiles(extensionsIndexDir, skip = []):
s4extFiles = []
files = os.listdir(extensionsIndexDir)
for descriptionFile in files:
if not fnmatch.fnmatch(descriptionFile, '*.s4ext'):
continue
if extractExtensionName(descriptionFile) in skip:
continue
s4extFiles.append(os.path.join(extensionsIndexDir, descriptionFile))
return s4extFiles
#---------------------------------------------------------------------------
def getExtensionHomepages(files):
import SlicerWizard as sw
print("\nCollecting extension homepage links")
homepages = {}
for file_ in files:
desc = sw.ExtensionDescription(filepath=file_)
name = extractExtensionName(file_)
homepages[name] = desc.homepage
return homepages
#---------------------------------------------------------------------------
def wikiPageExists(wikiName, page):
try:
exist = persistentCacheEntry(page)
except KeyError:
wiki = connectToWikiByName(wikiName)
exist = setPersistentCacheEntry(page, wiki.Pages[page].exists)
return exist
#---------------------------------------------------------------------------
WIKI_LINK_INTERNAL = 0
WIKI_LINK_EXTERNAL = 1
WIKI_LINK_OFF = 2
#---------------------------------------------------------------------------
def wikiPageToWikiLink(page, name=None):
if not name:
return "[[{}]]".format(page)
else:
return wikiPageToWikiLink("{0}|{1}".format(page, name))
#---------------------------------------------------------------------------
def urlToWikiLink(url, name):
return "[{0} {1}]".format(url, name)
#---------------------------------------------------------------------------
def _generateWikiLink(type_, what, name, linkName, url=None, slicerVersion=None):
if type_ == WIKI_LINK_INTERNAL:
if not slicerVersion:
raise RuntimeError, ("slicerVersion parameter is required when "
"specifying WIKI_LINK_INTERNAL wiki link type.")
release = getSlicerReleaseIdentifier(slicerVersion)
page = "Documentation/{release}/{what}/{name}".format(
release=release, what=what, name=name)
return wikiPageToWikiLink(page, linkName)
elif type_ == WIKI_LINK_EXTERNAL:
return urlToWikiLink(url, linkName)
else: # WIKI_LINK_OFF
return linkName
#---------------------------------------------------------------------------
def _createLinkItem(type_, what, name, linkName, url=None, slicerVersion=None):
return {'name' : name,
'wikilink' : _generateWikiLink(type_, what, name, linkName, url=url, slicerVersion=slicerVersion),
'type' : type_,
'url' : url}
#---------------------------------------------------------------------------
def generateItemWikiLinks(what, wikiName, homepages, slicerVersion=None):
if slicerVersion is None:
slicerVersion = getSlicerVersion(slicerBuildDir)
releaseIdentifier = getSlicerReleaseIdentifier(slicerVersion)
print("\nGenerating {0} wiki links for Slicer {1}:".format(what, releaseIdentifier))
wikiLinks = {}
for idx, (name, homepage) in enumerate(homepages.iteritems()):
if idx % 5 == 0:
print(" {:.0%}".format(float(idx) / len(homepages)))
item = _createLinkItem(WIKI_LINK_INTERNAL, what, name, prettify(name), slicerVersion=slicerVersion)
# If wiki page does NOT exist use the homepage link provided in the description file
if not wikiPageExists(wikiName, "Documentation/{0}/{1}/{2}".format(releaseIdentifier, what, name)):
if homepage:
item = _createLinkItem(WIKI_LINK_EXTERNAL, what, name, prettify(name), url=homepage)
else:
item = _createLinkItem(WIKI_LINK_OFF, what, name, prettify(name))
wikiLinks[name] = item
return wikiLinks
#---------------------------------------------------------------------------
def saveWikiPage(wikiName, name, summary, content):
wiki = connectToWikiByName(wikiName)
page = wiki.Pages[name]
return page.save(content, summary=summary)
#---------------------------------------------------------------------------
def getCategoryItems(itemCategories):
#----------------------------------------------------------------------
def _getParentCategory(category):
subModuleCategories = category.split('.')
parentCategory = subcategories
for subModuleCategory in subModuleCategories:
if subModuleCategory not in parentCategory:
parentCategory[subModuleCategory] = {}
parentCategory[subModuleCategory]['_ITEMS_'] = []
parentCategory = parentCategory[subModuleCategory]
return parentCategory
subcategories = {}
for name in itemCategories:
categories = ['Uncategorized']
if len(itemCategories[name]) > 0:
categories = itemCategories[name]
for category in categories:
# Skip empty category
if not category.strip():
continue
# Consider sub-categories
parentCategory = _getParentCategory(category)
parentCategory['_ITEMS_'].append(name)
return subcategories
#---------------------------------------------------------------------------
def getModuleCategories(modulesMetadata):
print("\nCollecting module 'categories'")
return {name: modulesMetadata[name]['categories'] for name in modulesMetadata}
#---------------------------------------------------------------------------
def getExtensionCategories(files):
import SlicerWizard as sw
print("\nCollecting extension 'categories'")
categories = {}
for file_ in files:
desc = sw.ExtensionDescription(filepath=file_)
name = extractExtensionName(file_)
categories[name] = []
if hasattr(desc, 'category') and desc.category.strip():
categories[name] = [desc.category]
return categories
#---------------------------------------------------------------------------
def _appendToDictValue(dict_, key, value, allowDuplicate=True):
if key not in dict_:
dict_[key] = []
append = True
if not allowDuplicate and value in dict_[key]:
append = False
if append:
dict_[key].append(value)
#---------------------------------------------------------------------------
def parseContributors(name, contributors):
# XXX This has been copied from [1]
# [1] https://github.com/Slicer/Slicer/blob/a8a01aa29210f938eaf48bb5c991681c3c67632d/Modules/Scripted/ExtensionWizard/ExtensionWizardLib/EditExtensionMetadataDialog.py#L101
def _parseIndividuals(individuals):
# Clean inputs
individuals = individuals.replace("This tool was developed by", "")
# Split by ',' and 'and', then flatten the list using itertools
individuals=list(itertools.chain.from_iterable(
[individual.split("and") for individual in individuals.split(",")]))
# Strip spaces and dot from each individuals and remove empty ones
individuals = filter(None, [individual.strip().strip(".") for individual in individuals])
return individuals
def _parseOrganization(organization):
try:
c = organization
c = c.strip()
n = c.index("(")
individuals = _parseIndividuals(c[:n].strip())
organization = c[n+1:-1].strip()
except ValueError:
individuals = _parseIndividuals(organization)
organization = ""
return (organization, individuals)
def _parseContributors(contributors):
orgs = re.split("(?<=[)])\s*,", contributors)
for c in orgs:
c = c.strip()
if not c:
print(" {0}: no contributors".format(name))
continue
(organization, individuals) = _parseOrganization(c)
for individual in individuals:
if individual == "":
print(" {0}: organization {1} has no individuals".format(name, organization))
continue
_appendToDictValue(orgToIndividuals, organization, individual)
_appendToDictValue(individualToOrgs, individual, organization)
orgToIndividuals = {}
individualToOrgs = {}
# Split by organization
if isinstance(contributors, basestring):
contributors = [contributors]
for contributor in contributors:
_parseContributors(contributor)
return (orgToIndividuals, individualToOrgs)
#---------------------------------------------------------------------------
def getExtensionContributors(files):
import SlicerWizard as sw
print("\nCollecting extension 'contributors'")
contributors = {}
for file_ in files:
desc = sw.ExtensionDescription(filepath=file_)
name = extractExtensionName(file_)
if not hasattr(desc, 'contributors'):
print(" skipping %s: missing contributors field" % name)
continue
contributors[name] = desc.contributors
return contributors
#---------------------------------------------------------------------------
def getModuleContributors(modulesMetadata):
print("\nCollecting module 'contributors'")
return {name: modulesMetadata[name]['contributors'] for name in modulesMetadata}
#---------------------------------------------------------------------------
def getContributingOrganizationsAndIndividuals(itemContributors):
organizationItems = {}
individualItems = {}
itemOrganizations = {}
individualOrganizations = {}
for itemName, contributors in itemContributors.iteritems():
(orgToIndividuals, individualToOrgs) = parseContributors(itemName, contributors)
for organization in orgToIndividuals.keys():
_appendToDictValue(organizationItems, organization, itemName)
itemOrganizations[itemName] = orgToIndividuals
for individual in individualToOrgs.keys():
_appendToDictValue(individualItems, individual, itemName)
orgs = individualToOrgs[individual]
for org in orgs:
if org:
_appendToDictValue(individualOrganizations, individual, org, allowDuplicate=False)
return (organizationItems, individualItems, itemOrganizations, individualOrganizations)
#---------------------------------------------------------------------------
def sortKeys(dict_, prettifyKey=False):
"""Return list of sorted dictionnary keys.
"""
def _updateKey(s):
s = s.lower()
if prettifyKey:
s = prettify(s)
return s
return sorted(dict_, key=_updateKey)
#---------------------------------------------------------------------------
def sortPrettifiedKeys(dict_):
"""Return list of sorted dictionnary keys.
"""
return sortKeys(dict_, prettifyKey=True)
#---------------------------------------------------------------------------
def generateContributorsWikiLinks(extensionName, organizations):
for org in sortPrettifiedKeys(organizations):
orgLink = "[[#{}|{}]]".format(org, org)
for individual in sortPrettifiedKeys(organizations[org]):
individualLink = "[[#{}|{}]]".format(individual, individual)
#---------------------------------------------------------------------------
def tocEntryAsWikiListItem(name, level=0, anchor=None, extras=[]):
return linkAsWikiListItem(
wikiPageToWikiLink('#' + convertTitleToWikiAnchor(name if anchor is None else anchor), prettify(name)),
level, extras)
#---------------------------------------------------------------------------
def individualEntryAsWikiListItem(name, level=0):
extras = []
individualOrganizations = cacheEntry("individualOrganizations")
if name in individualOrganizations:
if individualOrganizations[name]:
extras.append(individualOrganizations[name][0])
return tocEntryAsWikiListItem(name, level, extras=extras)
#---------------------------------------------------------------------------
def headerForWikiList(title, teaser):
lines = []
lines.append(u"= {} =".format(title))
lines.extend(teaser)
return lines
#---------------------------------------------------------------------------
def linkAsWikiListItem(link, level=0, extras=[]):
wikilink = link
if isinstance(link, dict):
wikilink = link['wikilink']
extraTxt = " <small>({})</small>".format(", ".join(extras)) if extras else ""
return "{0} {1}{2}".format("*"*(level+1), wikilink, extraTxt)
#---------------------------------------------------------------------------
def footerForWikiList(title, teaser):
return []
#---------------------------------------------------------------------------
def moduleLinkAsListItem(link, level=0):
name = link['name']
extras = []
moduleTypes = cacheEntry("moduleTypes")
moduleExtensions = cacheEntry("moduleExtensions")
if name in moduleExtensions:
extensionName = moduleExtensions[name]
extensionLinks = cacheEntry("extensionLinks")
# type (cli, loadable, scripted)
extras.append(moduleTypes[name])
# provenance (built-in or extension)
if extensionName in extensionLinks:
extras.append("bundled in {} extension".format(extensionLinks[extensionName]['wikilink']))
elif extensionName == 'builtin':
extras.append("built-in")
return linkAsWikiListItem(link, level, extras)
#---------------------------------------------------------------------------
linksAsWikiList = (headerForWikiList, linkAsWikiListItem, footerForWikiList)
# #---------------------------------------------------------------------------
# def headerForWikiTable():
# pass
#
# #---------------------------------------------------------------------------
# def linkAsWikiTableEntry():
# pass
#
# #---------------------------------------------------------------------------
# def headerForWikiTable():
# pass
#---------------------------------------------------------------------------
# linksAsWikiTable = (headerForWikiTable, linkAsWikiTableEntry, headerForWikiTable)
#---------------------------------------------------------------------------
def itemByCategoryToWiki(what, links, categories, linksRenderer=linksAsWikiList,
tocEntryRenderer=tocEntryAsWikiListItem, withToc=False):
def _traverse(categories, lines, categoryCallback,
itemCallback=None,
category=None, completeCategory=None,
level=-1,
lookup=lambda item:item):
if category:
categoryAnchor = sectionAnchor + '_' + convertTitleToWikiAnchor(completeCategory)
lines.append(categoryCallback(category, level, categoryAnchor))
if itemCallback and '_ITEMS_' in categories:
for item in categories['_ITEMS_']:
lines.append(itemCallback(lookup(item)))
for subcategory in sortKeys(categories):
if subcategory == '_ITEMS_':
continue
level = level + 1
_traverse(categories[subcategory], lines, categoryCallback,
itemCallback=itemCallback,
category=subcategory,
completeCategory=subcategory if category is None else category + '_' + subcategory,
level=level, lookup=lookup)
level = level - 1
title = "{0} by category".format(what)
print("\nGenerating '%s' section" % title)
sectionAnchor = convertTitleToWikiAnchor(title)
teaser = []
if withToc:
teaser.append("{} categories:".format(len(categories)))
_traverse(categories, teaser, tocEntryRenderer)
else:
teaser.append("{} categories".format(len(categories)))
lines = []
lines.extend(headerForWikiList(title, teaser))
# content
_traverse(categories, lines,
lambda category, level, anchor:
u"<span id='{}'></span>\n".format(anchor) +
u"{0} {1} {0}".format("="*(level+2), category),
itemCallback=linksRenderer[1], lookup=lambda item:links[item])
return (title, '#' + sectionAnchor, lines)
#---------------------------------------------------------------------------
def itemByNameToWiki(what, links, linksRenderer=linksAsWikiList):
title = "{0} by name".format(what)
print("\nGenerating '{0}' section".format(title))
teaser = ["{0} {1}:".format(len(links), what.lower())]
lines = []
lines.extend(linksRenderer[0](title, teaser))
for name in sortPrettifiedKeys(links):
lines.append(linksRenderer[1](links[name]))
lines.extend(linksRenderer[2](title, teaser))
return (title, '#' + convertTitleToWikiAnchor(title), lines)
#---------------------------------------------------------------------------
def itemByPropertyToWiki(what, links, description, items,
linksRenderer=linksAsWikiList,
tocEntryRenderer=tocEntryAsWikiListItem, withToc=False):
title = "{0} by {1}".format(what, description)
print("\nGenerating '%s' section" % title)
teaser = []
if withToc:
teaser.append("{0} {1}s:".format(len(items), description))
for name in sortKeys(items):
if not name or len(items[name]) == 0:
continue
teaser.append(tocEntryRenderer(name))
else:
teaser.append("{0} {1}s".format(len(items), description))
lines = []
lines.extend(linksRenderer[0](title, teaser))
for item in sortKeys(items):
if item != "" and len(items[item]) > 0:
lines.append("== {} ==".format(item))
for name in sortPrettifiedKeys(items[item]):
if item == "":
print(u" skipping {0}: missing '{1}'".format(name, description))
continue
lines.append(linksRenderer[1](links[name]))
lines.extend(linksRenderer[2](title, teaser))
return (title, '#' + convertTitleToWikiAnchor(title), lines)
#---------------------------------------------------------------------------
def getMetadataFiles(prefix):
"""Return a list of files associated with ``prefix``.
"""
targetDir = getPackagesMetadataDataDirectory()
print("\nScanning directory '{0}' using prefix '{1}'".format(targetDir, prefix))
files = glob.glob(os.path.join(targetDir, '{0}_*.json'.format(prefix)))
print("\nFound {0} file(s) matching prefix '{1}'".format(len(files), prefix))
for file in files:
print(" {}".format(file))
return files
#---------------------------------------------------------------------------
def _merge(a, b, path=None):
"Merge b into a"
# See http://stackoverflow.com/a/7205107/1539918
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
_merge(a[key], b[key], path + [str(key)])
elif isinstance(a[key], list) and isinstance(b[key], list):
a[key] = list(set(a[key] + b[key]))
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
#---------------------------------------------------------------------------
def mergeMetadataFiles(prefix):
"""Return a merged dictonnary of all metadata files associated with ``prefix``.
"""
#-----------------------------------------------------------------------
def _readJson(filePath):
with codecs.open(filePath, 'r', 'utf-8') as fileContents:
return json.load(fileContents)
return reduce(_merge, [_readJson(filePath) for filePath in getMetadataFiles(prefix)])
#---------------------------------------------------------------------------
def cloneRepository(git_url, repo_dir, branch='master'):
"""Clone ``git_url`` into ``repo_dir`` and return a reference to it.
If a clone already exists, local change are discarded and ``branch``
is checked out. Then, a reference to the clone is returned.
"""
if not os.path.isdir(repo_dir):
git.Repo.clone_from(git_url, repo_dir)
print("Cloned '{0}' into '{1}'".format(git_url, repo_dir))
repo = git.Repo(repo_dir)
print("\nFound '{0}' in '{1}'".format(git_url, repo.working_dir))
checkoutBranch(repo, branch)
return repo
#---------------------------------------------------------------------------
def checkoutBranch(repo, branch):
"""Discard local ``repo`` changes, fetch remote changes and checkout
``branch``.
"""
print("\nDiscarding local changes in '{}'".format(repo.working_dir))
# Discard local changes
repo.git.reset('--hard','HEAD')
# Fetch changes
origin = repo.remotes.origin
print("\nFetching changes from '{}'".format(origin.url))
origin.fetch()
# Checkout branch and update branch
repo.git.checkout(branch)
print("\nApplying changes")
repo.git.reset('--hard','origin/{}'.format(branch))
#---------------------------------------------------------------------------
SLICER_PACKAGES_METADATA_GIT_URL = '[email protected]:Slicer/slicer-packages-metadata'
SLICER_EXTENSIONS_INDEX_GIT_URL = 'git://github.com/Slicer/ExtensionsIndex'
#---------------------------------------------------------------------------
def getPackagesMetadataTopLevelDirectory():
return os.path.join(tempfile.gettempdir(), 'slicer-packages-metadata')
#---------------------------------------------------------------------------
def getPackagesMetadataDataDirectory():
metadataDir = os.path.join(getPackagesMetadataTopLevelDirectory(), 'metadata')
if not os.path.exists(metadataDir):
os.makedirs(metadataDir)
return metadataDir
#---------------------------------------------------------------------------
def getExtensionsIndexTopLevelDirectory():
return os.path.join(tempfile.gettempdir(), 'slicer-extensions-index')
#---------------------------------------------------------------------------
def getModuleLinks(wikiName, modulesMetadata, slicerVersion=None):
moduleLinks = \
generateItemWikiLinks('Modules', wikiName,
{name:"" for name in modulesMetadata.keys()}, slicerVersion)
return moduleLinks
#---------------------------------------------------------------------------
def getExtensionLauncherAdditionalSettingsFromBuildDirs(slicerExtensionsIndexBuildDir):
launcherSettingsFiles = []
for dirname in os.listdir(slicerExtensionsIndexBuildDir):
extensionBuildDir = os.path.join(slicerExtensionsIndexBuildDir, dirname)
if os.path.isdir(extensionBuildDir):
if dirname.endswith('-build'):
launcherSettings = getExtensionLauncherSettings(extensionBuildDir)
if launcherSettings is not None:
launcherSettingsFiles.append(launcherSettings)
return launcherSettingsFiles
#---------------------------------------------------------------------------
def _readLauncherSettings(settingsFile):
"""This function read the given ``settingsFile``, trim all lines
and return the corresponding buffer.
.. note::
This function is needed for Slicer < r24174. For new version of Slicer,
the settings generation has been fixed.
"""
updatedFileContents = []
with open(settingsFile) as fileContents:
for line in fileContents:
updatedFileContents.append(line.lstrip().rstrip('\n'))
return '\n'.join(updatedFileContents)
#---------------------------------------------------------------------------
def readAdditionalLauncherSettings(settingsFile, configs):
"""Read ``settingsFile`` and populate the provided ``configs`` dictionnary.
"""
parser = ConfigParser.ConfigParser()
settingsFileContents = _readLauncherSettings(settingsFile)
parser.readfp(io.BytesIO(settingsFileContents))
for section in ['LibraryPaths', 'Paths', 'PYTHONPATH', 'QT_PLUGIN_PATH']:
if not parser.has_section(section):
continue
if section not in configs:
configs[section] = []
for idx in range(parser.getint(section, 'size')):
configs[section].append(parser.get(section, '{0}\\path'.format(idx+1)))
#---------------------------------------------------------------------------
def writeLauncherAdditionalSettings(outputSettingsFile, configs):
"""Write ``outputSettingsFile`` using provided ``configs`` dictionnary.
"""
with open(outputSettingsFile, 'w') as fileContents:
def _writeSection():
fileContents.write('[{0}]\n'.format(section))
items = configs[section]
size = len(items)
for idx in range(size):
fileContents.write('{0}\\path={1}\n'.format(idx+1, items[idx]))
fileContents.write('size={0}\n'.format(size))
for section in configs:
_writeSection()
fileContents.write('\n')
#---------------------------------------------------------------------------
def mergeExtensionsLauncherAdditionalSettings(slicerExtensionsIndexBuildDir):
mergedSettingsFile = getPackagesMetadataTopLevelDirectory() + "AdditionalLauncherSettings.ini"
print("\nCreating {0}".format(mergedSettingsFile))
# Read extension launcher additional settings
settingsFiles = getExtensionLauncherAdditionalSettingsFromBuildDirs(slicerExtensionsIndexBuildDir)
configs = {}
for settingsFile in settingsFiles:
readAdditionalLauncherSettings(settingsFile, configs)
# Write common launcher additional settings
writeLauncherAdditionalSettings(mergedSettingsFile, configs)
return mergedSettingsFile
#---------------------------------------------------------------------------
def getSlicerLauncher(slicerBuildDir):
launcher = os.path.join(slicerBuildDir, _e('Slicer'))
if not os.path.exists(launcher):
return None
return launcher
#---------------------------------------------------------------------------
def _e(name):
"""Append the executable suffix corresponding to the platform running
this script.
"""
return name if not sys.platform.startswith('win') else name + '.exe'
#---------------------------------------------------------------------------
def installPip(slicerBuildDir=None):
url = 'https://bootstrap.pypa.io/get-pip.py'
filePath = os.path.basename(url)
print("\nDownloading '{0}' into '{1}'".format(url, filePath))
response = urllib2.urlopen(url)
with open(filePath, "wb") as fileContents:
fileContents.write(response.read())
# XXX See https://github.com/commontk/AppLauncher/issues/57
pythonExecutable = _e('python')
if sys.platform == 'darwin':
pythonExecutable = os.path.join(slicerBuildDir, '../python-install/bin/python')
print("\nInstalling pip")
slicerLauncherPopen(getSlicerLauncher(slicerBuildDir), ['--launch', pythonExecutable, filePath])
#---------------------------------------------------------------------------
def runPip(args, slicerBuildDir=None):
def _runPip():
print("\npip {0}".format(" ".join(args)))
slicerLauncherPopen(getSlicerLauncher(slicerBuildDir), ['--launch', _e('pip')] + args)
try:
_runPip()
except RuntimeError:
installPip(slicerBuildDir)
_runPip()
#---------------------------------------------------------------------------
def slicerLauncherPopen(launcher, args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
if launcher is None:
args.pop(0) # Ignore '--launch' argument
print("\nStarting {0}".format(" \\\n ".join(args)))
else:
print("\nStarting {0} {1}".format(launcher, " \\\n ".join(args)))
p = subprocess.Popen([launcher] + args, stdout=stdout, stderr=stderr, **kwargs)
ec = p.wait()
if ec:
raise RuntimeError, "Calling {0} failed (exit code {1})".format(launcher, ec)
return p
#---------------------------------------------------------------------------
def getSlicerVersion(slicerBuildDir):
p = slicerLauncherPopen(getSlicerLauncher(slicerBuildDir), ['--version'])
if p is None:
return None
version = p.stdout.read().strip() # Slicer X.Y.Z[-YYYY-MM-DD]
print("\nAuto-discovered version is '{0}' [major.minor:{1}, release:{2}]".format(
version,
getSlicerMajorMinorVersion(version),
isSlicerReleaseVersion(version)))
return version
#---------------------------------------------------------------------------
def getSlicerMajorMinorVersion(slicerVersion):
version = re.findall(r'^Slicer (\d\.\d)', slicerVersion)[0]
return version
#---------------------------------------------------------------------------
def isSlicerReleaseVersion(slicerVersion):
"""Return True if the given slicer version corresponds to a
Slicer release.
>>> isSlicerReleaseVersion('foo')
False
>>> [isSlicerReleaseVersion('Slicer {}'.format(v)) for v in ['4.4', '4.4.1', '4.4.1-3']]
[True, True, True]
>>> [isSlicerReleaseVersion('Slicer {}-2014-12-23'.format(v)) for v in ['4.4', '4.4.1', '4.4.1-3']]
[False, False, False]
>>> [isSlicerReleaseVersion('Slicer {}-SomeText'.format(v)) for v in ['4.4', '4.4.1', '4.4.1-3']]
[False, False, False]
>>> [isSlicerReleaseVersion('Slicer {}-A'.format(v)) for v in ['4.4', '4.4.1', '4.4.1-3']]
[False, False, False]
>>> [isSlicerReleaseVersion('Slicer {}-0'.format(v)) for v in ['4.4', '4.4.1', '4.4.1-3']]
[False, True, False]
"""
return re.match(r'^Slicer \d\.\d(\.\d(\-\d)?)?$', slicerVersion) is not None
#---------------------------------------------------------------------------
def getModuleDirectories(basePath, slicerMajorMinorVersion):
"""Recursively walk ``basepath`` directory and return the list of directory expected
to contain cli, scripted or loadable modules.
"""
output = []
for subdir in ['cli-modules', 'qt-loadable-modules', 'qt-scripted-modules']:
moduleDir = os.path.join(basePath, 'lib', 'Slicer-{0}'.format(slicerMajorMinorVersion), subdir)
if os.path.isdir(moduleDir):
output.append(moduleDir)
if os.path.isdir(basePath) and os.path.basename(basePath) not in ['_CPack_Packages']:
for dirname in os.listdir(basePath):
output.extend(getModuleDirectories(os.path.join(basePath, dirname), slicerMajorMinorVersion))
return output
#---------------------------------------------------------------------------
def getExtensionLauncherSettings(extensionBuildDir):
"""Recursively walk an extension build directory until a file named
`AdditionalLauncherSettings.ini` is found.
"""
for filename in os.listdir(extensionBuildDir):
filepath = os.path.join(extensionBuildDir, filename)
if filename == 'AdditionalLauncherSettings.ini':
return filepath
elif not os.path.isdir(filepath):
continue
else:
return getExtensionLauncherSettings(filepath)
#---------------------------------------------------------------------------
def isCLIExecutable(filePath):
import ctk_cli
result = ctk_cli.isCLIExecutable(filePath)
if not result:
return False
moduleName = extractCLIModuleName(filePath)
# for pattern in ['Test$']:
# if re.search(pattern, moduleName, flags=re.IGNORECASE) is not None:
# return False
return True
#---------------------------------------------------------------------------
def extractCLIModuleName(filePath):
name = os.path.basename(filePath)
if name.endswith('.exe'):
name = result[:-4]
return name
#---------------------------------------------------------------------------
def isLoadableModule(filePath):
return extractLoadableModuleName(filePath) is not None
#---------------------------------------------------------------------------
def extractLoadableModuleName(filePath):
# See qSlicerUtils::isLoadableModule
result = re.match("(?:libqSlicer(.+)Module\\.(?:so|dylib))|(?:(?!lib)qSlicer(.+)Module\\.(?:dll|DLL))", os.path.basename(filePath))
name = None
if result is not None:
name = result.group(1) if result.group(1) is not None else result.group(2)
return name
#---------------------------------------------------------------------------
def isScriptedModule(filePath):
isScript = os.path.splitext(filePath)[-1] == '.py'
if not isScript:
return False
moduleName = extractScriptedModuleName(filePath)
for pattern in ['Plugin', 'SelfTest', 'Test', '\d{4}', 'Tutorial']:
if re.search(pattern, moduleName, flags=re.IGNORECASE) is not None:
return False
return moduleName
#---------------------------------------------------------------------------
def extractScriptedModuleName(filePath):
return os.path.splitext(os.path.basename(filePath))[0]
#---------------------------------------------------------------------------
def _getModuleNames(tester, extractor, buildDir):
names = []
for path in os.listdir(buildDir):
filePath = os.path.join(buildDir, path)
if tester(filePath):
names.append(extractor(filePath))
return names
#---------------------------------------------------------------------------
def getCLIModuleNames(buildDir):
return _getModuleNames(isCLIExecutable, extractCLIModuleName, buildDir)
#---------------------------------------------------------------------------
def getLoadableModuleNames(buildDir):
return _getModuleNames(isLoadableModule, extractLoadableModuleName, buildDir)
#---------------------------------------------------------------------------
def getScriptedModuleNames(buildDir):
return _getModuleNames(isScriptedModule, extractScriptedModuleName, buildDir)
#---------------------------------------------------------------------------
def getModuleNamesByType(modulePaths):
"""Return a dictionnary of module types and associated module names
given a list of module paths.
.. note::
Module types are indentified using keys ``cli``, ``loadable`` and ``scripted``.
"""
results = {
'cli':[],
'loadable':[],
'scripted':[]
}