-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcli.py
More file actions
2444 lines (2107 loc) · 83.9 KB
/
cli.py
File metadata and controls
2444 lines (2107 loc) · 83.9 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
from __future__ import annotations
import re
import sys
from pathlib import Path
import click
from . import __version__
from .core import GreatDocs
def _detect_python_version_from_pyproject(project_root: Path) -> str | None:
"""Detect the minimum Python version from pyproject.toml.
Parses the `requires-python` field (e.g., '>=3.12', '>=3.10,<3.13')
and returns a suitable Python version string for CI (e.g., '3.12').
Returns None if pyproject.toml doesn't exist or has no version requirement.
"""
pyproject_path = project_root / "pyproject.toml"
if not pyproject_path.exists():
return None
try:
# Use tomllib (Python 3.11+) or tomli as fallback
try:
import tomllib
except ImportError:
import tomli as tomllib
with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
requires_python = data.get("project", {}).get("requires-python")
if not requires_python:
return None
# Parse version specifier to find minimum version
# Common patterns: ">=3.12", ">=3.10,<3.13", "~=3.11", ">=3.9"
# Extract versions from specifiers
version_pattern = r"(\d+\.\d+)"
matches = re.findall(version_pattern, requires_python)
if not matches:
return None
# For >= specifiers, use the specified version
if ">=" in requires_python or "~=" in requires_python:
# Return the first (minimum) version found
return matches[0]
# For other specifiers, try to pick a reasonable version
# Find the highest version mentioned (likely the target)
versions = [tuple(map(int, v.split("."))) for v in matches]
max_version = max(versions)
return f"{max_version[0]}.{max_version[1]}"
except Exception:
# If parsing fails, return None to use default
return None
def _detect_package_manager(project_root: Path) -> str:
"""Detect the package manager used by the project.
Checks for lock files to determine which package manager is in use:
- uv.lock -> uv
- poetry.lock -> poetry
- Otherwise -> pip (default)
Returns:
One of: 'uv', 'poetry', or 'pip'
"""
if (project_root / "uv.lock").exists():
return "uv"
if (project_root / "poetry.lock").exists():
return "poetry"
return "pip"
def _detect_optional_dependencies(project_root: Path) -> list[str]:
"""Detect optional dependency groups from pyproject.toml.
Returns a list of optional dependency group names that are likely
related to documentation or development (e.g., 'dev', 'docs', 'test').
This helps generate appropriate pip install commands like:
pip install -e ".[dev,docs]"
"""
pyproject_path = project_root / "pyproject.toml"
if not pyproject_path.exists():
return []
try:
try:
import tomllib
except ImportError:
import tomli as tomllib
with open(pyproject_path, "rb") as f:
data = tomllib.load(f)
optional_deps = data.get("project", {}).get("optional-dependencies", {})
if not optional_deps:
return []
# Look for common dev/docs dependency group names
doc_related_extras = []
for key in optional_deps.keys():
key_lower = key.lower()
# Include extras that are likely needed for documentation builds
if any(term in key_lower for term in ["dev", "doc", "notebook", "test", "all", "full"]):
doc_related_extras.append(key)
return sorted(doc_related_extras)
except Exception:
return []
class OrderedGroup(click.Group):
"""Click group that lists commands in the order they were added."""
def list_commands(self, ctx: click.Context) -> list[str]:
return list(self.commands.keys())
@click.group(cls=OrderedGroup)
@click.version_option(version=__version__, prog_name="great-docs")
def cli():
"""Great Docs - Beautiful documentation for Python packages.
Great Docs generates professional documentation sites with auto-generated
API references, CLI documentation, smart navigation, and modern styling.
Get started with 'great-docs init' to set up your docs, then use
'great-docs build' to generate your site.
"""
pass
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--force",
is_flag=True,
help="Delete existing great-docs.yml and generate a fresh default config",
)
def init(project_path: str | None, force: bool) -> None:
"""Initialize great-docs in your project (one-time bootstrap).
Creates a fresh great-docs.yml configuration file with discovered
package exports and sensible defaults. Refuses to run if
great-docs.yml already exists (use --force to reset).
\b
• Creates great-docs.yml with discovered API exports
• Auto-detects your package name and public API
• Updates .gitignore to exclude the build directory
• Detects docstring style (numpy, google, sphinx)
After init, customize great-docs.yml then use 'great-docs build'
for all subsequent builds. You should never need to run init again
unless you want to completely reset your configuration.
\b
Examples:
great-docs init # Initialize in current directory
great-docs init --force # Reset config to defaults
great-docs init --project-path ../pkg # Initialize in another project
"""
try:
docs = GreatDocs(project_path=project_path)
docs.install(force=force)
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--watch",
is_flag=True,
help="Watch for changes and rebuild automatically",
)
@click.option(
"--no-refresh",
is_flag=True,
help="Skip re-discovering package exports (faster rebuild when API unchanged)",
)
@click.option(
"--versions",
"version_filter",
type=str,
default=None,
help="Build only specific versions (comma-separated tags, e.g. '0.3,dev')",
)
@click.option(
"--latest-only",
is_flag=True,
help="Build only the latest version (skip historical versions)",
)
@click.option(
"--from-repo",
"from_repo",
type=str,
default=None,
help="Clone a remote Git repository and build its docs (HTTPS or SSH URL)",
)
@click.option(
"--branch",
type=str,
default=None,
help="Branch or tag to check out when using --from-repo (default: repo default)",
)
@click.option(
"--output-dir",
type=click.Path(file_okay=False, dir_okay=True),
default=None,
help="Where to copy the built site when using --from-repo (default: ./great-docs/_site)",
)
@click.option(
"--shallow",
is_flag=True,
help="Force shallow clone with --from-repo (fastest, but no versioned docs or page dates)",
)
@click.option(
"--preview",
"preview_after",
is_flag=True,
help="Start a preview server after building with --from-repo",
)
def build(
project_path: str | None,
watch: bool,
no_refresh: bool,
version_filter: str | None,
latest_only: bool,
from_repo: str | None,
branch: str | None,
output_dir: str | None,
shallow: bool,
preview_after: bool,
) -> None:
"""Build your documentation site.
Requires great-docs.yml to exist (run 'great-docs init' first).
This is the only command you need day-to-day and in CI.
Creates the 'great-docs/' build directory, copies all assets,
and builds the documentation site. The build directory is ephemeral and
should not be committed to version control.
Use --project-path to point to a project in a different directory.
Use --watch to automatically rebuild when source files change.
Use --no-refresh to skip API discovery for faster rebuilds when your
package's public API hasn't changed.
When multi-version documentation is configured, use --versions to build
only specific versions, or --latest-only to skip historical versions.
Use --from-repo to build documentation from a remote Git repository.
This clones the repo into a temporary directory, creates an isolated
virtual environment, installs the package and great-docs, builds the
site, and copies the output to --output-dir (or ./great-docs/_site).
Add --preview to automatically start a local server after a --from-repo
build completes, opening the site in your browser.
\b
Examples:
great-docs build # Full build with API refresh
great-docs build --no-refresh # Fast rebuild (skip API discovery)
great-docs build --watch # Rebuild on file changes
great-docs build --versions 0.3,dev # Build specific versions only
great-docs build --latest-only # Build only the latest version
great-docs build --project-path ../pkg
great-docs build --from-repo https://github.com/owner/pkg.git
great-docs build --from-repo git@github.com:owner/pkg.git --branch v1.0
great-docs build --from-repo https://github.com/owner/pkg.git --output-dir ./site
great-docs build --from-repo https://github.com/owner/pkg.git --shallow
great-docs build --from-repo https://github.com/owner/pkg.git --preview
"""
try:
if from_repo:
# Remote build: clone, install, build, copy output
if project_path:
click.echo(
"Warning: --project-path is ignored when --from-repo is used",
err=True,
)
if watch:
click.echo("Error: --watch is not supported with --from-repo", err=True)
sys.exit(1)
version_tags = None
if version_filter:
version_tags = [v.strip() for v in version_filter.split(",") if v.strip()]
GreatDocs.build_from_repo(
from_repo,
branch=branch,
output_dir=output_dir,
refresh=not no_refresh,
version_tags=version_tags,
latest_only=latest_only,
shallow=shallow,
)
if preview_after:
site_path = output_dir or str(Path.cwd() / "great-docs" / "_site")
GreatDocs.preview_site(site_path)
else:
if branch:
click.echo("Warning: --branch is ignored without --from-repo", err=True)
if shallow:
click.echo("Warning: --shallow is ignored without --from-repo", err=True)
if output_dir:
click.echo("Warning: --output-dir is ignored without --from-repo", err=True)
if preview_after:
click.echo("Warning: --preview is ignored without --from-repo", err=True)
docs = GreatDocs(project_path=project_path)
# Parse version filter if provided
version_tags = None
if version_filter:
version_tags = [v.strip() for v in version_filter.split(",") if v.strip()]
docs.build(
watch=watch,
refresh=not no_refresh,
version_tags=version_tags,
latest_only=latest_only,
)
except KeyboardInterrupt:
click.echo("\n👋 Stopped watching")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
def uninstall(project_path: str | None) -> None:
"""Remove great-docs from your project.
This command removes the great-docs configuration and build directory:
\b
• Deletes great-docs.yml configuration file
• Removes great-docs/ build directory
Your source files (user_guide/, README.md, etc.) are preserved.
\b
Examples:
great-docs uninstall # Remove from current project
"""
try:
docs = GreatDocs(project_path=project_path)
docs.uninstall()
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--port",
type=int,
default=3000,
show_default=True,
help="Port for the local preview server",
)
@click.option(
"--site-dir",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
default=None,
help="Path to a pre-built site directory to serve (bypasses project detection)",
)
def preview(project_path: str | None, port: int, site_dir: str | None) -> None:
"""Preview your documentation locally.
Starts a local HTTP server and opens the built documentation site in your
default browser. If the site hasn't been built yet, it will build it first.
The site is served from great-docs/_site/. Use 'great-docs build' to
rebuild if you've made changes.
Use --site-dir to preview a site from any directory (e.g. output from
a --from-repo build).
\b
Examples:
great-docs preview # Preview on port 3000
great-docs preview --port 8080 # Preview on port 8080
great-docs preview --site-dir /tmp/weathervault-site
"""
try:
if site_dir:
if project_path:
click.echo(
"Warning: --project-path is ignored when --site-dir is used",
err=True,
)
GreatDocs.preview_site(site_dir, port=port)
else:
docs = GreatDocs(project_path=project_path)
docs.preview(port=port)
except KeyboardInterrupt:
click.echo("\n👋 Server stopped")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--force",
is_flag=True,
help="Overwrite existing great-docs.yml without prompting",
)
def config(project_path: str | None, force: bool) -> None:
"""Generate a great-docs.yml configuration file.
Creates a great-docs.yml file with all available options documented.
The generated file contains commented examples for each setting.
\b
Examples:
great-docs config # Generate in current directory
great-docs config --force # Overwrite existing file
great-docs config --project-path ../pkg
"""
from pathlib import Path
from .config import create_default_config
try:
project_root = Path(project_path) if project_path else Path.cwd()
config_path = project_root / "great-docs.yml"
if config_path.exists() and not force:
if not click.confirm(
f"⚠️ Configuration file already exists at {config_path}\n Overwrite it?"
):
click.echo("Cancelled.")
return
config_content = create_default_config()
config_path.write_text(config_content, encoding="utf-8")
click.echo(f"✓ Created {config_path}")
click.echo("\nEdit this file to customize your documentation settings.")
click.echo("See https://posit-dev.github.io/great-docs/user-guide/03-configuration.html")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# Register commands in the desired order
cli.add_command(init)
cli.add_command(build)
cli.add_command(preview)
cli.add_command(uninstall)
cli.add_command(config)
@click.command()
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--docs-dir",
type=str,
help="Path to documentation directory relative to project root",
)
@click.option(
"--verbose",
"-v",
is_flag=True,
help="Show method names for each class",
)
def scan(project_path: str | None, docs_dir: str | None, verbose: bool) -> None:
"""Discover package exports and preview what can be documented.
This command analyzes your package to find public classes, functions,
and other exports. Use this to see what's available before writing
your reference config.
\b
Examples:
great-docs scan # Show discovered exports
great-docs scan --verbose # Include method names for classes
great-docs scan -v # Short form of --verbose
"""
try:
docs = GreatDocs(project_path=project_path)
# Detect package name
package_name = docs._detect_package_name()
if not package_name:
click.echo("Error: Could not detect package name.", err=True)
sys.exit(1)
# Use explicit module name from great-docs.yml (or auto-detection) when
# available; this handles namespace packages like "firebird.base" where
# the importable module name differs from the PyPI project name.
module_name = docs._detect_module_name()
if module_name:
importable_name = module_name
else:
importable_name = docs._normalize_package_name(package_name)
# Section 1: Discovery
click.echo("─" * 50)
click.echo("📡 Discovery")
click.echo("─" * 50)
click.echo(f"Package: {importable_name}\n")
# Get discovered exports
exports = docs._get_package_exports(importable_name)
if not exports:
click.echo("No exports discovered.")
sys.exit(0)
# Categorize exports
categories = docs._categorize_api_objects(importable_name, exports)
# Build sets of what's in the reference config
reference_config = docs._config.reference
ref_items = set() # Items explicitly listed
ref_classes_with_members = set() # Classes with members: true (or default)
ref_classes_without_members = set() # Classes with members: false
for section in reference_config:
for item in section.get("contents", []):
if isinstance(item, str):
ref_items.add(item)
elif isinstance(item, dict):
name = item.get("name", "")
ref_items.add(name)
# Check members setting
members = item.get("members", True)
if members is False:
ref_classes_without_members.add(name)
else:
ref_classes_with_members.add(name)
# Section 2: Exports
click.echo("\n" + "─" * 50)
click.echo(f"📦 Exports ({len(exports)} item(s))")
click.echo("─" * 50)
# Markers with colors
marker_included = click.style("[x]", fg="green")
marker_not_included = click.style("[ ]", fg="red")
marker_class_only = click.style("[-]", fg="yellow")
# Show class-like categories (with method details)
_class_like_cats = [
("classes", "Classes"),
("dataclasses", "Dataclasses"),
("abstract_classes", "Abstract Classes"),
("protocols", "Protocols"),
]
for cat_key, label in _class_like_cats:
cat_items = categories.get(cat_key)
if cat_items:
click.echo(f"\n{label}:")
for class_name in cat_items:
method_names = categories.get("class_method_names", {}).get(class_name, [])
# Determine class marker
if class_name in ref_classes_without_members:
class_marker = marker_class_only
elif class_name in ref_classes_with_members or class_name in ref_items:
class_marker = marker_included
else:
class_marker = marker_not_included
click.echo(f"• {class_marker} {class_name}")
for method in method_names:
full_method = f"{class_name}.{method}"
method_marker = (
marker_included if full_method in ref_items else marker_not_included
)
click.echo(f" • {method_marker} {full_method}")
# Show flat categories (simple lists)
_flat_cats = [
("enums", "Enumerations"),
("exceptions", "Exceptions"),
("namedtuples", "Named Tuples"),
("typeddicts", "Typed Dicts"),
("functions", "Functions"),
("async_functions", "Async Functions"),
("constants", "Constants"),
("type_aliases", "Type Aliases"),
("other", "Other"),
]
for cat_key, label in _flat_cats:
cat_items = categories.get(cat_key)
if cat_items:
click.echo(f"\n{label}:")
for name in cat_items:
m = marker_included if name in ref_items else marker_not_included
click.echo(f"• {m} {name}")
# Section 3: Config status
click.echo("\n" + "─" * 50)
click.echo("📋 Reference Config")
click.echo("─" * 50)
if reference_config:
click.echo(f"\n✅ Found in great-docs.yml ({len(reference_config)} section(s))")
if verbose:
for section in reference_config:
title = section.get("title", "Untitled")
contents = section.get("contents", [])
click.echo(f" • {title}: {len(contents)} item(s)")
else:
click.echo("\n💡 No reference config found. Add one to great-docs.yml:")
click.echo(" reference:")
click.echo(" - title: Core Classes")
click.echo(" desc: Main classes for the package")
click.echo(" contents:")
click.echo(" - name: MyClass")
click.echo(" members: false # Don't document methods")
click.echo(" - SimpleClass # Methods inline")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
cli.add_command(scan)
@click.command(name="setup-github-pages")
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--main-branch",
type=str,
default="main",
help="Main branch name for deployment (default: main)",
)
@click.option(
"--python-version",
type=str,
default=None,
help="Python version for CI (default: auto-detect from pyproject.toml, or 3.11)",
)
@click.option(
"--package-manager",
type=click.Choice(["auto", "pip", "uv", "poetry"]),
default="auto",
help="Package manager for installing dependencies (default: auto-detect)",
)
@click.option(
"--force",
is_flag=True,
help="Overwrite existing workflow file without prompting",
)
@click.option(
"--install-from-main",
is_flag=True,
help="Install Great Docs from GitHub main branch instead of PyPI release",
)
def setup_github_pages(
project_path: str | None,
main_branch: str,
python_version: str | None,
package_manager: str,
force: bool,
install_from_main: bool,
) -> None:
"""Set up automatic deployment to GitHub Pages.
This command creates a GitHub Actions workflow that automatically builds
and deploys your documentation when you push to the main branch.
\b
The workflow will:
• Build docs on every push and pull request
• Deploy to GitHub Pages on main branch pushes
• Use Quarto's official GitHub Action for reliable builds
• Install dev dependencies (auto-detected from your package manager)
The Python version is automatically detected from your pyproject.toml's
`requires-python` field. Use --python-version to override.
The package manager is auto-detected by checking for lock files:
• uv.lock → uses uv (installs dev dependencies automatically)
• poetry.lock → uses poetry (installs with dev dependencies)
• Otherwise → uses pip with optional extras like [dev,docs]
After running this command, commit the workflow file and enable GitHub
Pages in your repository settings (Settings → Pages → Source: GitHub Actions).
\b
Examples:
great-docs setup-github-pages # Auto-detect everything
great-docs setup-github-pages --main-branch dev # Deploy from 'dev' branch
great-docs setup-github-pages --python-version 3.12
great-docs setup-github-pages --package-manager uv
great-docs setup-github-pages --force # Overwrite existing workflow
great-docs setup-github-pages --install-from-main # Use GitHub main branch
"""
try:
# Determine project root
project_root = Path(project_path) if project_path else Path.cwd()
# Auto-detect Python version if not specified
if python_version is None:
detected_version = _detect_python_version_from_pyproject(project_root)
if detected_version:
python_version = detected_version
click.echo(f"📦 Detected Python {python_version} from pyproject.toml")
else:
python_version = "3.12"
click.echo("📦 Using default Python 3.12 (no requires-python found)")
# Auto-detect package manager if not specified
if package_manager == "auto":
package_manager = _detect_package_manager(project_root)
if package_manager == "uv":
click.echo("🔧 Detected uv (found uv.lock)")
elif package_manager == "poetry":
click.echo("🔧 Detected poetry (found poetry.lock)")
else:
click.echo("🔧 Using pip (no uv.lock or poetry.lock found)")
# Determine great-docs install source
if install_from_main:
great_docs_install = "git+https://github.com/posit-dev/great-docs.git"
click.echo("📥 Will install Great Docs from GitHub main branch")
else:
great_docs_install = "great-docs"
click.echo("📥 Will install Great Docs from PyPI (latest release)")
# Generate install commands based on package manager
if package_manager == "uv":
install_commands = f"""\
python -m pip install uv
uv sync
uv pip install {great_docs_install}"""
build_command = "uv run great-docs build"
elif package_manager == "poetry":
install_commands = f"""\
python -m pip install poetry
poetry install
poetry run pip install {great_docs_install}"""
build_command = "poetry run great-docs build"
else:
# pip: try to detect optional dependencies
optional_deps = _detect_optional_dependencies(project_root)
if optional_deps:
extras = ",".join(optional_deps)
click.echo(f"📋 Found optional dependencies: {extras}")
install_commands = f"""\
python -m pip install --upgrade pip
python -m pip install -e ".[{extras}]"
python -m pip install {great_docs_install}"""
else:
install_commands = f"""\
python -m pip install --upgrade pip
python -m pip install -e .
python -m pip install {great_docs_install}"""
build_command = "great-docs build"
# Create .github/workflows directory
workflow_dir = project_root / ".github" / "workflows"
workflow_file = workflow_dir / "docs.yml"
# Check if workflow file already exists
if workflow_file.exists() and not force:
if not click.confirm(
f"⚠️ Workflow file already exists at {workflow_file.relative_to(project_root)}\n"
" Overwrite it?",
default=False,
):
click.echo("❌ Aborted. Use --force to overwrite without prompting.")
sys.exit(1)
# Create directory structure
workflow_dir.mkdir(parents=True, exist_ok=True)
# Load template
try:
# For Python 3.9+
from importlib.resources import files
template_file = files("great_docs").joinpath("assets/github-workflow-template.yml")
template_content = template_file.read_text()
except (ImportError, AttributeError):
# For Python 3.8 or earlier
from importlib_resources import files
template_file = files("great_docs").joinpath("assets/github-workflow-template.yml")
template_content = template_file.read_text()
# Replace placeholders (using replace() to handle linter-formatted templates)
workflow_content = template_content.replace("{ main_branch }", main_branch)
workflow_content = workflow_content.replace("{main_branch}", main_branch)
workflow_content = workflow_content.replace("{ python_version }", python_version)
workflow_content = workflow_content.replace("{python_version}", python_version)
workflow_content = workflow_content.replace("{install_commands}", install_commands)
workflow_content = workflow_content.replace("{build_command}", build_command)
# Write workflow file
workflow_file.write_text(workflow_content)
click.echo(
f"✅ Created GitHub Actions workflow at {workflow_file.relative_to(project_root)}"
)
click.echo()
click.echo("📋 Next steps:")
click.echo(" 1. Commit and push the workflow file to your repository")
click.echo(" 2. Go to your repository Settings → Pages")
click.echo(" 3. Set Source to 'GitHub Actions' (or 'gh-pages branch' if using that)")
click.echo(f" 4. Push changes to '{main_branch}' branch to trigger deployment")
click.echo()
click.echo("💡 The workflow will:")
click.echo(f" • Build docs on every push to '{main_branch}' and pull requests")
click.echo(" • Automatically deploy to GitHub Pages on main branch")
click.echo(" • Create preview deployments for pull requests")
except Exception as e:
click.echo(f"Error: {e}", err=True)
sys.exit(1)
# Register commands in the desired order
cli.add_command(setup_github_pages)
@click.command(name="check-links")
@click.option(
"--project-path",
type=click.Path(exists=True, file_okay=False, dir_okay=True),
help="Path to your project root directory (default: current directory)",
)
@click.option(
"--source-only",
is_flag=True,
help="Only check links in Python source files",
)
@click.option(
"--docs-only",
is_flag=True,
help="Only check links in documentation files",
)
@click.option(
"--timeout",
type=float,
default=10.0,
help="Timeout in seconds for each HTTP request (default: 10)",
)
@click.option(
"--ignore",
"-i",
multiple=True,
help="URL pattern to ignore (can be used multiple times)",
)
@click.option(
"--verbose",
"-v",
is_flag=True,
help="Show detailed progress for each URL checked",
)
@click.option(
"--json-output",
is_flag=True,
help="Output results as JSON",
)
def check_links(
project_path: str | None,
source_only: bool,
docs_only: bool,
timeout: int,
ignore: tuple[str, ...],
verbose: bool,
json_output: bool,
) -> None:
"""Check for broken links in source code and documentation.
This command scans Python source files and documentation (`.qmd`, `.md`)
for URLs and checks their HTTP status. It reports broken links (404s)
and warns about redirects.
\b
Default ignore patterns include:
• localhost and 127.0.0.1 URLs
• example.com, example.org, yoursite.com URLs
• Placeholder URLs with brackets like [username]
\b
Examples:
great-docs check-links # Check all links
great-docs check-links --verbose # Show progress for each URL
great-docs check-links --docs-only # Only check documentation
great-docs check-links --source-only # Only check source code
great-docs check-links -i "github.com/.*#" # Ignore GitHub anchor links
great-docs check-links --timeout 5 # Use 5 second timeout
great-docs check-links --json-output # Output as JSON
"""
import json as json_module
try:
docs = GreatDocs(project_path=project_path)
# Determine what to scan
include_source = not docs_only
include_docs = not source_only
# Build ignore patterns list
ignore_patterns = list(ignore) if ignore else []
# Add default ignore patterns
default_ignores = [
r"localhost",
r"127\.0\.0\.1",
r"0\.0\.0\.0",
r"example\.com",
r"example\.org",
r"example\.net",
r"\[", # URLs with brackets (placeholders like [username])
r"yoursite\.com",
r"your-package",
r"YOUR-USERNAME",
r"\.git(@|$)", # Git URLs (pip install git+...) with optional branch/tag
]
ignore_patterns.extend(default_ignores)
if not json_output:
click.echo("🔗 Checking links...")
if not include_source:
click.echo(" (documentation files only)")
elif not include_docs:
click.echo(" (source files only)")
results = docs.check_links(
include_source=include_source,
include_docs=include_docs,
timeout=timeout,
ignore_patterns=ignore_patterns,
verbose=verbose,
)
if json_output:
# Output as JSON
click.echo(json_module.dumps(results, indent=2))
sys.exit(1 if results["broken"] else 0)
# Print summary
click.echo("\n" + "=" * 60)
click.echo("📊 Link Check Summary")
click.echo("=" * 60)
total_checked = results["total"] - len(results["skipped"])
click.echo(f"\n Total URLs found: {results['total']}")
click.echo(f" URLs checked: {total_checked}")
click.echo(f" URLs skipped: {len(results['skipped'])}")
click.echo(f"\n ✅ OK: {len(results['ok'])}")
click.echo(f" ↪️ Redirects: {len(results['redirects'])}")
click.echo(f" ❌ Broken: {len(results['broken'])}")
# Show broken links
if results["broken"]:
click.echo("\n" + "-" * 60)
click.echo("❌ Broken Links:")