-
I have a map and, somewhere else, I have some anchors defined. I would like to change the name of an anchor, then change the alias that references it to use new name. This works. But I would like to also add a new entry to the map, and make it reference that anchor. Here is what I have so far: import YAML, { isAlias, isMap } from "yaml";
const TEST_YAML_STRING = `
my_custom_schedules:
custom_schedule: &custom_schedule_alias
foo: bar
my_config:
default: &default
foo: baz
my-c-005: *default
my-c-006: *custom_schedule_alias
`;
const document = YAML.parseDocument(TEST_YAML_STRING);
const customSchedules = document.get("my_custom_schedules");
if (isMap(customSchedules)) {
const customSchedule = customSchedules.get("custom_schedule");
if (isMap(customSchedule)) {
// change the name of the anchor
customSchedule.anchor = "new_custom_schedule_anchor";
}
}
const config = document.get("my_config");
if (isMap(config)) {
// change the existing C006 alias to point to the new anchor
const myC006 = config.get("my-c-006");
if (isAlias(myC006)) {
myC006.source = "new_custom_schedule_anchor";
}
// create a new alias for C007 to point to the anchor
config.add({ key: "my-c-007", value: "???" });
}
const documentStr = document.toString(); I would expect the following: my_custom_schedules:
custom_schedule: &new_custom_schedule_anchor
foo: bar
my_config:
default: &default
foo: baz
my-c-005: *default
my-c-006: *new_custom_schedule_anchor
my-c-007: *new_custom_schedule_anchor But how do I add |
Beta Was this translation helpful? Give feedback.
Answered by
slhck
Apr 29, 2023
Replies: 1 comment 3 replies
-
I'd use a visitor. Something like this ought to work, though I've not tested it: import { type Document, visit } from 'yaml'
function renameAlias(doc: Document, prev: string, next: string) {
visit(doc, {
Alias(_, alias) {
if (alias.source === prev) alias.source = next
},
Node(_, node) {
if (node.anchor === prev) node.anchor = next
}
)}
} |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, I figured that I'd need it, but the exact steps required weren't obvious for me from the given examples.
After fumbling around a lot, here is the simplest way I found to create a new alias:
Here is the fully working example from the original question — note that I forced casts of the return values from
.get
which is not recomm…