| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
from dataclasses import replace |
| 18 |
from typing import Any |
| 19 |
|
| 20 |
from . import data as res |
| 21 |
|
| 22 |
RS = res.Section[Any, Any] |
| 23 |
RE = res.Entry[Any, Any] |
| 24 |
|
| 25 |
|
| 26 |
def add_entries( |
| 27 |
target: res.Resource[res.V, res.M], |
| 28 |
source: res.Resource[res.V, res.M], |
| 29 |
*, |
| 30 |
use_source_entries: bool = False, |
| 31 |
) -> int: |
| 32 |
""" |
| 33 |
Modifies `target` by adding entries from `source` that are not already present in `target`. |
| 34 |
Standalone comments are not added. |
| 35 |
If `use_source_entries` is set, |
| 36 |
entries from `source` override those in `target` when they differ, |
| 37 |
as well as updating section comments and metadata from `source`. |
| 38 |
|
| 39 |
Entries are not copied, so further changes will be reflected in both resources. |
| 40 |
|
| 41 |
Returns a count of added or changed entries and sections. |
| 42 |
""" |
| 43 |
|
| 44 |
change_count = 0 |
| 45 |
cur_tgt_section: RS | None = None |
| 46 |
for src_section in source.sections: |
| 47 |
tgt_match = [s for s in target.sections if s.id == src_section.id] |
| 48 |
prev_pos: tuple[RS, int] | None = None |
| 49 |
new_entries: list[RE | res.Comment] = [] |
| 50 |
for entry in src_section.entries: |
| 51 |
if isinstance(entry, res.Entry): |
| 52 |
target_pos = next( |
| 53 |
( |
| 54 |
(s, i) |
| 55 |
for s in tgt_match |
| 56 |
for i, e in enumerate(s.entries) |
| 57 |
if isinstance(e, res.Entry) and e.id == entry.id |
| 58 |
), |
| 59 |
None, |
| 60 |
) |
| 61 |
sc = src_section.comment |
| 62 |
sm = src_section.meta |
| 63 |
if target_pos: |
| 64 |
cur_tgt_section, idx = target_pos |
| 65 |
if use_source_entries: |
| 66 |
if cur_tgt_section.entries[idx] != entry: |
| 67 |
cur_tgt_section.entries[idx] = entry |
| 68 |
change_count += 1 |
| 69 |
if cur_tgt_section.comment != sc or cur_tgt_section.meta != sm: |
| 70 |
cur_tgt_section.comment = sc |
| 71 |
cur_tgt_section.meta = sm |
| 72 |
change_count += 1 |
| 73 |
prev_pos = target_pos |
| 74 |
else: |
| 75 |
|
| 76 |
|
| 77 |
change_count += 1 |
| 78 |
if prev_pos and prev_pos[0].comment == sc: |
| 79 |
|
| 80 |
|
| 81 |
idx = prev_pos[1] + 1 |
| 82 |
prev_pos[0].entries.insert(idx, entry) |
| 83 |
prev_pos = (prev_pos[0], idx) |
| 84 |
else: |
| 85 |
ts = next((s for s in tgt_match if s.comment == sc), None) |
| 86 |
if ts: |
| 87 |
|
| 88 |
|
| 89 |
ts.entries.append(entry) |
| 90 |
prev_pos = (ts, len(ts.entries) - 1) |
| 91 |
else: |
| 92 |
|
| 93 |
new_entries.append(entry) |
| 94 |
prev_pos = None |
| 95 |
if new_entries: |
| 96 |
idx = target.sections.index(cur_tgt_section) + 1 if cur_tgt_section else 0 |
| 97 |
cur_tgt_section = replace(src_section, entries=new_entries) |
| 98 |
target.sections.insert(idx, cur_tgt_section) |
| 99 |
return change_count |