-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmakefile
1486 lines (1197 loc) · 44.5 KB
/
makefile
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
#|==================================================================|
#| python project makefile template |
#| originally by Michael Ivanitskiy ([email protected]) |
#| https://github.com/mivanit/python-project-makefile-template |
#| version: v0.2.1 |
#| license: https://creativecommons.org/licenses/by-sa/4.0/ |
#| modifications from the original should be denoted with `~~~~~` |
#| as this makes it easier to find edits when updating makefile |
#|==================================================================|
###### ######## ######
## ## ## ## ##
## ## ##
## ###### ## ####
## ## ## ##
## ## ## ## ##
###### ## ######
# ==================================================
# configuration & variables
# ==================================================
# it assumes that the source is in a directory named the same as the package name
# this also gets passed to some other places
PACKAGE_NAME := muutils
# for checking you are on the right branch when publishing
PUBLISH_BRANCH := main
# where to put docs
# if you change this, you must also change pyproject.toml:tool.makefile.docs.output_dir to match
DOCS_DIR := docs
# where the tests are, for pytest
TESTS_DIR := tests
# tests temp directory to clean up. will remove this in `make clean`
TESTS_TEMP_DIR := $(TESTS_DIR)/_temp/
# probably don't change these:
# --------------------------------------------------
# where the pyproject.toml file is. no idea why you would change this but just in case
PYPROJECT := pyproject.toml
# dir to store various configuration files
# use of `.meta/` inspired by https://news.ycombinator.com/item?id=36472613
META_DIR := .meta
# requirements.txt files for base package, all extras, dev, and all
REQUIREMENTS_DIR := $(META_DIR)/requirements
# local files (don't push this to git!)
LOCAL_DIR := $(META_DIR)/local
# will print this token when publishing. make sure not to commit this file!!!
PYPI_TOKEN_FILE := $(LOCAL_DIR)/.pypi-token
# version files
VERSIONS_DIR := $(META_DIR)/versions
# the last version that was auto-uploaded. will use this to create a commit log for version tag
# see `gen-commit-log` target
LAST_VERSION_FILE := $(VERSIONS_DIR)/.lastversion
# current version (writing to file needed due to shell escaping issues)
VERSION_FILE := $(VERSIONS_DIR)/.version
# base python to use. Will add `uv run` in front of this if `RUN_GLOBAL` is not set to 1
PYTHON_BASE := python
# where the commit log will be stored
COMMIT_LOG_FILE := $(LOCAL_DIR)/.commit_log
# pandoc commands (for docs)
PANDOC ?= pandoc
# where to put the coverage reports
# note that this will be published with the docs!
# modify the `docs` targets and `.gitignore` if you don't want that
COVERAGE_REPORTS_DIR := $(DOCS_DIR)/coverage
# this stuff in the docs will be kept
# in addition to anything specified in `pyproject.toml:tool.makefile.docs.no_clean`
DOCS_RESOURCES_DIR := $(DOCS_DIR)/resources
# location of the make docs script
MAKE_DOCS_SCRIPT_PATH := $(DOCS_RESOURCES_DIR)/make_docs.py
# version vars - extracted automatically from `pyproject.toml`, `$(LAST_VERSION_FILE)`, and $(PYTHON)
# --------------------------------------------------
# assuming your `pyproject.toml` has a line that looks like `version = "0.0.1"`, `gen-version-info` will extract this
PROJ_VERSION := NULL
# `gen-version-info` will read the last version from `$(LAST_VERSION_FILE)`, or `NULL` if it doesn't exist
LAST_VERSION := NULL
# get the python version, now that we have picked the python command
PYTHON_VERSION := NULL
# ==================================================
# reading command line options
# ==================================================
# for formatting or something, we might want to run python without uv
# RUN_GLOBAL=1 to use global `PYTHON_BASE` instead of `uv run $(PYTHON_BASE)`
RUN_GLOBAL ?= 0
ifeq ($(RUN_GLOBAL),0)
PYTHON = uv run $(PYTHON_BASE)
else
PYTHON = $(PYTHON_BASE)
endif
# if you want different behavior for different python versions
# --------------------------------------------------
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# compatibility mode for python <3.10
# loose typing, allow warnings for python <3.10
# --------------------------------------------------
TYPECHECK_ARGS ?=
# COMPATIBILITY_MODE: whether to run in compatibility mode for python <3.10
COMPATIBILITY_MODE := $(shell $(PYTHON) -c "import sys; print(1 if sys.version_info < (3, 10) else 0)")
# compatibility mode for python <3.10
# --------------------------------------------------
# whether to run pytest with warnings as errors
WARN_STRICT ?= 0
ifneq ($(WARN_STRICT), 0)
PYTEST_OPTIONS += -W error
endif
# Update the PYTEST_OPTIONS to include the conditional ignore option
ifeq ($(COMPATIBILITY_MODE), 1)
JUNK := $(info !!! WARNING !!!: Detected python version less than 3.10, some behavior will be different)
PYTEST_OPTIONS += --ignore=tests/unit/validate_type/
TYPECHECK_ARGS += --disable-error-code misc --disable-error-code syntax --disable-error-code import-not-found
endif
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# options we might want to pass to pytest
# --------------------------------------------------
# base options for pytest, will be appended to if `COV` or `VERBOSE` are 1.
# user can also set this when running make to add more options
PYTEST_OPTIONS ?=
# set to `1` to run pytest with `--cov=.` to get coverage reports in a `.coverage` file
COV ?= 1
# set to `1` to run pytest with `--verbose`
VERBOSE ?= 0
ifeq ($(VERBOSE),1)
PYTEST_OPTIONS += --verbose
endif
ifeq ($(COV),1)
PYTEST_OPTIONS += --cov=.
endif
# ==================================================
# default target (help)
# ==================================================
# first/default target is help
.PHONY: default
default: help
###### ###### ######## #### ######## ######## ######
## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ##
###### ## ######## ## ######## ## ######
## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ##
###### ###### ## ## #### ## ## ######
# ==================================================
# python scripts we want to use inside the makefile
# when developing, these are populated by `scripts/assemble_make.py`
# ==================================================
# create commands for exporting requirements as specified in `pyproject.toml:tool.uv-exports.exports`
define SCRIPT_EXPORT_REQUIREMENTS
import sys
import warnings
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
from pathlib import Path
from typing import Any, Dict, Union, List
from functools import reduce
TOOL_PATH: str = "tool.makefile.uv-exports"
def deep_get(d: dict, path: str, default: Any = None, sep: str = ".") -> Any:
return reduce(
lambda x, y: x.get(y, default) if isinstance(x, dict) else default, # function
path.split(sep) if isinstance(path, str) else path, # sequence
d, # initial
)
def export_configuration(
export: dict,
all_groups: List[str],
all_extras: List[str],
export_opts: dict,
output_dir: Path,
):
# get name and validate
name = export.get("name")
if not name or not name.isalnum():
warnings.warn(
f"Export configuration missing valid 'name' field {export}",
)
return
# get other options with default fallbacks
filename: str = export.get("filename") or f"requirements-{name}.txt"
groups: Union[List[str], bool, None] = export.get("groups", None)
extras: Union[List[str], bool] = export.get("extras", [])
options: List[str] = export.get("options", [])
# init command
cmd: List[str] = ["uv", "export"] + export_opts.get("args", [])
# handle groups
if groups is not None:
groups_list: List[str] = []
if isinstance(groups, bool):
if groups:
groups_list = all_groups.copy()
else:
groups_list = groups
for group in all_groups:
if group in groups_list:
cmd.extend(["--group", group])
else:
cmd.extend(["--no-group", group])
# handle extras
extras_list: List[str] = []
if isinstance(extras, bool):
if extras:
extras_list = all_extras.copy()
else:
extras_list = extras
for extra in extras_list:
cmd.extend(["--extra", extra])
# add extra options
cmd.extend(options)
# assemble the command and print to console -- makefile will run it
output_path = output_dir / filename
print(f"{' '.join(cmd)} > {output_path.as_posix()}")
def main(
pyproject_path: Path,
output_dir: Path,
):
# read pyproject.toml
with open(pyproject_path, "rb") as f:
pyproject_data: dict = tomllib.load(f)
# all available groups
all_groups: List[str] = list(pyproject_data.get("dependency-groups", {}).keys())
all_extras: List[str] = list(
deep_get(pyproject_data, "project.optional-dependencies", {}).keys()
)
# options for exporting
export_opts: dict = deep_get(pyproject_data, TOOL_PATH, {})
# what are we exporting?
exports: List[Dict[str, Any]] = export_opts.get("exports", [])
if not exports:
exports = [{"name": "all", "groups": [], "extras": [], "options": []}]
# export each configuration
for export in exports:
export_configuration(
export=export,
all_groups=all_groups,
all_extras=all_extras,
export_opts=export_opts,
output_dir=output_dir,
)
if __name__ == "__main__":
main(
pyproject_path=Path(sys.argv[1]),
output_dir=Path(sys.argv[2]),
)
endef
export SCRIPT_EXPORT_REQUIREMENTS
# get the version from `pyproject.toml:project.version`
define SCRIPT_GET_VERSION
import sys
try:
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
pyproject_path: str = sys.argv[1].strip()
with open(pyproject_path, "rb") as f:
pyproject_data: dict = tomllib.load(f)
print("v" + pyproject_data["project"]["version"], end="")
except Exception:
print("NULL", end="")
sys.exit(1)
endef
export SCRIPT_GET_VERSION
# get the commit log since the last version from `$(LAST_VERSION_FILE)`
define SCRIPT_GET_COMMIT_LOG
import subprocess
import sys
from typing import List
def main(
last_version: str,
commit_log_file: str,
):
if last_version == "NULL":
print("!!! ERROR !!!", file=sys.stderr)
print("LAST_VERSION is NULL, can't get commit log!", file=sys.stderr)
sys.exit(1)
try:
log_cmd: List[str] = [
"git",
"log",
f"{last_version}..HEAD",
"--pretty=format:- %s (%h)",
]
commits: List[str] = (
subprocess.check_output(log_cmd).decode("utf-8").strip().split("\n")
)
with open(commit_log_file, "w") as f:
f.write("\n".join(reversed(commits)))
except subprocess.CalledProcessError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main(
last_version=sys.argv[1].strip(),
commit_log_file=sys.argv[2].strip(),
)
endef
export SCRIPT_GET_COMMIT_LOG
# get cuda information and whether torch sees it
define SCRIPT_CHECK_TORCH
import os
import sys
import re
import subprocess
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
def print_info_dict(
info: Dict[str, Union[Any, Dict[str, Any]]],
indent: str = " ",
level: int = 1,
) -> None:
indent_str: str = indent * level
longest_key_len: int = max(map(len, info.keys()))
for key, value in info.items():
if isinstance(value, dict):
print(f"{indent_str}{key:<{longest_key_len}}:")
print_info_dict(value, indent, level + 1)
else:
print(f"{indent_str}{key:<{longest_key_len}} = {value}")
def get_nvcc_info() -> Dict[str, str]:
# Run the nvcc command.
try:
result: subprocess.CompletedProcess[str] = subprocess.run(
["nvcc", "--version"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
except Exception as e:
return {"Failed to run 'nvcc --version'": str(e)}
output: str = result.stdout
lines: List[str] = [line.strip() for line in output.splitlines() if line.strip()]
# Ensure there are exactly 5 lines in the output.
assert len(lines) == 5, (
f"Expected exactly 5 lines from nvcc --version, got {len(lines)} lines:\n{output}"
)
# Compile shared regex for release info.
release_regex: re.Pattern = re.compile(
r"Cuda compilation tools,\s*release\s*([^,]+),\s*(V.+)"
)
# Define a mapping for each desired field:
# key -> (line index, regex pattern, group index, transformation function)
patterns: Dict[str, Tuple[int, re.Pattern, int, Callable[[str], str]]] = {
"build_time": (
2,
re.compile(r"Built on (.+)"),
1,
lambda s: s.replace("_", " "),
),
"release": (3, release_regex, 1, str.strip),
"release_V": (3, release_regex, 2, str.strip),
"build": (4, re.compile(r"Build (.+)"), 1, str.strip),
}
info: Dict[str, str] = {}
for key, (line_index, pattern, group_index, transform) in patterns.items():
match: Optional[re.Match] = pattern.search(lines[line_index])
if not match:
raise ValueError(
f"Unable to parse {key} from nvcc output: {lines[line_index]}"
)
info[key] = transform(match.group(group_index))
info["release_short"] = info["release"].replace(".", "").strip()
return info
def get_torch_info() -> Tuple[List[Exception], Dict[str, Any]]:
exceptions: List[Exception] = []
info: Dict[str, Any] = {}
try:
import torch
info["torch.__version__"] = torch.__version__
info["torch.cuda.is_available()"] = torch.cuda.is_available()
if torch.cuda.is_available():
info["torch.version.cuda"] = torch.version.cuda
info["torch.cuda.device_count()"] = torch.cuda.device_count()
if torch.cuda.device_count() > 0:
info["torch.cuda.current_device()"] = torch.cuda.current_device()
n_devices: int = torch.cuda.device_count()
info["n_devices"] = n_devices
for current_device in range(n_devices):
try:
current_device_info: Dict[str, Union[str, int]] = {}
dev_prop = torch.cuda.get_device_properties(
torch.device(f"cuda:{current_device}")
)
current_device_info["name"] = dev_prop.name
current_device_info["version"] = (
f"{dev_prop.major}.{dev_prop.minor}"
)
current_device_info["total_memory"] = (
f"{dev_prop.total_memory} ({dev_prop.total_memory:.1e})"
)
current_device_info["multi_processor_count"] = (
dev_prop.multi_processor_count
)
current_device_info["is_integrated"] = dev_prop.is_integrated
current_device_info["is_multi_gpu_board"] = (
dev_prop.is_multi_gpu_board
)
info[f"device cuda:{current_device}"] = current_device_info
except Exception as e:
exceptions.append(e)
else:
raise Exception(
f"{torch.cuda.device_count() = } devices detected, invalid"
)
else:
raise Exception(
f"CUDA is NOT available in torch: {torch.cuda.is_available() =}"
)
except Exception as e:
exceptions.append(e)
return exceptions, info
if __name__ == "__main__":
print(f"python: {sys.version}")
print_info_dict(
{
"python executable path: sys.executable": str(sys.executable),
"sys.platform": sys.platform,
"current working directory: os.getcwd()": os.getcwd(),
"Host name: os.name": os.name,
"CPU count: os.cpu_count()": str(os.cpu_count()),
}
)
nvcc_info: Dict[str, Any] = get_nvcc_info()
print("nvcc:")
print_info_dict(nvcc_info)
torch_exceptions, torch_info = get_torch_info()
print("torch:")
print_info_dict(torch_info)
if torch_exceptions:
print("torch_exceptions:")
for e in torch_exceptions:
print(f" {e}")
endef
export SCRIPT_CHECK_TORCH
# get todo's from the code
define SCRIPT_GET_TODOS
from __future__ import annotations
import urllib.parse
import argparse
import fnmatch
from dataclasses import asdict, dataclass, field
import json
from pathlib import Path
from typing import Any, Dict, List, Union
from functools import reduce
import warnings
from jinja2 import Template
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
TOOL_PATH: str = "tool.makefile.inline-todo"
def deep_get(d: dict, path: str, default: Any = None, sep: str = ".") -> Any:
return reduce(
lambda x, y: x.get(y, default) if isinstance(x, dict) else default, # function
path.split(sep) if isinstance(path, str) else path, # sequence
d, # initial
)
TEMPLATE_MD: str = """\
# Inline TODOs
{% for tag, file_map in grouped|dictsort %}
# {{ tag }}
{% for filepath, item_list in file_map|dictsort %}
## [`{{ filepath }}`](/{{ filepath }})
{% for itm in item_list %}
- {{ itm.stripped_title }}
local link: [`/{{ filepath }}#{{ itm.line_num }}`](/{{ filepath }}#{{ itm.line_num }})
| view on GitHub: [{{ itm.file }}#L{{ itm.line_num }}]({{ itm.code_url | safe }})
| [Make Issue]({{ itm.issue_url | safe }})
{% if itm.context %}
```{{ itm.file_lang }}
{{ itm.context.strip() }}
```
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
"""
TEMPLATE_ISSUE: str = """\
# source
[`{file}#L{line_num}`]({code_url})
# context
```{file_lang}
{context}
```
"""
@dataclass
class Config:
"""Configuration for the inline-todo scraper"""
search_dir: Path = Path(".")
out_file: Path = Path("docs/todo-inline.md")
tags: List[str] = field(
default_factory=lambda: ["CRIT", "TODO", "FIXME", "HACK", "BUG"]
)
extensions: List[str] = field(default_factory=lambda: ["py", "md"])
exclude: List[str] = field(default_factory=lambda: ["docs/**", ".venv/**"])
context_lines: int = 2
tag_label_map: Dict[str, str] = field(
default_factory=lambda: {
"CRIT": "bug",
"TODO": "enhancement",
"FIXME": "bug",
"BUG": "bug",
"HACK": "enhancement",
}
)
extension_lang_map: Dict[str, str] = field(
default_factory=lambda: {
"py": "python",
"md": "markdown",
"html": "html",
"css": "css",
"js": "javascript",
}
)
template_md: str = TEMPLATE_MD
# template for the output markdown file
template_issue: str = TEMPLATE_ISSUE
# template for the issue creation
template_html_source: Path = Path("docs/resources/templates/todo-template.html")
# template source for the output html file (interactive table)
@property
def template_html(self) -> str:
return self.template_html_source.read_text(encoding="utf-8")
template_code_url_: str = "{repo_url}/blob/{branch}/{file}#L{line_num}"
# template for the code url
@property
def template_code_url(self) -> str:
return self.template_code_url_.replace("{repo_url}", self.repo_url).replace(
"{branch}", self.branch
)
repo_url: str = "UNKNOWN"
# for the issue creation url
branch: str = "main"
# branch for links to files on github
@classmethod
def read(cls, config_file: Path) -> Config:
output: Config
if config_file.is_file():
# read file and load if present
with config_file.open("rb") as f:
data: Dict[str, Any] = tomllib.load(f)
# try to get the repo url
repo_url: str = "UNKNOWN"
try:
urls: Dict[str, str] = {
k.lower(): v for k, v in data["project"]["urls"].items()
}
if "repository" in urls:
repo_url = urls["repository"]
if "github" in urls:
repo_url = urls["github"]
except Exception as e:
warnings.warn(
f"No repository URL found in pyproject.toml, 'make issue' links will not work.\n{e}"
)
# load the inline-todo config if present
data_inline_todo: Dict[str, Any] = deep_get(
d=data, path=TOOL_PATH, default={}
)
if "repo_url" not in data_inline_todo:
data_inline_todo["repo_url"] = repo_url
output = cls.load(data_inline_todo)
else:
# return default otherwise
output = cls()
return output
@classmethod
def load(cls, data: dict) -> Config:
data = {
k: Path(v) if k in {"search_dir", "out_file", "template_html_source"} else v
for k, v in data.items()
}
return cls(**data)
CFG: Config = Config()
# this is messy, but we use a global config so we can get `TodoItem().issue_url` to work
@dataclass
class TodoItem:
"""Holds one todo occurrence"""
tag: str
file: str
line_num: int
content: str
context: str = ""
def serialize(self) -> Dict[str, Union[str, int]]:
return {
**asdict(self),
"issue_url": self.issue_url,
"file_lang": self.file_lang,
"stripped_title": self.stripped_title,
"code_url": self.code_url,
}
@property
def code_url(self) -> str:
"""Returns a URL to the code on GitHub"""
return CFG.template_code_url.format(
file=self.file,
line_num=self.line_num,
)
@property
def stripped_title(self) -> str:
"""Returns the title of the issue, stripped of the tag"""
return self.content.split(self.tag, 1)[-1].lstrip(":").strip()
@property
def issue_url(self) -> str:
"""Constructs a GitHub issue creation URL for a given TodoItem."""
# title
title: str = self.stripped_title
if not title:
title = "Issue from inline todo"
# body
body: str = CFG.template_issue.format(
file=self.file,
line_num=self.line_num,
context=self.context,
code_url=self.code_url,
file_lang=self.file_lang,
).strip()
# labels
label: str = CFG.tag_label_map.get(self.tag, self.tag)
# assemble url
query: Dict[str, str] = dict(title=title, body=body, labels=label)
query_string: str = urllib.parse.urlencode(query, quote_via=urllib.parse.quote)
return f"{CFG.repo_url}/issues/new?{query_string}"
@property
def file_lang(self) -> str:
"""Returns the language for the file extension"""
ext: str = Path(self.file).suffix.lstrip(".")
return CFG.extension_lang_map.get(ext, ext)
def scrape_file(
file_path: Path,
tags: List[str],
context_lines: int,
) -> List[TodoItem]:
"""Scrapes a file for lines containing any of the specified tags"""
items: List[TodoItem] = []
if not file_path.is_file():
return items
lines: List[str] = file_path.read_text(encoding="utf-8").splitlines(True)
for i, line in enumerate(lines):
for tag in tags:
if tag in line[:200]:
start: int = max(0, i - context_lines)
end: int = min(len(lines), i + context_lines + 1)
snippet: str = "".join(lines[start:end])
items.append(
TodoItem(
tag=tag,
file=file_path.as_posix(),
line_num=i + 1,
content=line.strip("\n"),
context=snippet.strip("\n"),
)
)
break
return items
def collect_files(
search_dir: Path,
extensions: List[str],
exclude: List[str],
) -> List[Path]:
"""Recursively collects all files with specified extensions, excluding matches via globs"""
results: List[Path] = []
for ext in extensions:
results.extend(search_dir.rglob(f"*.{ext}"))
filtered: List[Path] = []
for f in results:
# Skip if it matches any exclude glob
if not any(fnmatch.fnmatch(f.as_posix(), pattern) for pattern in exclude):
filtered.append(f)
return filtered
def group_items_by_tag_and_file(
items: List[TodoItem],
) -> Dict[str, Dict[str, List[TodoItem]]]:
"""Groups items by tag, then by file"""
grouped: Dict[str, Dict[str, List[TodoItem]]] = {}
for itm in items:
grouped.setdefault(itm.tag, {}).setdefault(itm.file, []).append(itm)
for tag_dict in grouped.values():
for file_list in tag_dict.values():
file_list.sort(key=lambda x: x.line_num)
return grouped
def main(config_file: Path) -> None:
global CFG
# read configuration
cfg: Config = Config.read(config_file)
CFG = cfg
# get data
files: List[Path] = collect_files(cfg.search_dir, cfg.extensions, cfg.exclude)
all_items: List[TodoItem] = []
n_files: int = len(files)
for i, fpath in enumerate(files):
print(f"Scraping {i + 1:>2}/{n_files:>2}: {fpath.as_posix():<60}", end="\r")
all_items.extend(scrape_file(fpath, cfg.tags, cfg.context_lines))
# create dir
cfg.out_file.parent.mkdir(parents=True, exist_ok=True)
# write raw to jsonl
with open(cfg.out_file.with_suffix(".jsonl"), "w", encoding="utf-8") as f:
for itm in all_items:
f.write(json.dumps(itm.serialize()) + "\n")
# group, render
grouped: Dict[str, Dict[str, List[TodoItem]]] = group_items_by_tag_and_file(
all_items
)
rendered: str = Template(cfg.template_md).render(grouped=grouped)
# write md output
cfg.out_file.with_suffix(".md").write_text(rendered, encoding="utf-8")
# write html output
try:
html_rendered: str = cfg.template_html.replace(
"//{{DATA}}//", json.dumps([itm.serialize() for itm in all_items])
)
cfg.out_file.with_suffix(".html").write_text(html_rendered, encoding="utf-8")
except Exception as e:
warnings.warn(f"Failed to write html output: {e}")
print("wrote to:")
print(cfg.out_file.with_suffix(".md").as_posix())
if __name__ == "__main__":
# parse args
parser: argparse.ArgumentParser = argparse.ArgumentParser("inline_todo")
parser.add_argument(
"--config-file",
default="pyproject.toml",
help="Path to the TOML config, will look under [tool.inline-todo].",
)
args: argparse.Namespace = parser.parse_args()
# call main
main(Path(args.config_file))
endef
export SCRIPT_GET_TODOS
# markdown to html using pdoc
define SCRIPT_PDOC_MARKDOWN2_CLI
import argparse
from pathlib import Path
from typing import Optional
from pdoc.markdown2 import Markdown, _safe_mode # type: ignore
def convert_file(
input_path: Path,
output_path: Path,
safe_mode: Optional[_safe_mode] = None,
encoding: str = "utf-8",
) -> None:
"""Convert a markdown file to HTML"""
# Read markdown input
text: str = input_path.read_text(encoding=encoding)
# Convert to HTML using markdown2
markdown: Markdown = Markdown(
extras=["fenced-code-blocks", "header-ids", "markdown-in-html", "tables"],
safe_mode=safe_mode,
)
html: str = markdown.convert(text)
# Write HTML output
output_path.write_text(str(html), encoding=encoding)
def main() -> None:
parser: argparse.ArgumentParser = argparse.ArgumentParser(
description="Convert markdown files to HTML using pdoc's markdown2"
)
parser.add_argument("input", type=Path, help="Input markdown file path")
parser.add_argument("output", type=Path, help="Output HTML file path")
parser.add_argument(
"--safe-mode",
choices=["escape", "replace"],
help="Sanitize literal HTML: 'escape' escapes HTML meta chars, 'replace' replaces with [HTML_REMOVED]",
)
parser.add_argument(
"--encoding",
default="utf-8",
help="Character encoding for reading/writing files (default: utf-8)",
)
args: argparse.Namespace = parser.parse_args()
convert_file(
args.input, args.output, safe_mode=args.safe_mode, encoding=args.encoding
)
if __name__ == "__main__":
main()
endef
export SCRIPT_PDOC_MARKDOWN2_CLI
# clean up the docs (configurable in pyproject.toml)
define SCRIPT_DOCS_CLEAN
import sys
import shutil
from functools import reduce
from pathlib import Path
from typing import Any, List, Set
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # type: ignore
TOOL_PATH: str = "tool.makefile.docs"
DEFAULT_DOCS_DIR: str = "docs"
def deep_get(d: dict, path: str, default: Any = None, sep: str = ".") -> Any:
"""Get nested dictionary value via separated path with default."""
return reduce(
lambda x, y: x.get(y, default) if isinstance(x, dict) else default, # function
path.split(sep) if isinstance(path, str) else path, # sequence
d, # initial
)