topmark.processors.base¶
topmark / processors / base
Header processor base module for TopMark's header processing pipeline.
This module defines the HeaderProcessor base class, which provides a framework for processing file headers in different file types. It includes logic for scanning, parsing, and rendering header fields according to comment styles and file extensions.
The module also supports associating processors with file types to enable flexible, extensible header processing in the TopMark pipeline.
Placement strategies¶
TopMark supports two complementary placement strategies:
- Line-based insertion (default): processors return a line anchor from
get_header_insertion_index(); pipeline steps usecompute_insertion_anchor()as the façade to obtain that anchor. - Character-offset insertion (for positional formats like XML/HTML): processors
return
NO_LINE_ANCHORfromget_header_insertion_index()and implementget_header_insertion_char_offset()to compute a byte/character offset.
The pipeline first attempts text-based insertion when a char offset is provided; otherwise it falls back to the line-based strategy using the computed anchor.
RuntimeConfigLike ¶
Bases: Protocol
Minimal structural subset of FrozenConfig required by HeaderProcessor.
This protocol keeps topmark.processors.base
independent from the full runtime FrozenConfig
model and avoids import cycles. Only the fields actually consumed by
render_header_lines()
are included here.
ProcessingContextLike ¶
Bases: Protocol
Minimal structural subset of ProcessingContext required by HeaderProcessor.
This protocol keeps topmark.processors.base independent from the full
pipeline context model and avoids import cycles. Only the views bundle and
diagnostic sink methods needed by processor helpers are included here.
HeaderProcessor ¶
HeaderProcessor(
*,
block_prefix=None,
block_suffix=None,
line_prefix=None,
line_suffix=None,
line_indent=None,
header_indent=None,
)
Base class for header processors that handle specific file types.
A header processor knows how to find, render, and modify TopMark
headers for one concrete topmark.filetypes.model.FileType.
The registry binds a processor instance to a file type at runtime (proc.file_type = ft),
and TopMark uses that pairing during scanning and updates.
Responsibilities
- Scanning: Locate existing headers via start/end markers and comment
affixes (see
get_header_bounds,line_has_directive). - Parsing: Extract key→value pairs from the header payload (see
parse_fields). - Rendering: Emit preamble/fields/postamble with proper comment syntax
(see
render_preamble_lines,render_header_lines,render_postamble_lines). - Placement policy: Determine insertion points; default is
shebang-aware for languages like Python (see
get_header_insertion_index). - Update/strip helpers: Prepare insertions and removals in a way that
preserves surrounding whitespace (see
prepare_header_for_insertion,strip_header_block).
What this class does not do:
- Content-based recognition. Deciding which file type a path belongs
to is the role of topmark.filetypes.model.FileType via
FileType.content_matcher. The processor assumes it is already
associated with the correct file type.
Indentation semantics
header_indent: indentation before the line prefix (used to preserve existing indentation when replacing nested/indented headers).line_indent: indentation after the line prefix (applied to the header field lines).
Extension points
Subclasses typically set comment delimiters (line_prefix,
line_suffix, block_prefix, block_suffix) and may override any of
the hooks documented below to support format-specific behavior (e.g., XML
prolog placement or Markdown fences).
Placement strategies
- Line-based (default): override
get_header_insertion_index()if needed. Pipeline steps callcompute_insertion_anchor()as a stable façade. - Character-offset (XML/HTML-like): return
NO_LINE_ANCHORfromget_header_insertion_index()and implementget_header_insertion_char_offset(); the pipeline will prefer this path.
Public API note
In the stable public surface, consider typing against a minimal protocol rather than this concrete base if you are authoring plugins. The registry binds processors to file types and exposes read-only metadata for common integrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block_prefix
|
str | None
|
The prefix string for block-style header start. |
None
|
block_suffix
|
str | None
|
The suffix string for block-style header end. |
None
|
line_prefix
|
str | None
|
The prefix string for each line within the header block. |
None
|
line_suffix
|
str | None
|
The suffix string for each line within the header block. |
None
|
line_indent
|
str | None
|
The indentation applied to header field lines after
the comment prefix (e.g., spaces after |
None
|
header_indent
|
str | None
|
The indentation applied before the comment prefix; used to preserve existing leading indentation when replacing an indented header block inside a document (e.g., nested JSONC). |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
str
|
Processor namespace class metadata. |
local_key |
str
|
Unique processor identity class metadata within its namespace. |
description |
str
|
Human-readable processor description class metadata. |
file_type |
FileType | None
|
The |
block_prefix |
str
|
The prefix string for block-style header start. |
block_suffix |
str
|
The suffix string for block-style header end. |
line_prefix |
str
|
The prefix string for each line within the header block. |
line_suffix |
str
|
The suffix string for each line within the header block. |
line_indent |
str
|
The indentation applied to header field lines after
the comment prefix (e.g., spaces after |
header_indent |
str
|
The indentation applied before the comment prefix; used to preserve existing leading indentation when replacing an indented header block inside a document (e.g., nested JSONC). |
Source code in src/topmark/processors/base.py
qualified_key
property
¶
Return the qualified identity key for this processor.
Format: "<namespace>:<local_key>".
parse_fields ¶
Parse key-value pairs from the detected header block (view-based).
This implementation expects the scanner to have populated
context.header with an outer slice (markers included). It searches
within context.header.lines for the first START marker and the next END
marker, then parses only the payload lines between them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
ProcessingContextLike
|
Pipeline context where |
required |
Returns:
| Type | Description |
|---|---|
HeaderParseResult
|
Parsed mapping and per-line success/error counters. |
Notes
- Comment affixes (
line_prefix/line_suffix) are stripped per line. - Malformed field lines add diagnostics but do not mutate
context.status.header(handled by the scanner). - Subclasses may override to support multi-line fields or alternate syntax.
Source code in src/topmark/processors/base.py
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 | |
render_preamble_lines ¶
render_preamble_lines(
*,
newline_style,
block_prefix=None,
line_prefix=None,
line_suffix=None,
header_indent="",
)
Render the TopMark preamble lines for the current processor.
The preamble consists of
1) the block comment opener (when configured),
2) the TOPMARK_START_MARKER directive line, and
3) an intentional blank line following the start marker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
newline_style
|
str
|
Newline characters to append to each rendered line. |
required |
block_prefix
|
str | None
|
Optional override for the block prefix; defaults to
the instance's |
None
|
line_prefix
|
str | None
|
Optional override for the line prefix; defaults to
the instance's |
None
|
line_suffix
|
str | None
|
Optional override for the line suffix; defaults to
the instance's |
None
|
header_indent
|
str
|
The indentation applied before the comment prefix; used to preserve existing leading indentation when replacing an indented header block inside a document (e.g., nested JSONC). |
''
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Preamble lines (each ending with |
Source code in src/topmark/processors/base.py
render_postamble_lines ¶
render_postamble_lines(
*,
newline_style,
block_suffix=None,
line_prefix=None,
line_suffix=None,
header_indent="",
)
Render the TopMark postamble lines for the current processor.
The postamble consists of
1) an intentional blank line before the end marker,
2) the TOPMARK_END_MARKER directive line, and
3) the block comment closer (when configured).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
newline_style
|
str
|
Newline characters to append to each rendered line. |
required |
block_suffix
|
str | None
|
Optional override for the block suffix; defaults to
the instance's |
None
|
line_prefix
|
str | None
|
Optional override for the line prefix; defaults to
the instance's |
None
|
line_suffix
|
str | None
|
Optional override for the line suffix; defaults to
the instance's |
None
|
header_indent
|
str
|
The indentation applied before the comment prefix; used to preserve existing leading indentation when replacing an indented header block inside a document (e.g., nested JSONC). |
''
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Postamble lines (each ending with |
Source code in src/topmark/processors/base.py
render_header_lines ¶
render_header_lines(
header_values,
config,
newline_style,
block_prefix_override=None,
block_suffix_override=None,
line_prefix_override=None,
line_suffix_override=None,
line_indent_override=None,
header_indent_override=None,
)
Render a header block from configuration, template, and overrides.
This method generates a header string using the configuration's header fields and values, optionally overridden by provided header_list and custom_headers. It respects alignment and raw_header settings from the configuration to format the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header_values
|
Mapping[str, str]
|
Mapping of header fields to render. |
required |
config
|
RuntimeConfigLike
|
TopMark configuration (defines header fields and options). |
required |
newline_style
|
str
|
Newline style ( |
required |
block_prefix_override
|
str | None
|
Optional block prefix override. |
None
|
block_suffix_override
|
str | None
|
Optional block suffix override. |
None
|
line_prefix_override
|
str | None
|
Optional line prefix override. |
None
|
line_suffix_override
|
str | None
|
Optional line suffix override. |
None
|
line_indent_override
|
str | None
|
Optional indentation override after
the comment prefix, applied to header field lines (defaults to the
processor's |
None
|
header_indent_override
|
str | None
|
Optional indentation override before the comment prefix, applied to complete header lines (used to preserve existing leading indentation on replace). |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Rendered header lines ending with |
Source code in src/topmark/processors/base.py
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 | |
compute_insertion_anchor ¶
Return a stable line-based insertion anchor for the pipeline.
This small facade exists so pipeline steps have a single, stable
entry point for line-based placement. By default, it simply
delegates to get_header_insertion_index.
Processors that insert by character offset (e.g., XML/HTML) should
override get_header_insertion_index to return
NO_LINE_ANCHOR, which this method will propagate unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
list[str]
|
Full file content split into lines. |
required |
Returns:
| Type | Description |
|---|---|
int
|
A 0-based line index where a header would be inserted, or |
int
|
line-based anchoring is not used. |
Source code in src/topmark/processors/base.py
get_header_insertion_index ¶
Determine where to insert the header based on file type policy.
Default behavior is shebang-aware:
- If the file type policy declares supports_shebang=True and the first line
starts with #!, insert the header after the shebang (and optional encoding
line when encoding_line_regex is provided).
- Otherwise, insert at the top of file (index 0).
If inserting after a preamble and the next line is already blank, consume exactly one existing blank line so that a single blank separates the preamble from the header.
Subclasses may override this when a format imposes different placement rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_lines
|
list[str]
|
Lines from the file being processed. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Index at which to insert the TopMark header, or |
int
|
index can be found. |
Source code in src/topmark/processors/base.py
line_has_directive ¶
Check whether a line contains the directive with the expected affixes.
This method is used by get_header_bounds() to locate header start/end markers.
Subclasses may override this method for more flexible or format-specific matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
The line of text to check (whitespace is trimmed internally). |
required |
directive
|
str
|
The directive string to look for. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
otherwise |
Source code in src/topmark/processors/base.py
validate_header_location ¶
Validate that a detected header is at an acceptable location.
The default policy accepts a candidate header only when its start line is exactly at the computed anchor or within a small proximity window around it. Subclasses may override this to enforce format-specific constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
list[str]
|
Full file content split into lines. |
required |
header_start_idx
|
int
|
0-based index of the candidate header's first line. |
required |
header_end_idx
|
int
|
0-based index of the candidate header's last line (inclusive). |
required |
anchor_idx
|
int
|
0-based index where a header would be inserted per policy. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
otherwise |
Notes
The proximity window can be tuned per file type by defining
scan_window_before and scan_window_after on the associated
FileType. Defaults are 0 and 2, respectively.
Source code in src/topmark/processors/base.py
get_header_bounds ¶
Locate the TopMark header bounds as (start_idx, end_idx), inclusive.
This method first performs a marker preflight to catch malformed
shapes (e.g., lone :end, lone :start, multiple or reversed markers).
It then applies format-aware detection and proximity validation to return
a valid span when present.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
Logical file lines ( |
required |
newline_style
|
str
|
Dominant newline style ( |
required |
Returns:
| Type | Description |
|---|---|
HeaderBounds
|
A discriminated result:
- |
Notes
Subclasses may override this method to provide format-specific detection and location validation but should preserve the discriminated-union semantics of the return value.
Source code in src/topmark/processors/base.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 | |
strip_header_block ¶
Remove the TopMark header block and return the updated file image.
This method supports two detection modes:
-
Policy-aware detection (preferred): If
spanis not provided, the processor callsget_header_bounds(lines, newline_style)to locate a valid header near the computed insertion anchor. This respects file-type placement rules (shebang handling, XML prolog, Markdown fences, etc.). -
Permissive fallback (best-effort): If policy-aware detection fails, the method performs a lightweight scan for the first
START..ENDmarker pair anywhere in the file. The scan accepts either exact directive matches (prefix/suffix aware) or marker substrings appearing inside single-line comment wrappers (e.g.,<!-- TOPMARK_START_MARKER -->for XML/HTML/Markdown). This covers older files or content transformed by formatters.
When a header is removed at the very top of the file (start == 0), the
method trims exactly one leading blank line that may be left behind by the
removal to avoid introducing an extra gap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
list[str]
|
Full file content split into lines (each typically ending with a newline). |
required |
span
|
tuple[int, int] | None
|
Optional inclusive |
None
|
newline_style
|
str
|
Newline style ( |
'\n'
|
ends_with_newline
|
bool | None
|
If known, whether the original file ended with a newline.
If |
None
|
Returns:
| Type | Description |
|---|---|
StripHeaderResult
|
Structured strip result containing the updated file lines, the |
StripHeaderResult
|
inclusive removed span when a header was removed, and the diagnostic |
StripHeaderResult
|
describing the outcome. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If policy-aware bounds detection reports a SPAN but omits start/end indices. |
Source code in src/topmark/processors/base.py
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 | |
prepare_header_for_insertion ¶
prepare_header_for_insertion(
*,
original_lines,
insert_index,
rendered_header_lines,
newline_style,
)
Adjust whitespace around the header for line-based insertion.
Default implementation returns rendered_header_lines unchanged. Subclasses
and mixins can override to add/remove leading or trailing blank lines
depending on surrounding context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_lines
|
list[str]
|
The original file lines. |
required |
insert_index
|
int
|
Line index at which the header will be inserted. |
required |
rendered_header_lines
|
list[str]
|
The header lines to insert. |
required |
newline_style
|
str
|
Newline style ( |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Possibly modified header lines to insert at |
Source code in src/topmark/processors/base.py
get_header_insertion_char_offset ¶
Return a character offset for text-based insertion, or None.
This hook enables processors to compute non line-based insertion points
(e.g., XML prolog-aware placement when declaration/DOCTYPE and content appear
on the same line). Returning None signals that the pipeline should fall
back to the standard line-based insertion path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_text
|
str
|
Full file content as a single string. |
required |
Returns:
| Type | Description |
|---|---|
int | None
|
0-based character offset at which to insert, or |
int | None
|
insertion strategy. |
Source code in src/topmark/processors/base.py
prepare_header_for_insertion_text ¶
prepare_header_for_insertion_text(
*,
original_text,
insert_offset,
rendered_header_text,
newline_style,
)
Adjust the rendered header text before text-based insertion.
Subclasses may override this to add or trim surrounding newlines so the header block sits on its own lines when performing text-based insertion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_text
|
str
|
Full file content as a single string. |
required |
insert_offset
|
int
|
0-based character offset where the header will be inserted. |
required |
rendered_header_text
|
str
|
The header block as a single string. |
required |
newline_style
|
str
|
Newline style ( |
required |
Returns:
| Type | Description |
|---|---|
str
|
The (possibly modified) header text to splice into |
str
|
|