From c428d8068215c337ab69e78fb6f731729d8617b2 Mon Sep 17 00:00:00 2001 From: Leon Brocard Date: Tue, 16 Jul 2024 13:58:55 +0200 Subject: [PATCH] feat(formatter): prevent indentation of #FASTLY macros - Modified the formatComment function to skip indentation for comments starting with "#FASTLY" - Added unit tests to verify the new behaviour for regular comments, #FASTLY macros, and mixed comment scenarios - This change ensures that #FASTLY macros remain at the start of the line, adhering to Fastly's VCL formatting conventions, e.g.: - https://www.fastly.com/documentation/guides/vcl/using/#custom-vcl --- formatter/formatter.go | 5 ++- formatter/formatter_test.go | 74 +++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/formatter/formatter.go b/formatter/formatter.go index 4ec3bf4a..68e5b61c 100644 --- a/formatter/formatter.go +++ b/formatter/formatter.go @@ -154,7 +154,10 @@ func (f *Formatter) formatComment(comments ast.Comments, sep string, level int) if comments[i].PreviousEmptyLines > 0 { buf.WriteString("\n") } - buf.WriteString(f.indent(level)) + // #FASTLY macros are not indented + if !strings.HasPrefix(comments[i].String(), "#FASTLY") { + buf.WriteString(f.indent(level)) + } switch f.conf.CommentStyle { case config.CommentStyleSharp, config.CommentStyleSlash: r := '#' // default as sharp style comment diff --git a/formatter/formatter_test.go b/formatter/formatter_test.go index a7657e50..a993924a 100644 --- a/formatter/formatter_test.go +++ b/formatter/formatter_test.go @@ -62,3 +62,77 @@ func BenchmarkFormatter(b *testing.B) { New(c).Format(vcl) } } + +func TestFormatComment(t *testing.T) { + tests := []struct { + name string + input string + conf *config.FormatConfig + expect string + }{ + { + name: "Regular comment", + input: `sub recv { +// This is a single comment +return(pass); +}`, + expect: `sub recv { + // This is a single comment + return(pass); +} +`, + conf: &config.FormatConfig{ + CommentStyle: "slash", + IndentWidth: 2, + IndentStyle: "space", + ReturnStatementParenthesis: true, + }, + }, + { + name: "Comment starting with #FASTLY", + input: `sub recv { +#FASTLY recv +return(pass); +}`, + expect: `sub recv { +#FASTLY recv + return(pass); +} +`, + conf: &config.FormatConfig{ + CommentStyle: "sharp", + IndentWidth: 2, + IndentStyle: "space", + ReturnStatementParenthesis: true, + }, + }, + { + name: "Multiple comments", + input: `sub recv { +# Regular comment 1 +#FASTLY recv + # Regular comment 2 +return(pass); +}`, + expect: `sub recv { + # Regular comment 1 +#FASTLY recv + # Regular comment 2 + return(pass); +} +`, + conf: &config.FormatConfig{ + CommentStyle: "sharp", + IndentWidth: 2, + IndentStyle: "space", + ReturnStatementParenthesis: true, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert(t, tt.input, tt.expect, tt.conf) + }) + } +}