Repository navigation
Expand file tree
/
Copy pathingest.py
More file actions
4295 lines (3661 loc) · 155 KB
/
Copy pathingest.py
File metadata and controls
4295 lines (3661 loc) · 155 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
"""
This is the script that gathers markdown files from all of Netdata's repos in this repo
Stages of this ingest script:
Stage_1: Ingest every available markdown from the defaultRepos
Stage_2: We create three buckets:
1. all_markdown_files: all the markdown files in defaultRepos
2. markdown_files_with_metadata: all the markdown files that have hidden metadata fields
3. toPublish: markdown files that must be included in the learn
(metadata_key_value: "learn_status": "Published")
Stage_3:
1. Move the toPublish markdown files under the DOCS_PREFIX folder based on their metadata (they decide where,
they live)
2. Generate autogenerated pages
Stage_4: Sanitization
1. Make the hidden metadata fields actual readable metadata for docusaurus
Stage_5: Convert GH links to version specific links
"""
# Imports
import argparse
import ast
import errno
import glob
import hashlib
import io
import os
import re
import secrets
import shutil
import stat
import urllib.parse
from pathlib import Path, PurePosixPath
import json
import xml.etree.ElementTree as ET
import git
import numpy as np
import pandas as pd
import requests
import yaml
from jsonschema import Draft7Validator
try:
from PIL import Image
except Exception:
Image = None
import autogenerateRedirects as genRedirects
import learn_links
import llms_files
import mdx_code
DRY_RUN = False
DEBUG = False
DOCS_PREFIX = "will be added by arguments"
rest_files_dictionary = {}
rest_files_with_metadata_dictionary = {}
to_publish = {}
all_markdown_files = []
UNCORRELATED_LINK_COUNTER = 0
# Dict mapping repo name to dict of broken URLs -> set of source files
UNCORRELATED_URLS_BY_REPO = {}
# Dict mapping repo name to dict of (url, header) -> set of source files
BROKEN_HEADER_LINKS_BY_REPO = {}
FAIL_ON_REPOS = set() # Set of repo names to fail on if broken links found
FAIL_ON_ALL_BROKEN_LINKS = False # If True, fail on any broken link regardless of repo
IGNORE_ON_PREM_REPO = (
False # If True, skip cloning on-prem repo and ignore links pointing to it
)
LOCAL_REPOS = {} # Dict mapping repo name to local path (use local dir instead of cloning)
# Temporarily until we release (change it (the default) to /docs
# version_prefix = "nightly" # We use this as the version prefix in the link strategy
TEMP_FOLDER = "ingest-temp-folder"
default_repos = {
"netdata": {
"owner": "netdata",
"branch": "master",
"HEAD": "master",
},
"netdata-cloud-onprem": {
"owner": "netdata",
"branch": "master",
"HEAD": "master",
},
".github": {
"owner": "netdata",
"branch": "main",
"HEAD": "main",
},
"agent-service-discovery": {
"owner": "netdata",
"branch": "master",
"HEAD": "master",
},
"netdata-grafana-datasource-plugin": {
"owner": "netdata",
"branch": "master",
"HEAD": "master",
},
"helmchart": {
"owner": "netdata",
"branch": "master",
"HEAD": "master",
},
}
# Regex to extract sidebar_position from frontmatter (supports double or single quotes)
POS_RE = re.compile(r'(?m)^\s*sidebar_position\s*:\s*["\']?(\d+)["\']?\s*$')
SIDEBAR_LABEL_RE = re.compile(r'(?m)^\s*sidebar_label\s*:\s*["\']([^"\']+)["\']\s*$')
# Marker string in auto-generated integration files
INTEGRATION_MARKER = "DO NOT EDIT THIS FILE DIRECTLY"
MAP_SIDEBAR_ORDER = {}
MAP_DOC_SCOPE = {}
MAP_SCHEMA_EXIT_CODE = 2
REDIRECT_GATE_EXIT_CODE = 3
SIDEBAR_ORDER_STATE_PATH = Path(__file__).resolve().with_name(
"generated_sidebar_order.json"
)
KICKSTART_CHECKSUM_PLACEHOLDER = "@KICKSTART_CHECKSUM@"
KICKSTART_CHECKSUM_DOC = Path(
"Netdata Agent/Installation/Linux/Linux.mdx"
)
KICKSTART_SCRIPT_PATH = Path("packaging/installer/kickstart.sh")
class UnsafeFilesystemPathError(RuntimeError):
"""Raised when ingest would cross an owned filesystem boundary."""
def _absolute_path(path):
return Path(os.path.abspath(os.fspath(path)))
def _lstat(path, *, allow_missing=False):
path = _absolute_path(path)
try:
return path, path.lstat()
except FileNotFoundError:
if allow_missing:
return path, None
raise
def _require_no_symlink_ancestors(path, *, include_leaf=False):
path = _absolute_path(path)
parts = path.parts
current = Path(parts[0])
limit = len(parts) if include_leaf else len(parts) - 1
for part in parts[1:limit]:
current /= part
_, current_stat = _lstat(current)
if stat.S_ISLNK(current_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link ancestor: {current}")
if not stat.S_ISDIR(current_stat.st_mode):
raise UnsafeFilesystemPathError(
f"Refusing non-directory ancestor: {current}"
)
return path
def _require_regular_file(path, *, allow_missing=False):
path = _require_no_symlink_ancestors(path)
path, path_stat = _lstat(path, allow_missing=allow_missing)
if path_stat is None:
return path
if stat.S_ISLNK(path_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {path}")
if not stat.S_ISREG(path_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing non-regular file: {path}")
return path
def _require_regular_directory(path):
path = _require_no_symlink_ancestors(path)
path, path_stat = _lstat(path)
if stat.S_ISLNK(path_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link directory: {path}")
if not stat.S_ISDIR(path_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing non-directory path: {path}")
return path
def _validate_docs_tree(docs_root):
"""Reject links and special files before an ingest recovery touches the tree."""
root = _require_regular_directory(docs_root)
stack = [root]
while stack:
directory = stack.pop()
with os.scandir(directory) as entries:
for entry in entries:
path = Path(entry.path)
if entry.is_symlink():
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {path}")
if entry.is_dir(follow_symlinks=False):
stack.append(path)
elif not entry.is_file(follow_symlinks=False):
raise UnsafeFilesystemPathError(
f"Refusing non-regular filesystem entry: {path}"
)
return root
def _child_directories(directory):
"""Return real child directories without relying on glob suffix behavior."""
directory = _require_regular_directory(directory)
children = []
with os.scandir(directory) as entries:
for entry in entries:
path = Path(entry.path)
if entry.is_symlink():
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {path}")
if entry.is_dir(follow_symlinks=False):
children.append(path)
elif not entry.is_file(follow_symlinks=False):
raise UnsafeFilesystemPathError(
f"Refusing non-regular filesystem entry: {path}"
)
return sorted(children, key=lambda path: path.name)
def _validate_path_under_root(
docs_root, path, *, allow_missing_leaf=False, expected="file"
):
root = _require_regular_directory(docs_root)
candidate = _absolute_path(path)
try:
relative = candidate.relative_to(root)
except ValueError as error:
raise UnsafeFilesystemPathError(
f"Path escapes configured docs root {root}: {candidate}"
) from error
if not relative.parts:
if expected != "directory":
raise UnsafeFilesystemPathError(
f"Expected a file below configured docs root {root}: {candidate}"
)
return root
current = root
parts = relative.parts
for index, part in enumerate(parts):
current /= part
is_leaf = index == len(parts) - 1
current, current_stat = _lstat(
current, allow_missing=allow_missing_leaf and is_leaf
)
if current_stat is None:
break
if stat.S_ISLNK(current_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {current}")
if not is_leaf and not stat.S_ISDIR(current_stat.st_mode):
raise UnsafeFilesystemPathError(
f"Refusing non-directory ancestor: {current}"
)
if is_leaf:
valid = (
stat.S_ISREG(current_stat.st_mode)
if expected == "file"
else stat.S_ISDIR(current_stat.st_mode)
)
if not valid:
noun = "file" if expected == "file" else "directory"
raise UnsafeFilesystemPathError(
f"Refusing non-regular {noun}: {current}"
)
real_root = root.resolve(strict=True)
real_parent = candidate.parent.resolve(strict=True)
try:
real_parent.relative_to(real_root)
except ValueError as error:
raise UnsafeFilesystemPathError(
f"Path parent escapes configured docs root {root}: {candidate}"
) from error
return candidate
def _read_regular_bytes(path):
path = _require_regular_file(path)
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
descriptor = os.open(path, flags)
try:
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
raise UnsafeFilesystemPathError(f"Refusing non-regular file: {path}")
with os.fdopen(descriptor, "rb", closefd=False) as stream:
return stream.read()
finally:
os.close(descriptor)
def _read_regular_text(path, *, encoding="utf-8"):
return _read_regular_bytes(path).decode(encoding)
def _atomic_write_text(path, content, *, docs_root=None, encoding="utf-8"):
if docs_root is None:
destination = _require_regular_file(path, allow_missing=True)
_require_regular_directory(destination.parent)
else:
destination = _validate_path_under_root(
docs_root, path, allow_missing_leaf=True, expected="file"
)
parent_stat = destination.parent.lstat()
directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
parent_descriptor = os.open(destination.parent, directory_flags)
temporary_name = f".{destination.name}.{os.getpid()}.{secrets.token_hex(12)}"
descriptor = -1
try:
opened_parent_stat = os.fstat(parent_descriptor)
if (opened_parent_stat.st_dev, opened_parent_stat.st_ino) != (
parent_stat.st_dev,
parent_stat.st_ino,
):
raise UnsafeFilesystemPathError(
f"Destination parent changed during validation: {destination.parent}"
)
existing_mode = 0o644
try:
destination_stat = os.stat(
destination.name, dir_fd=parent_descriptor, follow_symlinks=False
)
except FileNotFoundError:
destination_stat = None
if destination_stat is not None:
if stat.S_ISLNK(destination_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {destination}")
if not stat.S_ISREG(destination_stat.st_mode):
raise UnsafeFilesystemPathError(
f"Refusing non-regular file: {destination}"
)
existing_mode = stat.S_IMODE(destination_stat.st_mode)
descriptor = os.open(
temporary_name,
os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
existing_mode,
dir_fd=parent_descriptor,
)
os.fchmod(descriptor, existing_mode)
with os.fdopen(descriptor, "w", encoding=encoding) as stream:
descriptor = -1
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.replace(
temporary_name,
destination.name,
src_dir_fd=parent_descriptor,
dst_dir_fd=parent_descriptor,
)
finally:
if descriptor >= 0:
os.close(descriptor)
try:
os.unlink(temporary_name, dir_fd=parent_descriptor)
except FileNotFoundError:
pass
os.close(parent_descriptor)
def apply_kickstart_checksum(docs_root, checksum):
"""Write the supplied kickstart checksum into the ingested document."""
if (
not isinstance(checksum, str)
or re.fullmatch(r"[0-9a-fA-F]{32}", checksum) is None
):
raise ValueError(
"Kickstart checksum must be exactly 32 hexadecimal characters"
)
docs_root = _require_regular_directory(docs_root)
document = _validate_path_under_root(
docs_root, docs_root / KICKSTART_CHECKSUM_DOC, expected="file"
)
content = _read_regular_text(document)
occurrences = content.count(KICKSTART_CHECKSUM_PLACEHOLDER)
if occurrences != 1:
raise ValueError(
"Expected exactly one kickstart checksum placeholder in "
f"{document}, found {occurrences}"
)
updated = content.replace(
KICKSTART_CHECKSUM_PLACEHOLDER, checksum.lower(), 1
)
_atomic_write_text(document, updated, docs_root=docs_root)
def resolve_kickstart_checksum(checksum, regenerate_grids_only, local_repos):
"""Resolve the checksum without changing the selected source checkout."""
if regenerate_grids_only:
return checksum
if checksum is not None:
if (
not isinstance(checksum, str)
or re.fullmatch(r"[0-9a-fA-F]{32}", checksum) is None
):
raise ValueError(
"Kickstart checksum must be exactly 32 hexadecimal characters"
)
return checksum.lower()
local_netdata = local_repos.get("netdata")
if local_netdata is None:
raise ValueError(
"Full ingest requires --kickstart-checksum with exactly 32 hexadecimal "
"characters unless an explicit local netdata checkout is selected"
)
repository_root = _require_regular_directory(local_netdata)
script = _validate_path_under_root(
repository_root,
repository_root / KICKSTART_SCRIPT_PATH,
expected="file",
)
return hashlib.md5(
_read_regular_bytes(script), usedforsecurity=False
).hexdigest()
def _safe_unlink(path, docs_root):
target = _validate_path_under_root(docs_root, path, expected="file")
parent_stat = target.parent.lstat()
directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
parent_descriptor = os.open(target.parent, directory_flags)
try:
opened_parent_stat = os.fstat(parent_descriptor)
if (opened_parent_stat.st_dev, opened_parent_stat.st_ino) != (
parent_stat.st_dev,
parent_stat.st_ino,
):
raise UnsafeFilesystemPathError(
f"Artifact parent changed during validation: {target.parent}"
)
target_stat = os.stat(
target.name, dir_fd=parent_descriptor, follow_symlinks=False
)
if stat.S_ISLNK(target_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing symbolic link: {target}")
if not stat.S_ISREG(target_stat.st_mode):
raise UnsafeFilesystemPathError(f"Refusing non-regular file: {target}")
os.unlink(target.name, dir_fd=parent_descriptor)
finally:
os.close(parent_descriptor)
SIDEBAR_ORDER_STATE_SOURCE = "netdata/docs/.map/map.yaml"
SIDEBAR_ORDER_STATE_KEYS = {
"schema_version",
"source",
"source_sha256",
"source_corpus_sha256",
"full_ingest_identity_sha256",
"order",
}
SIDEBAR_ORDER_ENTRY_KEYS = {"parent_path", "child_name", "position"}
GENERATED_CATEGORY_OWNER = "netdata-learn-ingest"
LOGO_ANALYSIS_TIMEOUT = 8
LOGO_RASTER_SAMPLE_SIZE = 64
LOGO_ALPHA_MIN = 16
LOGO_CONTRAST_THRESHOLD = 2.1
LIGHT_THEME_BG_RGB = (0xFD / 255.0, 0xFD / 255.0, 0xFD / 255.0)
DARK_THEME_BG_RGB = (0.0, 0.0, 0.0)
LOGO_CACHE = {}
LOGO_ANALYSIS_SUMMARY = {
"analyzed": 0,
"low_dark": 0,
"low_light": 0,
"unknown": 0,
}
# WCAG AA normal-text threshold. Mermaid classDef/style fill+color pairs below
# this are rewritten to MERMAID_DEFAULT_* since a fixed hex fill can't adapt to
# light/dark colorMode on its own.
MERMAID_CONTRAST_THRESHOLD = 4.5
MERMAID_DEFAULT_FILL = "#f0f0f0"
MERMAID_DEFAULT_STROKE = "#666666"
MERMAID_DEFAULT_TEXT = "#1a1a1a"
MERMAID_CONTRAST_SUMMARY = {
"scanned": 0,
"fixed": 0,
}
MAP_COLUMNS = [
"custom_edit_url",
"sidebar_label",
"learn_status",
"learn_rel_path",
"keywords",
"description",
]
def format_map_schema_error(error):
path = (
".".join(str(p) for p in error.absolute_path) if error.absolute_path else "root"
)
return f"[{path}] {error.message}"
def validate_map_schema(map_path, schema_path):
with open(map_path, "r", encoding="utf-8") as map_file:
map_data = yaml.safe_load(map_file) or {}
with open(schema_path, "r", encoding="utf-8") as schema_file:
schema = json.load(schema_file)
validator = Draft7Validator(schema)
errors = [
format_map_schema_error(error) for error in validator.iter_errors(map_data)
]
return len(errors) == 0, errors
def _normalize_placeholder_kind(kind):
"""Normalize integration placeholder kind to '<kind>_integrations'."""
if not kind:
return None
if kind.endswith("_integrations"):
return kind
return f"{kind}_integrations"
def load_map_yaml(map_path):
"""Load simplified map.yaml and return ingest rows as a DataFrame.
Rules:
- Document rows are emitted only for nodes with non-empty `meta.edit_url`.
- Placeholder rows are emitted for `integration_placeholder` entries.
- `learn_rel_path` is reconstructed from hierarchy and optional `meta.path`.
- `learn_status` is set to "Published" for emitted document rows.
"""
with open(map_path, "r", encoding="utf-8") as fh:
data = yaml.safe_load(fh) or {}
sidebar = data.get("sidebar")
if not isinstance(sidebar, list):
raise ValueError("map.yaml must contain a top-level 'sidebar' list.")
rows = []
def join_path(parent_path, segment):
if not segment:
return parent_path
if parent_path == "root":
return segment
return f"{parent_path}/{segment}"
def walk(nodes, parent_path="root"):
for node in nodes:
if not node:
continue
if isinstance(node, dict) and node.get("type") == "integration_placeholder":
kind = _normalize_placeholder_kind(node.get("integration_kind"))
if kind:
rows.append(
{
"custom_edit_url": kind,
"sidebar_label": None,
"learn_status": None,
"learn_rel_path": None,
"keywords": None,
"description": None,
}
)
continue
if not isinstance(node, dict):
continue
meta = node.get("meta")
if not isinstance(meta, dict):
continue
label = meta.get("label")
has_items = isinstance(node.get("items"), list)
explicit_path = meta.get("path")
if has_items:
segment = explicit_path if explicit_path else label
current_path = join_path(parent_path, segment)
else:
if explicit_path:
current_path = join_path(parent_path, explicit_path)
elif parent_path == "root":
current_path = "root"
else:
current_path = parent_path
edit_url = meta.get("edit_url")
if isinstance(edit_url, str) and edit_url.strip():
rows.append(
{
"custom_edit_url": edit_url,
"sidebar_label": label,
"learn_status": "Published",
"learn_rel_path": current_path,
"keywords": meta.get("keywords"),
"description": meta.get("description"),
}
)
if has_items:
walk(node.get("items"), current_path)
walk(sidebar)
return pd.DataFrame(rows, columns=MAP_COLUMNS)
def load_map_sidebar_order(map_path):
"""Build sibling ordering map from map.yaml traversal order.
Returns:
- order_map: dict keyed by (parent_path, child_name) with sidebar positions
assigned as 10, 20, 30, ... within each parent scope.
- doc_scope_map: dict keyed by edit_url with resolved (parent_path, child_name)
for rows originating from map.yaml documents.
"""
with open(map_path, "r", encoding="utf-8") as fh:
data = yaml.safe_load(fh) or {}
sidebar = data.get("sidebar")
if not isinstance(sidebar, list):
return {}, {}
order = {}
doc_scope = {}
def join_path(parent_path, segment):
if not segment:
return parent_path
if parent_path == "root":
return segment
return f"{parent_path}/{segment}"
def walk(nodes, parent_parts):
sibling_index = 0
for node in nodes:
if not isinstance(node, dict):
continue
if node.get("type") == "integration_placeholder":
continue
meta = node.get("meta") or {}
label = meta.get("label")
if not isinstance(label, str) or not label.strip():
continue
has_items = isinstance(node.get("items"), list)
explicit_path = meta.get("path")
if has_items:
child_name = explicit_path if explicit_path else label
else:
if explicit_path:
child_name = explicit_path
else:
child_name = label
if not isinstance(child_name, str) or not child_name.strip():
continue
sibling_index += 1
parent_key = "/".join(parent_parts) if parent_parts else "root"
order.setdefault((parent_key, child_name), sibling_index * 10)
edit_url = meta.get("edit_url")
if isinstance(edit_url, str) and edit_url.strip():
if has_items:
doc_scope[edit_url] = (parent_key, child_name)
else:
if explicit_path:
leaf_parent = join_path(parent_key, child_name)
elif parent_key == "root":
leaf_parent = "root"
else:
leaf_parent = parent_key
doc_scope[edit_url] = (leaf_parent, label)
if has_items:
walk(node.get("items"), parent_parts + [child_name])
walk(sidebar, [])
return order, doc_scope
def _source_corpus_sha256(docs_root):
"""Hash the non-generated corpus that a grid recovery is allowed to use."""
docs_root = _validate_docs_tree(docs_root)
digest = hashlib.sha256()
for path in sorted(candidate for candidate in docs_root.rglob("*") if candidate.is_file()):
if _is_generated_grid_page(path) or _is_generated_category_file(path):
continue
relative = path.relative_to(docs_root).as_posix().encode("utf-8")
content = _read_regular_bytes(path)
digest.update(len(relative).to_bytes(8, "big"))
digest.update(relative)
digest.update(len(content).to_bytes(8, "big"))
digest.update(content)
return digest.hexdigest()
def write_sidebar_order_state(
order_map, map_path, docs_root, state_path=SIDEBAR_ORDER_STATE_PATH
):
"""Persist the exact full-ingest identity needed by offline grid recovery."""
_validate_docs_tree(docs_root)
source_bytes = _read_regular_bytes(map_path)
entries = [
{
"parent_path": parent_path,
"child_name": child_name,
"position": position,
}
for (parent_path, child_name), position in sorted(
order_map.items(), key=lambda item: (item[0][0], item[1], item[0][1])
)
]
payload = {
"schema_version": 1,
"source": SIDEBAR_ORDER_STATE_SOURCE,
"source_sha256": hashlib.sha256(source_bytes).hexdigest(),
"source_corpus_sha256": _source_corpus_sha256(docs_root),
"order": entries,
}
payload["full_ingest_identity_sha256"] = _sidebar_state_identity(payload)
state_content = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
_atomic_write_text(state_path, state_content, encoding="utf-8")
checksum = hashlib.sha256(state_content.encode("utf-8")).hexdigest()
checksum_path = _sidebar_state_checksum_path(state_path)
_atomic_write_text(
checksum_path,
f"{checksum} {Path(state_path).name}\n",
encoding="utf-8",
)
def _sidebar_state_identity(payload):
identity_payload = {
key: payload[key]
for key in sorted(SIDEBAR_ORDER_STATE_KEYS - {"full_ingest_identity_sha256"})
}
canonical = json.dumps(
identity_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
).encode("utf-8")
return hashlib.sha256(canonical).hexdigest()
def _sidebar_state_checksum_path(state_path):
state_path = Path(state_path)
return state_path.with_name(f"{state_path.name}.sha256")
def _read_verified_sidebar_state(state_path):
state_path = Path(state_path)
state_bytes = _read_regular_bytes(state_path)
checksum_path = _sidebar_state_checksum_path(state_path)
checksum_text = _read_regular_text(checksum_path, encoding="utf-8")
match = re.fullmatch(r"([0-9a-f]{64}) ([^\r\n]+)\n", checksum_text)
if match is None or match.group(2) != state_path.name:
raise ValueError(f"Invalid generated sidebar order checksum: {checksum_path}")
actual = hashlib.sha256(state_bytes).hexdigest()
if not secrets.compare_digest(match.group(1), actual):
raise ValueError(f"Generated sidebar order checksum mismatch: {state_path}")
return state_bytes.decode("utf-8")
def load_sidebar_order_state(state_path=SIDEBAR_ORDER_STATE_PATH, docs_root=None):
"""Load and validate the committed order used by grid-only recovery."""
payload = json.loads(_read_verified_sidebar_state(state_path))
if (
not isinstance(payload, dict)
or set(payload) != SIDEBAR_ORDER_STATE_KEYS
or payload.get("schema_version") != 1
or payload.get("source") != SIDEBAR_ORDER_STATE_SOURCE
or not isinstance(payload.get("order"), list)
or re.fullmatch(r"[0-9a-f]{64}", payload.get("source_sha256", "")) is None
or re.fullmatch(
r"[0-9a-f]{64}", payload.get("source_corpus_sha256", "")
)
is None
or re.fullmatch(
r"[0-9a-f]{64}", payload.get("full_ingest_identity_sha256", "")
)
is None
):
raise ValueError(f"Invalid generated sidebar order state: {state_path}")
if payload["full_ingest_identity_sha256"] != _sidebar_state_identity(payload):
raise ValueError(f"Invalid full-ingest identity in {state_path}")
order = {}
positions_by_parent = {}
for entry in payload["order"]:
if not isinstance(entry, dict) or set(entry) != SIDEBAR_ORDER_ENTRY_KEYS:
raise ValueError(f"Invalid sidebar order entry in {state_path}")
parent_path = entry.get("parent_path")
child_name = entry.get("child_name")
position = entry.get("position")
if (
not isinstance(parent_path, str)
or not parent_path
or not isinstance(child_name, str)
or not child_name
or type(position) is not int
or position <= 0
):
raise ValueError(f"Invalid sidebar order entry in {state_path}: {entry}")
key = (parent_path, child_name)
if key in order:
raise ValueError(f"Duplicate sidebar order entry in {state_path}: {key}")
parent_positions = positions_by_parent.setdefault(parent_path, set())
if position in parent_positions:
raise ValueError(
f"Duplicate sidebar order position in {state_path}: "
f"{parent_path} position {position}"
)
parent_positions.add(position)
order[key] = position
if docs_root is not None:
actual_corpus_sha256 = _source_corpus_sha256(docs_root)
if actual_corpus_sha256 != payload["source_corpus_sha256"]:
raise ValueError(
"Generated sidebar order state does not match the current source "
f"corpus: {state_path}"
)
return order
def _generated_category_payload(label, position):
return {
"label": label,
"position": position,
"customProps": {"generated_by": GENERATED_CATEGORY_OWNER},
}
def _is_generated_category_file(path):
try:
payload = json.loads(_read_regular_text(path, encoding="utf-8"))
except (FileNotFoundError, UnicodeDecodeError, json.JSONDecodeError):
return False
custom_props = payload.get("customProps") if isinstance(payload, dict) else None
return (
isinstance(custom_props, dict)
and custom_props.get("generated_by") == GENERATED_CATEGORY_OWNER
)
def ensure_category_json_for_dirs(docs_root):
"""
For every directory under docs_root:
- if <dir>/<basename(dir)>.mdx exists => treat as category overview; do nothing
- else create or overwrite _category_.json using map-derived sibling order
"""
docs_root = _validate_docs_tree(docs_root)
for dirpath, dirnames, filenames in os.walk(docs_root):
abs_dir = os.path.abspath(dirpath)
abs_root = os.path.abspath(docs_root)
base = os.path.basename(os.path.normpath(dirpath))
if abs_dir == abs_root:
continue
category_json = os.path.join(dirpath, "_category_.json")
if os.path.exists(os.path.join(dirpath, f"{base}.mdx")):
if _is_generated_category_file(category_json):
_safe_unlink(category_json, docs_root)
continue
mdx_files = [f for f in filenames if f.lower().endswith(".mdx")]
if not mdx_files:
if _is_generated_category_file(category_json):
_safe_unlink(category_json, docs_root)
continue
rel_parts = Path(dirpath).relative_to(Path(docs_root)).parts
parent_key = "/".join(rel_parts[:-1]) if len(rel_parts) > 1 else "root"
child_key = rel_parts[-1] if rel_parts else base
map_pos = MAP_SIDEBAR_ORDER.get((parent_key, child_key))
if map_pos is not None:
cat_pos = map_pos
else:
# Fallback: use alphabetical-last bucket for unmapped categories
cat_pos = 9999
if os.path.exists(category_json) and not _is_generated_category_file(
category_json
):
continue
payload = _generated_category_payload(base, cat_pos)
_atomic_write_text(
category_json,
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
docs_root=docs_root,
encoding="utf-8",
)
print(f"CREATE {category_json} with position={cat_pos} label='{base}'")
def _read_sidebar_label(path_to_file):
"""Read sidebar_label from frontmatter; fallback to file stem."""
try:
content = _read_regular_text(path_to_file, encoding="utf-8")
except OSError:
return Path(path_to_file).stem
match = SIDEBAR_LABEL_RE.search(content)
if match:
return match.group(1).strip()
return Path(path_to_file).stem
def _set_sidebar_position(path_to_file, sidebar_position, docs_root):
"""Upsert sidebar_position in frontmatter."""
path_obj = Path(path_to_file)
content = _read_regular_text(path_obj, encoding="utf-8")
if POS_RE.search(content):
updated = POS_RE.sub(
f'sidebar_position: "{sidebar_position}"', content, count=1
)
_atomic_write_text(path_obj, updated, docs_root=docs_root, encoding="utf-8")
return
lines = content.splitlines()
if lines and lines[0].strip() == "---":
lines.insert(1, f'sidebar_position: "{sidebar_position}"')
_atomic_write_text(
path_obj, "\n".join(lines) + "\n", docs_root=docs_root, encoding="utf-8"
)
def _set_category_position(path_to_file, label, sidebar_position, docs_root):
"""Upsert position in _category_.json preserving label."""
path_obj = Path(path_to_file)
try:
payload = json.loads(_read_regular_text(path_obj, encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
payload = {}
if not isinstance(payload, dict):
payload = {}
payload["label"] = label
payload["position"] = sidebar_position
_atomic_write_text(
path_obj,
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
docs_root=docs_root,
encoding="utf-8",
)
def normalize_sidebar_positions_by_parent(docs_root):
"""Assign unique sibling positions per parent scope.
Uses map-derived sibling rank when available, then falls back to alphabetical
ordering for injected/unknown siblings.
"""
docs_root = _validate_docs_tree(docs_root)
for dirpath, dirnames, filenames in os.walk(docs_root):
rel_parts = Path(dirpath).relative_to(Path(docs_root)).parts
parent_key = "/".join(rel_parts) if rel_parts else "root"
entries = []
# Direct child docs of this scope (exclude overview page for this scope)
for fn in sorted(filenames):
if not fn.lower().endswith(".mdx"):
continue
file_path = Path(dirpath) / fn
if rel_parts and file_path.stem == rel_parts[-1]:
continue
# Pagination artifacts are linked by GridPagination and deliberately
# hidden from the sidebar. They must not consume sibling positions.
if _is_generated_grid_page(file_path):
continue
label = _read_sidebar_label(file_path)