fix bug 176: preserve YAML comments when reordering items by matching content instead of position

This commit is contained in:
michael 2024-12-10 18:24:23 +00:00
parent 01906205f0
commit 8a2217c2b9

View file

@ -236,25 +236,30 @@ export function copyYAMLComments(doc : Document, src : Document) {
/** /**
* Copy yaml comments from srcItems to items * Copy yaml comments from srcItems to items
* Typescript is super annoying here, so I have to use any here * Attempts to preserve comments by matching content rather than just array indices
* TODO: Since comments are belong to the array index, the comments will be lost if the order of the items is changed or removed or added.
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
function copyYAMLCommentsItems(items : any, srcItems : any) { function copyYAMLCommentsItems(items: any, srcItems: any) {
if (!items || !srcItems) { if (!items || !srcItems) {
return; return;
} }
// First pass - try to match items by their content
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const item : any = items[i]; const item: any = items[i];
// Try to find matching source item by content
const srcIndex = srcItems.findIndex((srcItem: any) =>
JSON.stringify(srcItem.value) === JSON.stringify(item.value) &&
JSON.stringify(srcItem.key) === JSON.stringify(item.key)
);
if (srcIndex !== -1) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const srcItem : any = srcItems[i]; const srcItem: any = srcItems[srcIndex];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (!srcItem) { const nextSrcItem: any = srcItems[srcIndex + 1];
continue;
}
if (item.key && srcItem.key) { if (item.key && srcItem.key) {
item.key.comment = srcItem.key.comment; item.key.comment = srcItem.key.comment;
@ -265,6 +270,20 @@ function copyYAMLCommentsItems(items : any, srcItems : any) {
item.comment = srcItem.comment; item.comment = srcItem.comment;
} }
// Handle comments between array items
if (nextSrcItem && nextSrcItem.commentBefore) {
if (items[i + 1]) {
items[i + 1].commentBefore = nextSrcItem.commentBefore;
}
}
// Handle trailing comments after array items
if (srcItem.value && srcItem.value.comment) {
if (item.value) {
item.value.comment = srcItem.value.comment;
}
}
if (item.value && srcItem.value) { if (item.value && srcItem.value) {
if (typeof item.value === "object" && typeof srcItem.value === "object") { if (typeof item.value === "object" && typeof srcItem.value === "object") {
item.value.comment = srcItem.value.comment; item.value.comment = srcItem.value.comment;
@ -276,6 +295,7 @@ function copyYAMLCommentsItems(items : any, srcItems : any) {
} }
} }
} }
}
} }
/** /**