generated from AlabamaWaterInstitute/awi-open-source-project-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsetup_project.py
1282 lines (1209 loc) · 52.8 KB
/
setup_project.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
import sys, os, json, re, time, datetime, logging, traceback, ast
from pathlib import Path
from typing import Any
project_name = "unithg_bmi"
proj_folder = Path("unithg_bmi")
this_folder = Path(".")
requirements = []
author_name = "Chad Perry"
author_github_link = "https://github.com/chp2001"
# Month Day, Year
current_date = datetime.datetime.now().strftime("%B %d, %Y")
def harvest_requirements(src_dir:Path = proj_folder, requirements:list[str] = []):
for name in src_dir.iterdir():
if name.is_dir():
harvest_requirements(name, requirements)
elif name.suffix == ".py":
tree = ast.parse(name.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name == ".":
continue
requirements.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.module == None:
continue
requirements.append(node.module)
return requirements
def project_filenames(src_dir:Path = proj_folder, filenames:list[str] = []):
for name in src_dir.iterdir():
if name.is_dir():
project_filenames(name, filenames)
elif name.suffix == ".py":
filenames.append(name.name)
return filenames
project_files = project_filenames()
_requirements = harvest_requirements()
for req in _requirements:
_req = req
if req in sys.builtin_module_names or req in sys.stdlib_module_names:
continue
if req == project_name:
continue
if req.startswith("."):
continue
if "." in req:
req = req.split(".")[0]
if (proj_folder/req).exists() or (proj_folder/(req + ".py")).exists():
continue
if req + ".py" in project_files:
continue
print(f"Adding requirement: {_req}")
requirements.append(req)
requirements = list(set(requirements))
requirements.sort()
print(requirements)
def build_requirements_txt(requirements:list[str], path:Path = this_folder/"requirements.txt"):
path.write_text("\n".join(requirements))
build_requirements_txt(requirements)
def build_pyproject_toml(project_name:str, requirements:list[str], path:Path = this_folder/"pyproject.toml"):
toml = {}
toml["build-system"] = {
"requires": ["setuptools", "wheel"],
"build-backend": "setuptools.build_meta"
}
toml["project"] = {
"name": project_name,
"version": "0.1.0",
"description": "A Python-based Ngen-BMI model for unit hydrograph.",
"authors": [{"name": author_name}],
"maintainers": [{"name": author_name}],
"license": {"file": "LICENSE"},
"requires-python": ">=3.9",
}
dependencies = requirements
toml["project"]["dependencies"] = dependencies
# toml["project"]["dynamic"] = ["readme"]
toml["tool.setuptools.packages.find"] = {"where": ["."]}
def toml_str(toml:dict):
def toml_val_len(val:Any):
if isinstance(val, list):
return sum([toml_val_len(v) for v in val])
elif isinstance(val, dict):
return sum([1 + toml_val_len(v) for k, v in val.items()])
return 1
def toml_val_str(val:Any):
if isinstance(val, str):
return f'"{val}"'
elif isinstance(val, list):
len_val = toml_val_len(val)
if len_val == 0:
return "[]"
if len_val <= 2:
# Inline list
return f"[{', '.join([toml_val_str(v) for v in val])}]"
# Multiline list
result = "[\n"
indent = "\t"
for v in val:
result += f"{indent}{toml_val_str(v)},\n"
result += "]"
return result
elif isinstance(val, dict):
return f"{{{', '.join([f'{k} = {toml_val_str(v)}' for k, v in val.items()])}}}"
return str(val)
cats = []
for cat, val in toml.items():
cat_str = f"[{cat}]\n"
# val is always a dict
val:dict[str, Any]
for key, val in val.items():
cat_str += f"{key} = {toml_val_str(val)}\n"
cats.append(cat_str)
return "\n".join(cats)
path.write_text(toml_str(toml))
build_pyproject_toml(project_name, requirements)
def build_init_py(path:Path = proj_folder/"__init__.py"):
imports = []
for name in proj_folder.iterdir():
if name.is_dir():
prefix = name.name
for subname in name.iterdir():
if subname.suffix == ".py":
imports.append(f"from .{prefix}.{subname.stem} import *")
elif name.suffix == ".py":
if name.stem == "__init__":
continue
imports.append(f"from .{name.stem} import *")
path.write_text("\n".join(imports))
build_init_py()
# build README.md
from typing import List, Tuple, Dict, Set, Any, Union, Callable, Literal, Optional, TypeVar, _SpecialForm
@_SpecialForm
def Listable(self, param:type):
"""
Listable[arg] -> Union[List[arg], arg]
Allows annotating a type as either a list of a type or the type itself.
"""
arg = param
if not isinstance(arg, type) and not "typing" in str(arg):
raise TypeError(f"Listable[...] expects a type, not {arg}(type={type(arg)})")
return Union[List[arg], arg]
from abc import ABC, abstractmethod
class Markdown(ABC):
format_type:str = "N/A"
data:Any
addable:bool = False
def __init__(self, data:Optional[Any]=None):
self.data = data
@abstractmethod
def build(self, indent:int=0)->str:
pass
def __str__(self)->str:
return self.build()
def __repr__(self)->str:
return f"{self.format_type}({self.data})"
def multiline_indent(self, text:str, indent:int)->str:
return "\n".join([f"{' ' * indent}{line}" for line in text.split("\n")])
@abstractmethod
def __len__(self)->int: pass
@abstractmethod
def __height__(self, maxwidth:Optional[int] = None)->int: pass
def __width__(self)->int:
return len(self)
def size(self)->int:
"""Total expected text amount."""
if isinstance(self.data, Markdown):
return self.data.size()
elif isinstance(self.data, list):
size = 0
for item in self.data:
if isinstance(item, Markdown):
size += item.size()
else:
size += len(str(item))
return size
return len(str(self.data))
def width(markdown:Markdown)->int:
return markdown.__width__() if hasattr(markdown, "__width__") else len(markdown)
class SingleItem(Markdown):
"""
Abstract base class for Markdown elements that contain a single item/line.
Purpose is to provide a common height and width method for relevant Markdown elements.
"""
words:List[str]
def __width__(self)->int:
_width = 0
if hasattr(self.data, "__iter__"):
for item in self.data:
if isinstance(item, Markdown):
_width += width(item)
else:
_width += len(str(item))
else:
_width = width(self.data)
return _width
def __height__(self, maxwidth:Optional[int] = None)->int:
if maxwidth is None:
return 1
height = 0
xsize = 0
for item in self.data:
if isinstance(item, Markdown):
_width = width(item)
else:
_width = len(str(item))
if xsize + _width > maxwidth:
height += 1
xsize = 0
xsize += _width
return height
def __len__(self)->int:
return self.__width__()
class MultiItem(Markdown):
"""
Abstract base class for Markdown elements that contain multiple items/lines.
"""
def __width__(self)->int:
return max([width(item) for item in self.data])
def __height__(self, maxwidth:Optional[int] = None)->int:
if maxwidth is None:
return len(self.data)
return sum([item.__height__(maxwidth) for item in self.data])
def __len__(self)->int:
return len(self.data)
class Text(SingleItem):
format_type:str = "Text"
data:List[Union[str, Markdown]]
words:List[str]
addable:bool = True
def __init__(self, data:List[Union[str, Markdown]]):
self.words = []
self.data = []
self.add(data)
def add(self, text:Union[str, Markdown, List[Union[str, Markdown]]]):
if isinstance(text, list):
for item in text:
self.add(item)
return
self.data.append(text)
if isinstance(text, str):
self.words.extend(text.split())
elif isinstance(text, SingleItem):
self.words.extend(text.words)
else:
raise NotImplementedError(f"Unsupported text type: {type(text)}")
def build(self, indent:int=0)->str:
data = [item if isinstance(item, str) else item.build(indent) for item in self.data]
return "".join(data)
def __add__(self, other:Union[str, Markdown]):
self.data.append(other)
return self
def __iadd__(self, other:Union[str, Markdown]):
self.data.append(other)
return self
def __radd__(self, other:Union[str, Markdown]):
if isinstance(other, str):
other = Text([other])
return other + self
class Propagate(SingleItem):
"""Markdown element that has the infrastructure to concatenate with strings."""
def __add__(self, other:Union[str, Markdown]):
if isinstance(other, str):
return Text([self, other])
elif isinstance(other, Text):
other.data.insert(0, self)
return other
return self
def __iadd__(self, other:Union[str, Markdown]):
return self + other
def __radd__(self, other:Union[str, Markdown]):
if isinstance(other, str):
other = Text([other])
return other + self
class Header(Propagate):
"""Markdown header. Indent determines the number of '#' characters."""
format_type:str = "Header"
data:str
indent: int
def __init__(self, data:str, indent:int=2):
self.data = data
self.indent = indent
def build(self, _:int=None)->str:
header_str = "#" * min(self.indent, 4) # Max header level is 4
return f"{header_str} {self.data}\n"
class ListItem(SingleItem):
"""Unordered listitem."""
format_type:str = "ListItem"
data:Markdown
marker:str = "*"
indent:int
def __init__(self, data:Markdown, marker:str="*", indent:Optional[int]=None):
self.data = data
self.marker = marker
self.indent = indent if indent is not None else 0
def build(self, indent:Optional[int]=None)->str:
if indent is None:
indent = self.indent
return f"{' ' * indent}{self.marker} {self.data}\n"
class OrderedListItem(ListItem):
"""Ordered listitem."""
format_type:str = "OrderedListItem"
marker:str = "1."
indent:int
data:Markdown
def __init__(self, data:Markdown, indent:int=0):
super().__init__(data, indent=indent)
self.marker = "1."
def order(self, order:Union[str,int]):
if isinstance(order, int):
self.marker = f"{order}."
else:
self.marker = order
class UnOrderedList(Markdown):
"""Unordered list."""
format_type:str = "UnOrderedList"
data:List[ListItem]
addable:bool = True
def __init__(self, data:Optional[Union[str, ListItem, List[ListItem]]]=None):
self.data = []
if isinstance(data, str):
self.data.append(ListItem(data))
elif isinstance(data, ListItem):
self.data.append(data)
elif isinstance(data, list):
self.data.extend(data)
def build(self, indent:Optional[int]=None)->str:
result = "".join([item.build(indent) for item in self.data])
result = result.rstrip("\n") + "\n"
result = result.lstrip("\n") + "\n"
return result
def __add__(self, other:Union[str, ListItem])->'UnOrderedList':
if not isinstance(other, ListItem):
other = ListItem(other)
self.data.append(other)
return self
def __iadd__(self, other:Union[str, ListItem])->'UnOrderedList':
return self + other
def __len__(self)->int:
return len(self.data)
def __width__(self)->int:
return max([width(item) for item in self.data])
def __height__(self, maxwidth:Optional[int]=None)->int:
if maxwidth is None:
return len(self.data)
return sum([item.__height__(maxwidth) for item in self.data])
class OrderedList(UnOrderedList):
"""Ordered list."""
format_type:str = "OrderedList"
data:List[OrderedListItem]
addable:bool = True
def __init__(self, data:Optional[Union[str, OrderedListItem, List[OrderedListItem]]]=None):
self.data = []
if isinstance(data, str):
self.data.append(OrderedListItem(data))
elif isinstance(data, OrderedListItem):
self.data.append(data)
elif isinstance(data, list):
self.data.extend(data)
def build(self, _:Optional[int]=None)->str:
result = ""
marker_levels = [0] * (max([item.indent for item in self.data] + [0]) + 1)
for listitem in self.data:
indent = listitem.indent
marker_levels[indent] += 1
marker_levels[indent + 1:] = [0] * (5 - indent)
# marker = ".".join([str(marker_levels[j]) for j in range(indent + 1)])
marker = f"{marker_levels[indent]}"
listitem.order(marker + ".")
result += listitem.build()
return result
def __add__(self, other:Union[str, OrderedListItem])->'OrderedList':
if not isinstance(other, OrderedListItem):
other = OrderedListItem(other)
self.data.append(other)
return self
def __iadd__(self, other:Union[str, OrderedListItem])->'OrderedList':
return self + other
def __len__(self)->int:
return len(self.data)
def __width__(self)->int:
return max([width(item) for item in self.data])
def __height__(self, maxwidth:Optional[int]=None)->int:
if maxwidth is None:
return len(self.data)
return sum([item.__height__(maxwidth) for item in self.data])
class Link(Propagate):
"""Markdown link."""
format_type:str = "Link"
data:Tuple[str, str]
def build(self, indent:int=0)->str:
return f"[{self.data[0]}]({self.data[1]})"
class SectionLink(Link):
"""Markdown section link."""
format_type:str = "SectionLink"
data:Tuple[str, str]
def __init__(self, data:str):
self.data = (data, "#" + data.lower().replace(" ", "-"))
def build(self, indent:int=0)->str:
return f"[{self.data[0]}]({self.data[1]})"
class Image(Markdown):
"""Markdown image."""
format_type:str = "Image"
data:Tuple[str, str]
def build(self, indent:int=0)->str:
return f"![{self.data[0]}]({self.data[1]})"
class Bold(Propagate):
"""Markdown bold text."""
format_type:str = "Bold"
data:str
def build(self, indent:int=0)->str:
return f"**{self.data}**"
class Italic(Propagate):
"""Markdown italic text."""
format_type:str = "Italic"
data:str
def build(self, indent:int=0)->str:
return f"*{self.data}*"
class Code(Propagate):
"""Markdown code segment."""
format_type:str = "Code Segment"
data:str
def build(self, indent:int=0)->str:
return f"`{self.data}`"
class Underline(Propagate):
"""Markdown underline text."""
format_type:str = "Underline"
data:str
def build(self, indent:int=0)->str:
return f"<u>{self.data}</u>"
class Paragraph(MultiItem):
"""Markdown paragraph."""
format_type:str = "Paragraph"
data:List[Text]
addable:bool = True
def __init__(self, data:Optional[Union[str, Text, List[Text]]]=None):
self.data = []
if isinstance(data, str):
self.data.append(Text([data]))
elif isinstance(data, Text):
self.data.append(data)
elif isinstance(data, list):
for item in data:
if isinstance(item, str):
self.data.append(Text([item]))
else:
self.data.append(item)
def build(self, indent:int=0)->str:
result = "".join([item.build(indent) for item in self.data])
result = result.rstrip("\n") + "\n\n"
return result
def __add__(self, other:Union[str, Markdown])->'Paragraph':
if isinstance(other, Paragraph):
self.data.extend(other.data)
return self
elif isinstance(other, str):
other = Text([other])
self.data.append(other)
return self
def __iadd__(self, other:Union[str, Markdown])->'Paragraph':
return self + other
class CodeBlock(Paragraph):
"""Markdown code block."""
format_type:str = "Code Block"
data:List[Text]
language:str
def __init__(self, data:Any=None, language:str="python"):
super().__init__(data=data)
self.language = language
def build(self, indent:int=0)->str:
result = f"```{self.language}\n"
middle = "\n".join([item.build(indent) for item in self.data])
if indent > 0:
middle = self.multiline_indent(middle, indent)
return result + middle + "\n```\n"
class Section(MultiItem):
"""Markdown section."""
format_type:str = "Section"
data:List[Markdown]
header:Header
name:str
indent:int
addable:bool = True
def __init__(self, name:str, data:Optional[List[Markdown]]=None, indent:int=2):
self.header = Header(name, indent)
self.name = name
self.data = data if data is not None else []
self.indent = indent
def build(self, indent:int=0)->str:
result = self.header.build(indent) + "\n" + "".join([item.build(indent) for item in self.data])
result = result.rstrip("\n") + "\n\n"
return result
def __add__(self, other:Union[str, Markdown]):
if isinstance(other, str):
other = Paragraph(other)
self.data.append(other)
return self
def __iadd__(self, other:Union[str, Markdown]):
return self + other
def __len__(self)->int:
return len(self.data)
def get_link(self)->SectionLink:
return SectionLink(self.name)
class TableOfContents(Section):
"""Markdown table of contents."""
format_type:str = "TableOfContents"
data:List[Markdown]
def __init__(self, data:List[Tuple[SectionLink, int]]=None):
self.data = [OrderedList()]
self.header = Header("Table of Contents", 2)
self.name = "Table of Contents"
self.indent = 2
if data is not None:
for item in data:
self.add(*item)
def add(self, link:SectionLink, indent:int)->None:
if link.data[0] == "Table of Contents":
return
indent = max(indent, 2) - 2
self.data[0] += OrderedListItem(link, indent)
def link(self, section:Section)->None:
self.add(section.get_link(), section.indent)
class MarkdownTable: pass # Table container / parent
class MarkdownTableSeries: pass # Base class for table rows and columns
class MarkdownTableRow: pass # Table row (buildable)
class MarkdownTableColumn: pass # Table column (data only)
class MarkdownTableCell: pass # Table cell
class MarkdownTable: # partial definition
columns:List[MarkdownTableColumn]
rows:List[MarkdownTableRow]
data:List[MarkdownTableCell]
def get_columns(self)->List[MarkdownTableColumn]: pass
def get_rows(self)->List[MarkdownTableRow]: pass
def column(self, index:int)->MarkdownTableColumn: pass
def row(self, index:int)->MarkdownTableRow: pass
def cell(self, row:int, col:int)->MarkdownTableCell: pass
def calculate_max_widths(self, total_max_width:int)->List[int]: pass
pass
SeriesIndexType = Union[int, str, slice]
class MarkdownTableSeries(ABC):
data:List[MarkdownTableCell]
parent:MarkdownTable
index:int
axis:Literal["row", "column"]
@abstractmethod
def width(self)->int: pass
def add(self, cell:MarkdownTableCell)->None:
self.data.append(cell)
def __index__(self, index:SeriesIndexType)->Union[int, slice]:
if isinstance(index, str):
if self.axis == "row":
return self.parent.columns.index(index)
raise ValueError(f"Cannot index column by column name: {index}")
elif isinstance(index, slice):
args = [index.start, index.stop, index.step]
args = [self.__index__(arg) if arg is not None else arg for arg in args]
return slice(*args)
else:
return index
def __getitem__(self, index:SeriesIndexType)->Listable[MarkdownTableCell]:
index = self.__index__(index)
return self.data[index]
def __setitem__(self, index:SeriesIndexType, data:Listable[MarkdownTableCell])->None:
index = self.__index__(index)
if isinstance(index, slice):
if isinstance(data, list):
self.data[index] = data
else:
self.data[index] = [data] * len(index)
else:
if isinstance(data, list):
raise ValueError("Cannot set single cell to multiple cells.")
self.data[index] = data
def __len__(self)->int:
return len(self.data)
class MarkdownTableCell:
"""
Markdown table cell.
Can calculate its own width and height based on the data it contains.
"""
data:Markdown
rownum:Optional[int]
colnum:Optional[int]
def __init__(self, data:Any, rownum:Optional[int]=None, colnum:Optional[int]=None):
if isinstance(data, str):
self.data = Text([data])
elif isinstance(data, Markdown):
self.data = data
else:
self.data = Text([str(data)])
self.rownum = rownum
self.colnum = colnum
def width(self)->int:
if isinstance(self.data, str):
return len(self.data)
return width(self.data)
def height(self, maxwidth:Optional[int]=None)->int:
if isinstance(self.data, str):
return 1
return self.data.__height__(maxwidth)
def __str__(self)->str:
return str(self.data)
def __repr__(self)->str:
return f"MarkdownTableCell({self.data})"
def set_rownum(self, rownum:int)->None:
self.rownum = rownum
def set_colnum(self, colnum:int)->None:
self.colnum = colnum
def __len__(self)->int:
return self.width()
def build(self, desiredwidth:int, desiredheight:int)->str:
result = ""
if isinstance(self.data, str):
result = self.data
else:
result = self.data.build()
lines = result.split("\n")
if len(lines) < desiredheight:
lines += [""] * (desiredheight - len(lines))
result = "\n".join([line.ljust(desiredwidth) for line in lines])
return result
def data_len(self)->int:
if isinstance(self.data, str):
return len(self.data)
if isinstance(self.data, Markdown):
return self.data.size()
return len(str(self.data))
class MarkdownTableRow(MarkdownTableSeries):
"""
Markdown table row.
"""
data:List[MarkdownTableCell]
def __init__(self, data:Optional[List[MarkdownTableCell]] = None, parent:MarkdownTable = None, index:Optional[int] = None):
if parent is None:
raise ValueError("Parent table must be provided.")
if index is None:
index = len(parent.rows)
if data is None:
data = []
self.data = data
self.parent = parent
self.index = index
self.axis = "row"
def width(self, maxwidth:Optional[int]=None)->int:
return sum([min(cell.width(), maxwidth) for cell in self.data])
def height(self, maxwidth:Optional[int]=None)->int:
return max([cell.height(maxwidth) for cell in self.data])
def __len__(self)->int:
return self.width()
def build(self, desired_widths:List[int], divider:str = "|")->str:
result_lines = []
for i, cell in enumerate(self.data):
desired_width = desired_widths[i]
cell_str = cell.build(desired_width, self.height())
cell_lines = cell_str.split("\n")
for j, line in enumerate(cell_lines):
if j >= len(result_lines):
result_lines.append([])
append = f"{divider} {line}"
if i > 0:
append = f" {append}"
result_lines[j].append(append)
for i in range(len(result_lines)):
result_lines[i] = "".join(result_lines[i]) + " |\n"
return "".join(result_lines)
class MarkdownTableColumn(MarkdownTableSeries):
"""
Markdown table column.
"""
data:List[MarkdownTableCell]
def __init__(self, data:Optional[List[MarkdownTableCell]] = None, parent:MarkdownTable = None, index:Optional[int] = None):
if parent is None:
raise ValueError("Parent table must be provided.")
if index is None:
index = len(parent.columns)
if data is None:
data = []
self.data = data
self.parent = parent
self.index = index
self.axis = "column"
def width(self)->int:
return max([cell.width() for cell in self.data])
def height(self, maxwidth:Optional[int]=None)->int:
return sum([cell.height(maxwidth) for cell in self.data])
def __len__(self)->int:
return self.width()
def build(self, desired_width:int, desired_height:int, divider:str = "|")->str:
"""Column build won't be used outside of debugging. The row build method handles everything."""
result = ""
for cell in self.data:
result += cell.build(desired_width, desired_height) + "\n"
return result
def weight(self)->int:
weight = 0
for cell in self.data:
weight += cell.data_len()
return weight
class MarkdownHeaderCell(MarkdownTableCell):
"""
Markdown table header cell.
Identical to the standard cell, but a bottom border is added.
"""
def build(self, desiredwidth:int, desiredheight:int)->str:
result = super().build(desiredwidth, desiredheight)
result += "\n"
result += "-" * desiredwidth
return result
class MarkdownHeaderRow(MarkdownTableRow):
"""
Markdown table header row.
"""
data:List[MarkdownHeaderCell]
def __init__(self, data:List[MarkdownHeaderCell], parent:MarkdownTable):
super().__init__(data, parent, 0)
TableIndexerType = Union[int, tuple["TableIndexerType", "TableIndexerType"], slice, str]
class MarkdownTable(Markdown):
"""
Markdown table.
"""
column_names:List[str]
header_row:MarkdownHeaderRow
columns:List[MarkdownTableColumn]
rows:List[MarkdownTableRow]
data:List[MarkdownTableCell]
maxwidth:int
def __init__(self, maxwidth:int = 40, column_names:List[str] = [], data:Optional[List[List[Union[str, Markdown]]]]=None):
self.column_names = column_names
self.maxwidth = maxwidth
self.columns = []
self.rows = []
self.header_row = MarkdownHeaderRow([MarkdownHeaderCell(name) for name in column_names], self)
for i, name in enumerate(column_names):
self.columns.append(MarkdownTableColumn(parent=self))
self.columns[i].add(self.header_row.data[i])
self.rows.append(self.header_row)
self.data = []
if data is not None:
for i, row in enumerate(data):
self.add_row(row, i + 1)
def get_columns(self)->List[MarkdownTableColumn]:
return self.columns
def get_rows(self)->List[MarkdownTableRow]:
return self.rows
def column(self, index:Union[str, int])->MarkdownTableColumn:
if isinstance(index, str):
return self.columns[self.column_names.index(index)]
return self.columns[index]
def row(self, index:int)->MarkdownTableRow:
return self.rows[index]
def __index__(self, index:TableIndexerType)->Union[int, slice, tuple]:
if isinstance(index, str):
return self.column_names.index(index)
elif isinstance(index, tuple):
col = self.__index__(index[0])
row = self.columns[0].__index__(index[1])
return (col, row)
elif isinstance(index, slice):
return self.header_row.__index__(index)
return index
def __getitem__(self, index:TableIndexerType)->Listable[Union[MarkdownTableCell, MarkdownTableRow, MarkdownTableColumn]]:
index = self.__index__(index)
# [:, :] -> List[MarkdownTableCell]
# [:] -> List[MarkdownTableColumn]
# [:, 0] -> MarkdownTableRow
# [0, :] -> MarkdownTableColumn
# [0, 1:] -> List[MarkdownTableCell]
# [1:, 0] -> List[MarkdownTableRow]
# [1:, 1:] -> List[List[MarkdownTableCell]]
if isinstance(index, slice):
# [:] -> List[MarkdownTableColumn]
return self.columns[index]
elif isinstance(index, tuple):
# [0|:, 0|:] -> ?
if isinstance(index[0], int):
# [0, 0|:] -> Listable[MarkdownTableCell]
col = self.columns[index[0]]
return col[index[1]]
# [:, 0|:] -> Listable[Listable[MarkdownTableCell]]
cols = self.columns[index[0]]
result = []
for col in cols:
result.append(col[index[1]])
return result
elif isinstance(index, int):
# [0] -> MarkdownTableColumn
return self.columns[index]
else:
raise IndexError(f"Unknown index type: {index}(type={type(index)})")
def __setitem__(self, index:TableIndexerType, data:Listable[Union[MarkdownTableCell, MarkdownTableRow, MarkdownTableColumn]])->None:
index = self.__index__(index)
if isinstance(index, slice):
if isinstance(data, list):
self.columns[index] = data
else:
self.columns[index] = [data] * len(index)
elif isinstance(index, tuple):
if isinstance(data, list):
for i, col in enumerate(self.columns[index[0]]):
col[index[1]] = data[i]
else:
self.columns[index[0]][index[1]] = data
elif isinstance(index, int):
self.columns[index] = data
else:
raise IndexError(f"Unknown index type: {index}(type={type(index)})")
def calculate_max_widths(self, total_max_width:int)->List[int]:
expected_widths = [max([len(name)] + [self.columns[i].width()]) for i, name in enumerate(self.column_names)]
expected_max_width = sum(expected_widths)
if expected_max_width <= total_max_width:
return expected_widths
weights = [col.weight() for col in self.columns]
total_weight = sum(weights)
ratio = total_max_width / expected_max_width
expected_avg_width = total_max_width // len(self.column_names)
expected_widths = [int(expected_avg_width * weight / total_weight) for weight in weights]
return expected_widths
def build(self, indent:int=0)->str:
maxwidth = max(self.maxwidth, 20 * len(self.column_names))
widths = self.calculate_max_widths(maxwidth)
# result = self.header_row.build(widths)
result = ""
for row in self.rows:
result += row.build(widths)
return result
def __len__(self)->int:
return self.header_row.width()
def __new_row(self)->MarkdownTableRow:
result = MarkdownTableRow(parent=self)
self.rows.append(result)
return result
def __new_column(self, name:str)->MarkdownTableColumn:
result = MarkdownTableColumn(parent=self)
self.columns.append(result)
self.column_names.append(name)
return result
def add_cell(self, data:Union[str, Markdown], row:int, col:int)->None:
maxrow = len(self.rows)
maxcol = len(self.columns)
targetrow = None
if row < maxrow:
targetrow = self.rows[row]
elif row == maxrow:
targetrow = self.__new_row()
else:
raise IndexError(f"Row index out of range: {row} (max={maxrow}).\nCell islands are not supported.")
if col >= maxcol:
raise IndexError(f"No corresponding column for index: {col} (max={maxcol}).")
targetcol = self.columns[col]
cell = MarkdownTableCell(data, row, col)
targetrow.add(cell)
targetcol.add(cell)
self.data.append(cell)
def add_row(self, data:List[Union[str, Markdown]])->None:
row_index = len(self.rows)
for i, item in enumerate(data):
self.add_cell(item, row_index, i)
def add_column(self, name:str, data:List[Union[str, Markdown]])->None:
col_index = len(self.columns)
col = self.__new_column(name)
for i, item in enumerate(data):
self.add_cell(item, i, col_index)
def add(self, data:List[List[Union[str, Markdown]]])->None:
for row in data:
self.add_row(row)
def __width__(self) -> int:
return min(self.maxwidth, sum(col.width() for col in self.columns))
def __height__(self, maxwidth:Optional[int] = None) -> int:
return sum(row.__height__(maxwidth) for row in self.rows)
class MarkdownFile:
titleHeader:Optional[Header]
sections:List[str]
content:List[Section]
table_of_contents:TableOfContents
titleHeader:Optional[Header]
def __init__(self, sections:Optional[List[str]] = None):
self.sections = sections if sections is not None else []
self.content = []
self.table_of_contents = TableOfContents([])
self.titleHeader = None
def add_section(self, section:Section):
self.content.append(section)
self.table_of_contents.link(section)
if section.name not in self.sections:
self.sections.append(section.name)
def add(self, section: Union[Section, str, List[Section]]):
if isinstance(section, str):
if section == "Table of Contents":
return self.add_section(self.table_of_contents)
raise ValueError(f"Invalid section: {section}")
elif isinstance(section, Header):
if len(self.content) > 0:
section = Section(name=section.data, indent=section.indent)
else:
self.titleHeader = section
return
elif isinstance(section, list):
for sec in section:
self.add(sec)
return
self.add_section(section)
def build(self)->str:
result = ""
if self.titleHeader is not None:
result += self.titleHeader.build() + "\n"
for section in self.content:
# print(f"Building section: {section.name}, {section.data}")
section_str = section.build()
result += section_str
result = result.rstrip("\n") + "\n"
return result
def to_file(self, path:Path):
path.write_text(self.build())
install_md_path = this_folder/"INSTALL.md"
readme_path = this_folder/"README.md"
readme_sections = [
"Project Title",
"Description",
"Table of Contents",
"Dependencies",
"Installation",
"Usage",
"Testing",
"Known Issues",
"Getting Help",
"Getting Involved",
"Open Source Licensing Info",
"Credits and References"
]
## Links
ngen_address = "https://github.com/NOAA-OWP/ngen"
ngiab_cloudinfra_address = "https://github.com/CIROH-UA/NGIAB-CloudInfra"
alabama_water_institute_address = "https://github.com/AlabamaWaterInstitute/"
bmi_reference_address = "https://github.com/NOAA-OWP/ngen/blob/master/doc/BMIconventions.md"
def author_link()->Link:
return Link((author_name, author_github_link))
def ngen_link()->Link:
return Link(("Ngen", ngen_address))
def nextgen_link()->Link:
return Link(("Nextgen", ngen_address))
def ngiab_cloudinfra_link()->Link:
return Link(("NGIAB-CloudInfra", ngiab_cloudinfra_address))
def alabama_water_institute_link()->Link:
return Link(("Alabama Water Institute", alabama_water_institute_address))
def bmi_reference_link()->Link:
return Link(("BMI", bmi_reference_address))
## README.md sections
def build_project_title()->Header:
return Header(project_name, 1)
def build_description(indent:int = 2)->Section:
desc = Section("Description")
# para = Paragraph("This project is a Python-based Nextgen-BMI model that implements unit hydrograph functionality.")
para = "This project is a Python-based"
para += " " + bmi_reference_link() + " model that implements unit hydrograph functionality"
para += " for use with " + nextgen_link() + "."