Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hclwrite: Rewrite comments on blocks and attributes #601

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

izeau
Copy link

@izeau izeau commented Mar 26, 2023

Greetings,

The goal of this PR is to start a discussion around the manipulation of leadComments / lineComments in attributes and leadComments in blocks (I could not find a real reason for them to have lineComments, to be honest). This would solve the use case presented in #459, for line-style comments at least — since block-style comments seem to only be parsed as leadComments if they are on the same line as the attribute / block they annotate.

This PR adds a few methods to hclwrite.Block and hclwrite.Body. I’m quite new to Go so I’m sure my code may be clunky or non-idiomatic; feedback is welcome!

Example

func main() {
	file, _ := hclwrite.ParseConfig([]byte(`
city "tokyo" {
	# Tokyo is the capital of Japan
	country   = country.japan
	time_zone = "UTC+09:00"
	language  = "japanese" # jp-jp

}`,
	), "", hcl.InitialPos)

	tokyo := file.Body().FirstMatchingBlock("city", []string{"tokyo"})
	tokyo.SetComment("# Pop: 14M\n")
	tokyo.Body().SetAttributeLeadComments("country", nil)
	tokyo.Body().SetAttributeLeadComment("time_zone", "# Japan Standard Time\n")
	tokyo.Body().SetAttributeLineComments("language", nil)

	file.WriteTo(os.Stdout)
}

Output

# Pop: 14M
city "tokyo" {
  country = country.japan
  # Japan Standard Time
  time_zone = "UTC+09:00"
  language  = "japanese"
}

Caveats

As you can see on this example, I had to insert a newline after the language attribute, as the parser would otherwise create no TokenNewline: it is absorbed by the line comment. This is specific to line-style comments and would maybe be solved by rearranging the parser so that parsing line-style comments generates a TokenComment without a final newline char as well as a separate TokenNewline, if that makes sense. That may qualify as a breaking change however.

@izeau izeau force-pushed the hclwrite-rewrite-comments branch from b8aa042 to 38cc729 Compare July 20, 2023 06:57
@izeau
Copy link
Author

izeau commented Aug 15, 2023

Is there anything I can do to have this merged somehow?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant