Skip to content

Commit

Permalink
fix: line break format issue after refactor code (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
longkai committed Sep 12, 2022
1 parent 6da562a commit 9fffda5
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
2 changes: 1 addition & 1 deletion formatters/basic/features.go
Expand Up @@ -54,7 +54,7 @@ func ConfigureFeaturesFromConfig(config *Config) yamlfmt.FeatureList {
if config.LineEnding == yamlfmt.LineBreakStyleCRLF {
linebreakStr = "\r\n"
}
featLineBreak := hotfix.MakeFeatureRetainLineBreak(linebreakStr, config.Indent)
featLineBreak := hotfix.MakeFeatureRetainLineBreak(linebreakStr)
features = append(features, featLineBreak)
}
return features
Expand Down
20 changes: 20 additions & 0 deletions formatters/basic/formatter_test.go
Expand Up @@ -173,6 +173,26 @@ shell: |
# hello, world
# bye
echo "hello, world"
`,
},
{
desc: "multi level nested literal string",
input: `a: 1
x:
y:
shell: |
#!/usr/bin/env bash
# bye
echo "hello, world"`,
expect: `a: 1
x:
y:
shell: |
#!/usr/bin/env bash
# bye
echo "hello, world"
`,
},
}
Expand Down
18 changes: 11 additions & 7 deletions internal/hotfix/retain_line_break.go
Expand Up @@ -31,38 +31,42 @@ type paddinger struct {
strings.Builder
}

func (p *paddinger) adjust(size int) {
func (p *paddinger) adjust(txt string) {
var indentSize int
for i := 0; i < len(txt) && txt[i] == ' '; i++ { // yaml only allows space to indent.
indentSize++
}
// Grows if the given size is larger than us and always return the max padding.
for diff := size - p.Len(); diff > 0; diff-- {
for diff := indentSize - p.Len(); diff > 0; diff-- {
p.WriteByte(' ')
}
}

func MakeFeatureRetainLineBreak(linebreakStr string, indent int) yamlfmt.Feature {
func MakeFeatureRetainLineBreak(linebreakStr string) yamlfmt.Feature {
return yamlfmt.Feature{
Name: "Retain Line Breaks",
BeforeAction: replaceLineBreakFeature(linebreakStr, indent),
BeforeAction: replaceLineBreakFeature(linebreakStr),
AfterAction: restoreLineBreakFeature(linebreakStr),
}
}

func replaceLineBreakFeature(newlineStr string, indentSize int) yamlfmt.FeatureFunc {
func replaceLineBreakFeature(newlineStr string) yamlfmt.FeatureFunc {
return func(content []byte) ([]byte, error) {
var buf bytes.Buffer
reader := bytes.NewReader(content)
scanner := bufio.NewScanner(reader)
var padding paddinger
for scanner.Scan() {
txt := scanner.Text()
padding.adjust(indentSize)
padding.adjust(txt)
if strings.TrimSpace(txt) == "" { // line break or empty space line.
buf.WriteString(padding.String()) // prepend some padding incase literal multiline strings.
buf.WriteString(lineBreakPlaceholder)
buf.WriteString(newlineStr)
continue
}
buf.WriteString(txt)
buf.WriteByte('\n')
buf.WriteString(newlineStr)
}
return buf.Bytes(), scanner.Err()
}
Expand Down

0 comments on commit 9fffda5

Please sign in to comment.