Skip to content

Commit

Permalink
Ensure Anchor name uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
wwkimball committed Oct 29, 2020
1 parent 981ed0d commit 4694f5a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
21 changes: 11 additions & 10 deletions yamlpath/commands/yaml_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,6 @@
values and/or decrypt old values before checking them.
Copyright 2018, 2019, 2020 William W. Kimball, Jr. MBA MSIS
DEVELOPMENT GOALS:
* --aliasof sets --change to *anchor_name
* Let --aliasof and --change be identical when --anchor is also set as a way to
just rename an existing Anchor.
* When --anchor conflicts with an existing name, bail out (because a deliberate
rename of the other Anchor is possible AND because --aliasof can be set to
the other pre-existing Anchor).
"""
import sys
import tempfile
Expand All @@ -27,6 +19,7 @@
from os.path import isfile, exists
from shutil import copy2, copyfileobj
from pathlib import Path
from typing import Any, Dict

from yamlpath import __version__ as YAMLPATH_VERSION
from yamlpath.common import Anchors
Expand Down Expand Up @@ -453,16 +446,24 @@ def _alias_nodes(
anchor_node)
anchor_node = anchor_coord.parent[anchor_coord.parentref]

known_anchors: Dict[str, Any] = {}
Anchors.scan_for_anchors(processor.data, known_anchors)

if anchor_name:
# Rename any pre-existing anchor or set an original anchor name
# Rename any pre-existing anchor or set an original anchor name; the
# assigned name must be unique!
if anchor_name in known_anchors:
log.critical(
"Anchor names must be unique within YAML documents. Anchor"
" name, {}, is already used.".format(anchor_name))
anchor_node.yaml_set_anchor(anchor_name, always_dump=True)
elif anchor_node.anchor.value:
# The source node already has an anchor name
anchor_name = anchor_node.anchor.value
else:
# An orignial, unique-to-the-document anchor name must be generated
new_anchor = Anchors.generate_unique_anchor_name(
processor.data, anchor_coord)
processor.data, anchor_coord, known_anchors)
anchor_node.yaml_set_anchor(new_anchor, always_dump=True)

for node_coord in assign_to_nodes:
Expand Down
2 changes: 1 addition & 1 deletion yamlpath/common/anchors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Copyright 2020 William W. Kimball, Jr. MBA MSIS
"""
from typing import Any, Dict, List
from typing import Any, Dict

from ruamel.yaml.comments import CommentedSeq, CommentedMap

Expand Down

0 comments on commit 4694f5a

Please sign in to comment.