-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms-full.txt
More file actions
5708 lines (4667 loc) · 219 KB
/
Copy pathllms-full.txt
File metadata and controls
5708 lines (4667 loc) · 219 KB
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
# GitVersioned Full Documentation
This file contains the concatenated core configurations, codebase, and documentation for the project to provide comprehensive context to LLMs.
# SECTION 1: PROJECT CONFIGURATIONS
## File: pyproject.toml
```toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "gitversioned"
dynamic = ["version"]
description = "Opinionated PEP 440 Python versioning for Git repos and submodules. Enforces CI/User authority and generates rich version.py files with deep metadata for auditability. Native Hatch & Setuptools support. Simple, predictable, and foolproof automation."
readme = "README.md"
requires-python = ">=3.10"
license = { text = "Apache-2.0" }
authors = [{ name = "Mark Kurtz" }]
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
]
dependencies = [
"loguru~=0.7",
"packaging>=26.0",
"pydantic~=2.0",
"pydantic-settings~=2.0",
"setuptools>=64.0.0",
"tomli~=2.0; python_version < '3.11'",
"tstr>=0.4.1",
"typer>=0.12",
]
[project.optional-dependencies]
hatch = ["hatchling~=1.18"]
maturin = ["maturin>=1.0,<2.0"]
opentelemetry = ["opentelemetry-api>=1.0.0", "opentelemetry-sdk>=1.0.0"]
[dependency-groups]
test = [
"pytest>=9.0,<10",
"pytest-asyncio>=1.3,<2",
"pytest-cov>=7.1,<8",
"pytest-mock>=3.15,<4",
"respx>=0.23,<1",
"build",
"wheel",
"maturin>=1.0,<2.0",
]
lint = [
"ty",
"ruff>=0.15,<1",
"mdformat>=1.0,<2",
"mdformat-frontmatter>=2.0,<3",
"mdformat-gfm>=1.0,<2",
"mdformat-footnote>=0.1.1,<1",
"mdformat-gfm-alerts>=1.0.1,<3",
"yamllint>=1.35,<2",
"urlchecker>=0.0.35",
"phmdoctest>=1.4,<2",
"yamlfix>=1.19,<2",
"taplo",
]
docs = [
"zensical>=0.0.40",
"mkdocs-gen-files>=0.5.0",
"mkdocstrings>=0.24.0",
"mkdocstrings-python>=1.9.0",
# Temporary bridge: Zensical compatible fork of mike.
# Update to Zensical native versioning once stabilized.
"mike @ git+https://github.com/squidfunk/mike.git",
]
security = [
"detect-secrets>=1.5,<2",
"checkov>=3.0,<4",
"semgrep>=1.73,<2",
"pip-audit>=2.7,<3",
]
environment = ["hatch>=1.12.0"]
dev = [
{ include-group = "test" },
{ include-group = "lint" },
{ include-group = "docs" },
{ include-group = "security" },
{ include-group = "environment" },
]
[project.scripts]
gitversioned = "gitversioned.__main__:main"
[project.urls]
Homepage = "https://github.com/markurtz/git-versioned"
Repository = "https://github.com/markurtz/git-versioned.git"
Issues = "https://github.com/markurtz/git-versioned/issues"
Documentation = "https://markurtz.github.io/git-versioned/"
[project.entry-points.hatch]
gitversioned = "gitversioned.plugins.hatchling_plugin"
[project.entry-points."setuptools.finalize_distribution_options"]
gitversioned = "gitversioned.plugins.setuptools_plugin:finalize_distribution_options"
[tool.hatch.version]
path = "src/gitversioned/__init__.py"
pattern = "(?m)^__version__[^=]*= *(['\"])v?(?P<version>.+?)\\1"
# ==============================================================================
# Hatch Environment Configurations
# ==============================================================================
[tool.hatch.envs.default]
dependency-groups = ["dev"]
[tool.hatch.envs.default.env-vars]
PYTHON_TARGETS = "docs examples scripts src tests"
OCI_IMAGE = "gitversioned:latest"
MDFORMAT_TARGETS = ".devcontainer/ .github/ docs/*.md docs/community/ docs/examples/ docs/getting-started/ docs/guides/ examples/ scripts/ src/ tests/ *.md"
YAML_TARGETS = ".devcontainer/ .github/ docs/ examples/ scripts/ src/ tests/ *.yml *.yaml"
TOML_TARGETS = ".devcontainer/ .github/ docs/ examples/ scripts/ src/ tests/ *.toml"
PYTHON_SRC = "src"
PYTHON_UNIT_TESTS = "tests/python/unit"
PYTHON_INT_TESTS = "tests/python/integration"
PYTHON_COV_DIR = "coverage/python"
E2E_TESTS = "tests/e2e"
DOC_TESTS_PATH = ".tests/docs"
SECRETS_BASELINE = ".detect-secrets.scan.json"
RUN_OCI_SCRIPT = "scripts/run_oci.py"
CHECK_LINKS_SCRIPT = "scripts/check_links.py"
GENERATE_DOC_TESTS_SCRIPT = "scripts/generate_doc_tests.py"
[tool.hatch.envs.all]
template = "default"
builder = true
[tool.hatch.envs.all.scripts]
lint = [
"hatch run python:lint {args}",
"hatch run oci:lint {args}",
"hatch run project:lint {args}",
]
format = [
"hatch run python:format {args}",
"hatch run oci:format {args}",
"hatch run project:format {args}",
]
types = [
"hatch run python:types {args}",
"hatch run oci:types {args}",
"hatch run project:types {args}",
]
security = [
"hatch run python:security {args}",
"hatch run oci:security {args}",
"hatch run project:security {args}",
]
quality = [
"hatch run python:quality {args}",
"hatch run oci:quality {args}",
"hatch run project:quality {args}",
]
build = [
"hatch build {args}",
"hatch run oci:build {args}",
"hatch run project:docs {args}",
]
tests = ["hatch run tests-func {args}", "hatch run tests-e2e {args}"]
tests-cov = [
"hatch run tests-func-cov {args}",
"hatch run tests-e2e-cov {args}",
]
tests-func = [
"hatch run python:tests-func {args}",
"hatch run oci:tests-func {args}",
"hatch run project:tests-func {args}",
]
tests-func-cov = [
"hatch run python:tests-func-cov {args}",
"hatch run oci:tests-func-cov {args}",
"hatch run project:tests-func-cov {args}",
]
tests-unit = [
"hatch run python:tests-unit {args}",
"hatch run oci:tests-unit {args}",
"hatch run project:tests-unit {args}",
]
tests-unit-cov = [
"hatch run python:tests-unit-cov {args}",
"hatch run oci:tests-unit-cov {args}",
"hatch run project:tests-unit-cov {args}",
]
tests-int = [
"hatch run python:tests-int {args}",
"hatch run oci:tests-int {args}",
"hatch run project:tests-int {args}",
]
tests-int-cov = [
"hatch run python:tests-int-cov {args}",
"hatch run oci:tests-int-cov {args}",
"hatch run project:tests-int-cov {args}",
]
tests-e2e = [
"hatch run python:tests-e2e {args}",
"hatch run oci:tests-e2e {args}",
"hatch run project:tests-e2e {args}",
]
tests-e2e-cov = [
"hatch run python:tests-e2e-cov {args}",
"hatch run oci:tests-e2e-cov {args}",
"hatch run project:tests-e2e-cov {args}",
]
docs = [
"hatch run python:docs {args}",
"hatch run oci:docs {args}",
"hatch run project:docs {args}",
]
docs-serve = ["hatch run docs {args}", "hatch run project:docs-serve {args}"]
# ==============================================================================
# Python Environment
# ==============================================================================
[tool.hatch.envs.python]
template = "default"
builder = true
[tool.hatch.envs.python.scripts]
lint = [
"ruff check {args:{env:PYTHON_TARGETS}}",
"ruff format --check {args:{env:PYTHON_TARGETS}}",
]
format = [
"ruff check --fix {args:{env:PYTHON_TARGETS}}",
"ruff format {args:{env:PYTHON_TARGETS}}",
]
types = "ty check {args:{env:PYTHON_TARGETS}}"
security = [
"semgrep scan --error {args}",
"pip-audit {args}",
"ruff check --select S {args:{env:PYTHON_TARGETS}}",
]
quality = [
"hatch run python:format {args}",
"hatch run python:lint {args}",
"hatch run python:types {args}",
"hatch run python:security {args}",
]
tests-func = "pytest {args:{env:PYTHON_UNIT_TESTS} {env:PYTHON_INT_TESTS}}"
tests-func-cov = [
"python -c \"import pathlib; pathlib.Path('{env:PYTHON_COV_DIR}').mkdir(parents=True, exist_ok=True)\"",
"pytest --cov={env:PYTHON_SRC} --cov-context=test --cov-report=term --cov-report=markdown:{env:PYTHON_COV_DIR}/coverage_tests-func.md {args:{env:PYTHON_UNIT_TESTS} {env:PYTHON_INT_TESTS}}",
"coverage report --contexts=\".*tests/python/unit/.*|^$\" --format=markdown > {env:PYTHON_COV_DIR}/coverage_tests-unit.md",
"coverage report --contexts=\".*tests/python/integration/.*|^$\" --format=markdown > {env:PYTHON_COV_DIR}/coverage_tests-int.md",
"python -c \"import pathlib; [p.write_text('\\n'.join(line for line in p.read_text().splitlines() if not line.startswith('Combined'))) for p in (pathlib.Path('{env:PYTHON_COV_DIR}/coverage_tests-unit.md'), pathlib.Path('{env:PYTHON_COV_DIR}/coverage_tests-int.md')) if p.exists()]\"",
]
tests-unit = "pytest {args:{env:PYTHON_UNIT_TESTS}}"
tests-unit-cov = [
"python -c \"import pathlib; pathlib.Path('{env:PYTHON_COV_DIR}').mkdir(parents=True, exist_ok=True)\"",
"pytest --cov={env:PYTHON_SRC} --cov-report=term --cov-report=markdown:{env:PYTHON_COV_DIR}/coverage_tests-unit.md {args:{env:PYTHON_UNIT_TESTS}}",
]
tests-int = "pytest {args:{env:PYTHON_INT_TESTS}}"
tests-int-cov = [
"python -c \"import pathlib; pathlib.Path('{env:PYTHON_COV_DIR}').mkdir(parents=True, exist_ok=True)\"",
"pytest --cov={env:PYTHON_SRC} --cov-report=term --cov-report=markdown:{env:PYTHON_COV_DIR}/coverage_tests-int.md {args:{env:PYTHON_INT_TESTS}}",
]
tests-e2e = [
"hatch build",
"pip install --force-reinstall --no-deps --no-index --find-links=dist gitversioned",
"pytest {args:{env:E2E_TESTS}}",
]
tests-e2e-cov = [
"python -c \"import pathlib; pathlib.Path('{env:PYTHON_COV_DIR}').mkdir(parents=True, exist_ok=True)\"",
"hatch build",
"pip install --force-reinstall --no-deps --no-index --find-links=dist gitversioned",
"pytest --cov=gitversioned --cov-report=term --cov-report=markdown:{env:PYTHON_COV_DIR}/coverage_tests-e2e.md {args:{env:E2E_TESTS}}",
]
docs = [
"python -c \"import pathlib; pathlib.Path('.docs').mkdir(exist_ok=True)\"",
"typer src/gitversioned/__main__.py utils docs --name gitversioned --output .docs/cli.md",
]
# ==============================================================================
# OCI Environment
# ==============================================================================
[tool.hatch.envs.oci]
template = "default"
[tool.hatch.envs.oci.scripts]
lint = [
"python {env:RUN_OCI_SCRIPT} hadolint {args}",
"python {env:RUN_OCI_SCRIPT} compose-config {args}",
"python {env:RUN_OCI_SCRIPT} dclint {args}",
]
format = "python {env:RUN_OCI_SCRIPT} dclint --fix {args}"
types = "echo '[INFO] Type checking is not applicable for the OCI environment' {args}"
security = [
"python {env:RUN_OCI_SCRIPT} dockle {args}",
"python {env:RUN_OCI_SCRIPT} trivy {args}",
]
quality = [
"hatch run oci:format {args}",
"hatch run oci:lint {args}",
"hatch run oci:types {args}",
"hatch run oci:security {args}",
]
tests-func = [
"hatch run oci:tests-unit {args}",
"hatch run oci:tests-int {args}",
]
tests-func-cov = [
"hatch run oci:tests-unit-cov {args}",
"hatch run oci:tests-int-cov {args}",
]
tests-unit = "echo '[INFO] No unit tests are defined for the OCI environment' {args}"
tests-unit-cov = [
"hatch run oci:tests-unit {args}",
"echo '[INFO] No coverage analysis is applicable for unit tests in the OCI environment'",
]
tests-int = "echo '[INFO] No integration tests are defined for the OCI environment' {args}"
tests-int-cov = [
"hatch run oci:tests-int {args}",
"echo '[INFO] No coverage analysis is applicable for integration tests in the OCI environment'",
]
tests-e2e = "python {env:RUN_OCI_SCRIPT} cstest {args}"
tests-e2e-cov = [
"hatch run oci:tests-e2e {args}",
"echo '[INFO] No coverage analysis is applicable for E2E tests in the OCI environment'",
]
docs = "echo '[INFO] No documentation is defined for the OCI environment' {args}"
build = "docker build -t {env:OCI_IMAGE} . {args}"
# ==============================================================================
# Project Environment
# ==============================================================================
[tool.hatch.envs.project]
template = "default"
[tool.hatch.envs.project.scripts]
lint = [
"mdformat --check {args:{env:MDFORMAT_TARGETS}}",
"yamlfix --check {args:{env:YAML_TARGETS}}",
"yamllint {args:{env:YAML_TARGETS}}",
"taplo check {args:{env:TOML_TARGETS}}",
]
format = [
"mdformat {args:{env:MDFORMAT_TARGETS}}",
"yamlfix {args:{env:YAML_TARGETS}}",
"taplo fmt {args:{env:TOML_TARGETS}}",
]
types = "echo '[INFO] Type checking is not applicable for the project environment' {args}"
security = [
"detect-secrets scan --baseline {env:SECRETS_BASELINE} {args:.}",
"python -m checkov.main --quiet {args:-d .}",
]
quality = [
"hatch run project:format {args}",
"hatch run project:lint {args}",
"hatch run project:types {args}",
"hatch run project:security {args}",
]
security-update = ["detect-secrets scan {args:.} > {env:SECRETS_BASELINE}"]
tests-func = [
"hatch run project:tests-unit {args}",
"hatch run project:tests-int {args}",
]
tests-func-cov = [
"hatch run project:tests-unit-cov {args}",
"hatch run project:tests-int-cov {args}",
]
tests-unit = "echo '[INFO] No unit tests are defined for the project environment'"
tests-unit-cov = [
"hatch run project:tests-unit {args}",
"echo '[INFO] No coverage analysis is applicable for unit tests in the project environment'",
]
tests-int = [
"python {env:GENERATE_DOC_TESTS_SCRIPT} {args:{env:PYTHON_TARGETS}}",
"hatch -e python run pytest {env:DOC_TESTS_PATH} {args}",
]
tests-int-cov = [
"hatch run project:tests-int {args}",
"echo '[INFO] No coverage analysis is applicable for integration tests in the project environment'",
]
tests-e2e = "python {env:CHECK_LINKS_SCRIPT} {args:{env:MDFORMAT_TARGETS}}"
tests-e2e-cov = [
"hatch run project:tests-e2e {args}",
"echo '[INFO] No coverage analysis is applicable for E2E tests in the project environment'",
]
docs = [
"python docs/scripts/gen_ref_pages.py generate",
"python -m zensical {args:build}",
"python docs/scripts/gen_ref_pages.py clean",
]
docs-serve = [
"python docs/scripts/gen_ref_pages.py generate",
"python -m zensical serve {args}",
"python docs/scripts/gen_ref_pages.py clean",
]
[tool.ty.src]
include = ["src/gitversioned", "tests"]
[tool.ruff]
line-length = 88
indent-width = 4
exclude = ["build", "dist", "env", ".venv", ".tests"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
[tool.ruff.lint]
ignore = [
"COM812", # ignore trailing comma errors due to older Python versions
"ISC001", # implicit string concatenation (often disabled when using ruff format)
"PD011", # ignore .values usage since ruff assumes it's a Pandas DataFrame
"PLR0913", # ignore too many arguments in function definitions
"PLW1514", # allow Path.open without encoding
"RET505", # allow `else` blocks
"RET506", # allow `else` blocks
"S311", # allow standard pseudo-random generators
"TC001", # ignore imports used only for type checking
"TC002", # ignore imports used only for type checking
"TC003", # ignore imports used only for type checking
]
select = [
# Rules reference: https://docs.astral.sh/ruff/rules/
# Code Style / Formatting
"E", # pycodestyle: checks adherence to PEP 8 conventions including spacing, indentation, and line length
"W", # pycodestyle: checks adherence to PEP 8 conventions including spacing, indentation, and line length
"A", # flake8-builtins: prevents shadowing of Python built-in names
"C", # Convention: ensures code adheres to specific style and formatting conventions
"COM", # flake8-commas: enforces the correct use of trailing commas
"ERA", # eradicate: detects commented-out code that should be removed
"I", # isort: ensures imports are sorted in a consistent manner
"ICN", # flake8-import-conventions: enforces import conventions for better readability
"N", # pep8-naming: enforces PEP 8 naming conventions for classes, functions, and variables
"NPY", # NumPy: enforces best practices for using the NumPy library
"PD", # pandas-vet: enforces best practices for using the pandas library
"PT", # flake8-pytest-style: enforces best practices and style conventions for pytest tests
"PTH", # flake8-use-pathlib: encourages the use of pathlib over os.path for file system operations
"Q", # flake8-quotes: enforces consistent use of single or double quotes
"TCH", # flake8-type-checking: enforces type checking practices and standards
"TID", # flake8-tidy-imports: enforces tidy and well-organized imports
"RUF022", # flake8-ruff: enforce sorting of __all__ in modules
# Code Structure / Complexity
"C4", # flake8-comprehensions: improves readability and performance of list, set, and dict comprehensions
"C90", # mccabe: checks for overly complex code using cyclomatic complexity
"ISC", # flake8-implicit-str-concat: prevents implicit string concatenation
"PIE", # flake8-pie: identifies and corrects common code inefficiencies and mistakes
"R", # Refactor: suggests improvements to code structure and readability
"SIM", # flake8-simplify: simplifies complex expressions and improves code readability
# Code Security / Bug Prevention
"ARG", # flake8-unused-arguments: detects unused function and method arguments
"ASYNC", # flake8-async: identifies incorrect or inefficient usage patterns in asynchronous code
"B", # flake8-bugbear: detects common programming mistakes and potential bugs
"BLE", # flake8-blind-except: prevents blind exceptions that catch all exceptions without handling
"F", # Pyflakes: detects unused imports, shadowed imports, undefined variables, and various formatting errors in string operations
"INP", # flake8-no-pep420: prevents implicit namespace packages by requiring __init__.py
"PGH", # pygrep-hooks: detects deprecated and dangerous code patterns
"PL", # Pylint: comprehensive source code analyzer for enforcing coding standards and detecting errors
"RSE", # flake8-raise: ensures exceptions are raised correctly
"S", # flake8-bandit: detects security issues and vulnerabilities in the code
"SLF", # flake8-self: prevents incorrect usage of the self argument in class methods
"T10", # flake8-debugger: detects the presence of debugging tools such as pdb
"T20", # flake8-print: detects print statements left in the code
"UP", # pyupgrade: automatically upgrades syntax for newer versions of Python
"YTT", # flake8-2020: identifies code that will break with future Python releases
# Code Documentation
"FIX", # flake8-fixme: detects FIXMEs and other temporary comments that should be resolved
]
[tool.ruff.lint.extend-per-file-ignores]
"tests/**/*.py" = [
"S101", # asserts allowed in tests
"ARG", # Unused function args allowed in tests
"PLR2004", # Magic value used in comparison
"TCH002", # No import only type checking in tests
"SLF001", # enable private member access in tests
"S105", # allow hardcoded passwords in tests
"S106", # allow hardcoded passwords in tests
"S311", # allow standard pseudo-random generators in tests
"PT011", # allow generic exceptions in tests
"N806", # allow uppercase variable names in tests
"PGH003", # allow general ignores in tests
"PLR0915", # allow complex statements in tests
"S603", # allow subprocess with untrusted input in tests
"S607", # allow partial executable paths in tests
"T201", # allow print in tests
]
"examples/**/*.py" = [
"T201", # allow print in examples
"INP001", # allow implicit namespace packages
]
"scripts/**/*.py" = [
"T201", # allow print in scripts
"INP001", # allow implicit namespace packages
"S603", # allow subprocess check with untrusted input
"S607", # allow starting a process with a partial executable path
"PLC0415", # allow local imports (e.g. dynamic imports in build_docs)
"BLE001", # allow catching blind Exception
]
"docs/**/*.py" = [
"T201", # allow print in docs
"INP001", # allow implicit namespace packages
]
[tool.ruff.lint.isort]
known-first-party = ["gitversioned", "tests"]
[tool.pytest.ini_options]
addopts = "-s -vvv --cache-clear"
asyncio_mode = "auto"
markers = [
"smoke: quick tests to check basic functionality",
"sanity: detailed tests to ensure major functions work correctly",
"regression: tests to ensure that new changes do not break existing functionality",
]
testpaths = ["tests"]
[tool.yamlfix]
line_length = 88
sequence_style = "block_style"
preserve_quotes = true
[tool.coverage.run]
patch = ["subprocess"]
```
## File: taplo.toml
```toml
# Copyright 2026 markurtz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
include = [
"*.toml",
".devcontainer/**/*.toml",
".github/**/*.toml",
"docs/**/*.toml",
"examples/**/*.toml",
"scripts/**/*.toml",
"src/**/*.toml",
"tests/**/*.toml",
]
```
## File: .yamllint
```yaml
# Copyright 2026 markurtz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
extends: default
ignore: |
.venv/
venv/
target/
build/
dist/
rules:
line-length:
max: 300
truthy:
check-keys: false
document-start: disable
```
# SECTION 2: CORE STRUCTURAL INTERFACES
## File: src/gitversioned/__init__.py
```python
"""
Opinionated PEP 440 Python versioning for Git repos and submodules.
Provides an automated, deterministic system for generating rich version information from
Git repository metadata. It enforces CI/User authority and creates version files with
deep metadata for auditability, integrating natively with Hatch and Setuptools.
Example:
::
from gitversioned import Settings, resolve_version
from gitversioned.utils import BuildEnvironment, GitRepository
version, _, ref = resolve_version(
Settings(), GitRepository(), BuildEnvironment()
)
print(f"Current version: {version}")
"""
from __future__ import annotations
from .logging import LoggingSettings, configure_logger
from .settings import Settings
from .versioning import (
resolve_version,
resolve_version_output,
resolve_version_output_to_stream,
)
__all__ = [
"LoggingSettings",
"Settings",
"__version__",
"configure_logger",
"resolve_version",
"resolve_version_output",
"resolve_version_output_to_stream",
]
__version__ = "0.1.3.dev10+9eea393"
configure_logger()
```
## File: src/gitversioned/logging.py
```python
"""
Configure logging infrastructure and provide utilities for GitVersioned.
This module initializes the global logger with custom configurations such as
log levels, target sinks, and thread-safe queues. It also provides automatic
function execution logging and integrates with OpenTelemetry trace contexts
for structured JSON output.
"""
from __future__ import annotations
import contextlib
import functools
import json
import sys
import traceback
from collections.abc import Callable
from typing import Any, ClassVar, Literal, TypeVar, cast, overload
from loguru import logger
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from gitversioned.compat import opentelemetry_trace
__all__ = ["LoggingSettings", "autolog", "configure_logger", "logger"]
_LOG_ENTRY_FORMAT: str = "Calling function '{name}' with args={args}, kwargs={kwargs}"
_LOG_EXIT_FORMAT: str = "Function '{name}' returned: {result}"
_LOG_EXCEPTION_FORMAT: str = "Exception occurred in function '{name}': {exception}"
_FuncT = TypeVar("_FuncT", bound=Callable[..., Any])
_state: dict[str, int | None] = {"handler_id": None}
class LoggingSettings(BaseSettings):
"""
Settings for configuring the loguru logging infrastructure.
This Pydantic settings class loads variables prefixed with
GITVERSIONED__LOGGING__ to manage log levels, destination sinks, thread
queues, and OpenTelemetry format options.
Example:
>>> from gitversioned.logging import LoggingSettings, configure_logger
>>> settings = LoggingSettings(level="DEBUG")
>>> configure_logger(settings)
model_config : ClassVar[SettingsConfigDict]
Configuration dictionary dictating environment variable prefixes and
nested delimiters.
"""
enabled: bool = Field(
default=False,
description="Enables logging output across the gitversioned package.",
)
clear_loggers: bool = Field(
default=False,
description="Removes all existing active logger sinks prior to configuration.",
)
sink: str | Any = Field(
default=sys.stdout,
description=(
"Specifies the output target (e.g. stdout, stderr, or a file path) "
"for log messages."
),
)
level: str = Field(
default="INFO",
description="Sets the minimum severity level for logged messages.",
)
otel_formatting: Literal["auto", "enable", "disable"] = Field(
default="auto",
description="Enables JSON formatting compliant with OpenTelemetry.",
)
format: str | Callable[..., Any] | None = Field(
default="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | "
"<cyan>{name}</cyan>:<cyan>{function}</cyan> - <level>{message}</level>\n",
description="Defines the standard text format template for emitted log lines.",
)
filter: Any = Field(
default=True,
description="Specifies a filter function or package prefix string.",
)
enqueue: bool = Field(
default=True,
description="Enables asynchronous, thread-safe message queueing.",
)
kwargs: dict[str, Any] = Field(
default_factory=dict,
description="Extra arguments passed directly to loguru's add handler.",
)
model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(
env_prefix="GITVERSIONED__LOGGING__",
env_nested_delimiter="__",
)
@field_validator("sink", mode="before")
@classmethod
def _parse_sink(cls, value: Any) -> Any:
# Convert string aliases for standard output/error streams to stream objects.
if isinstance(value, str):
mapping = {
"stdout": sys.stdout,
"sys.stdout": sys.stdout,
"stderr": sys.stderr,
"sys.stderr": sys.stderr,
}
return mapping.get(value.lower(), value)
return value
def configure_logger(settings: LoggingSettings | None = None) -> None:
"""
Configure the global loguru logger handler.
Example:
>>> configure_logger(LoggingSettings(level="WARNING"))
:param settings: Logging configurations, defaults to None (loads from environment).
:type settings: LoggingSettings | None
:return: None
:raises ImportError: Raised if OpenTelemetry formatting is enabled but
the package is not installed.
"""
settings = settings or LoggingSettings()
if not settings.enabled:
logger.disable("gitversioned")
return
logger.enable("gitversioned")
if settings.clear_loggers:
logger.remove()
_state["handler_id"] = None
elif isinstance(_state["handler_id"], int):
with contextlib.suppress(ValueError):
logger.remove(_state["handler_id"])
_state["handler_id"] = None
use_otel = settings.otel_formatting == "enable" or (
settings.otel_formatting == "auto" and opentelemetry_trace is not None
)
if settings.otel_formatting == "enable" and opentelemetry_trace is None:
raise ImportError(
"OpenTelemetry is not installed but 'otel_formatting' was set to 'enable'."
)
log_format = _otel_formatter if use_otel else settings.format
filter_val = "gitversioned" if settings.filter is True else settings.filter
if isinstance(filter_val, (list, tuple, str)):
prefixes = (
tuple(filter_val)
if isinstance(filter_val, (list, tuple))
else (filter_val,)
)
def final_filter(record: dict[str, Any]) -> bool:
return bool(record["name"] and record["name"].startswith(prefixes))
else:
final_filter = None if filter_val is False else filter_val
_state["handler_id"] = logger.add(
cast("Any", settings.sink),
level=settings.level,
filter=cast("Any", final_filter),
format=cast("Any", log_format),
enqueue=settings.enqueue,
**settings.kwargs,
)
@overload
def autolog(func: _FuncT) -> _FuncT: ...
@overload
def autolog(
func: None = None,
*,
exception_log_level: str | None = "ERROR",
) -> Callable[[_FuncT], _FuncT]: ...
def autolog(
func: _FuncT | None = None,
*,
exception_log_level: str | None = "ERROR",
) -> _FuncT | Callable[[_FuncT], _FuncT]:
"""
Decorate a function to log call inputs, outputs, and any raised exceptions.
Examples:
Use as a direct decorator:
>>> @autolog
... def add(a: int, b: int) -> int:
... return a + b
Use as a decorator factory call with defaults:
>>> @autolog()
... def sub(a: int, b: int) -> int:
... return a - b
Use with a custom exception log level:
>>> @autolog(exception_log_level="WARNING")
... def divide(a: int, b: int) -> float:
... return a / b
:param func: Target function to wrap, defaults to None.
:type func: Callable | None
:param exception_log_level: Log level for exception reporting,
defaults to "ERROR".
:type exception_log_level: str | None
:return: The decorated wrapper or a decorator factory function.
:rtype: Callable
"""
def decorator(func_to_wrap: _FuncT) -> _FuncT:
@functools.wraps(func_to_wrap)
def wrapper(*args: Any, **kwargs: Any) -> Any:
func_name = getattr(func_to_wrap, "__qualname__", "function")
logger.debug(
_LOG_ENTRY_FORMAT.format(name=func_name, args=args, kwargs=kwargs)
)
try:
result = func_to_wrap(*args, **kwargs)
except Exception as error:
if exception_log_level == "ERROR":
logger.opt(exception=error).error(
_LOG_EXCEPTION_FORMAT.format(name=func_name, exception=error),
)
elif exception_log_level is not None:
logger.log(
exception_log_level,
_LOG_EXCEPTION_FORMAT.format(name=func_name, exception=error),
)
raise error
else:
logger.debug(_LOG_EXIT_FORMAT.format(name=func_name, result=result))
return result
return cast("_FuncT", wrapper)
if func is None:
return decorator
return decorator(func)
def _otel_formatter(record: dict[str, Any]) -> str:
# Format the log record as an OpenTelemetry compliant JSON string.
trace_id = span_id = trace_flags = None
if opentelemetry_trace:
span = opentelemetry_trace.get_current_span()
context = span.get_span_context()
if context.is_valid:
trace_id = format(context.trace_id, "032x")
span_id = format(context.span_id, "016x")
trace_flags = format(context.trace_flags, "02x")
log_record = {
"timestamp": record["time"].isoformat(),
"severity_text": record["level"].name,
"body": record["message"],
"resource": {"service.name": "gitversioned"},
"attributes": {
"module": record["name"],
"function": record["function"],
"line": record["line"],
"process_id": record["process"].id,
**record["extra"],
},
}
if record.get("exception"):
exception = record["exception"]
log_record["attributes"]["exception.type"] = exception.type.__name__
log_record["attributes"]["exception.message"] = str(exception.value)
log_record["attributes"]["exception.stacktrace"] = "".join(
traceback.format_exception(
exception.type, exception.value, exception.traceback
)
)
if trace_id:
log_record.update(
{
"trace_id": trace_id,
"span_id": span_id,
"trace_flags": trace_flags,
}
)
# Escape braces so loguru doesn't interpret the JSON string as a format string
# Escape '<' and '>' to prevent loguru from interpreting them as color markup tags
return (
json.dumps(log_record)
.replace("{", "{{")
.replace("}", "}}")
.replace("<", "\\<")
.replace(">", "\\>")
) + "\n"
```
## File: src/gitversioned/settings.py
```python
"""
Configuration management settings for GitVersioned.
This module resolves and manages configuration parameters loaded from CLI arguments,
environment variables, and files like ``pyproject.toml`` or ``setup.cfg``.
"""
from __future__ import annotations
import configparser
import contextlib
import functools
import re
from pathlib import Path
from typing import Annotated, Any, Literal, cast
from pydantic import BaseModel, Field, model_validator
from pydantic_settings import (
BaseSettings,
CliSettingsSource,
PydanticBaseSettingsSource,
PyprojectTomlConfigSettingsSource,
SettingsConfigDict,
)
from gitversioned.compat import tomllib
from gitversioned.logging import autolog
from gitversioned.utils import EnsureList, EnsurePath
__all__ = [
"IncrementLevel",
"OutputStrategy",