Skip to content

Commit

Permalink
Avoid comment duplication in block scalars (#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
pascalre committed Oct 22, 2023
1 parent 1238bc7 commit cd793e4
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/processor/comment-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,16 @@ export class CommentProcessor {
insert(comment: string[]) {
const indexOfComment = this.getIndexOfString(comment[1])
if (CommentProcessor.isCommentFound(indexOfComment)) {
const textAfter = this.text.slice(indexOfComment)
const textBefore = this.text.slice(0, indexOfComment)
this.insertIfNotContained(comment)
}
}

insertIfNotContained(comment: string[]) {
const indexOfComment = this.getIndexOfString(comment[1])
const textAfter = this.text.slice(indexOfComment)
const textBefore = this.text.slice(0, indexOfComment)

if (!textBefore.endsWith(`${comment[0]}\n`)) {
this.text = `${textBefore}${comment[0]}\n${textAfter.trimEnd()}`
}
}
Expand Down
17 changes: 17 additions & 0 deletions src/test/suite/controller/processor-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,21 @@ suite("Test ProcessorController - preprocess() & postprocess()", () => {

equal(processor.text, text)
})

test("GitHub issue #164: Comment processor duplicates comments inside block scalars", () => {
const text =
"block:\n" +
" - |\n" +
" # comment 1\n" +
" some command\n" +
" # comment 2\n" +
" some other command"
const processor = new ProcessorController(text)

processor.preprocess()
processor.postprocess()

equal(processor.text, text)

})
})
24 changes: 24 additions & 0 deletions src/test/suite/processor/comment-processor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,30 @@ suite("Test CommentProcessor - isCommentFound()", () => {
})
})

suite("Test CommentProcessor - insertIfNotContained()", () => {
test("when comment is already contained it should not be inserted", () => {
const text =
"block:\n" +
" - |\n" +
" # comment 1\n" +
" some command"
const commentprocessor = new CommentProcessor(text)

commentprocessor.findComments()
equal(commentprocessor.store.length, 1)

commentprocessor.insertIfNotContained(commentprocessor.store[0])
equal(commentprocessor.text, text)

commentprocessor.text =
"block:\n" +
" - |\n" +
" some command"
commentprocessor.insertIfNotContained(commentprocessor.store[0])
equal(commentprocessor.text, text)
})
})

suite("Test CommentProcessor - Issue 45", () => {
// https://github.com/pascalre/vscode-yaml-sort/issues/45#issuecomment-1329161613
test("should fuzzy find comments", () => {
Expand Down

0 comments on commit cd793e4

Please sign in to comment.