MCPcopy
hub / github.com/hashicorp/hcl / linesForFormat

Function linesForFormat

hclwrite/format.go:346–429  ·  view source on GitHub ↗
(tokens Tokens)

Source from the content-addressed store, hash-verified

344}
345
346func linesForFormat(tokens Tokens) []formatLine {
347 if len(tokens) == 0 {
348 return make([]formatLine, 0)
349 }
350
351 // first we'll count our lines, so we can allocate the array for them in
352 // a single block. (We want to minimize memory pressure in this codepath,
353 // so it can be run somewhat-frequently by editor integrations.)
354 lineCount := 1 // if there are zero newlines then there is one line
355 for _, tok := range tokens {
356 if tokenIsNewline(tok) {
357 lineCount++
358 }
359 }
360
361 // To start, we'll just put everything in the "lead" cell on each line,
362 // and then do another pass over the lines afterwards to adjust.
363 lines := make([]formatLine, lineCount)
364 li := 0
365 lineStart := 0
366 for i, tok := range tokens {
367 if tok.Type == hclsyntax.TokenEOF {
368 // The EOF token doesn't belong to any line, and terminates the
369 // token sequence.
370 lines[li].lead = tokens[lineStart:i]
371 break
372 }
373
374 if tokenIsNewline(tok) {
375 lines[li].lead = tokens[lineStart : i+1]
376 lineStart = i + 1
377 li++
378 }
379 }
380
381 // If a set of tokens doesn't end in TokenEOF (e.g. because it's a
382 // fragment of tokens from the middle of a file) then we might fall
383 // out here with a line still pending.
384 if lineStart < len(tokens) {
385 lines[li].lead = tokens[lineStart:]
386 if lines[li].lead[len(lines[li].lead)-1].Type == hclsyntax.TokenEOF {
387 lines[li].lead = lines[li].lead[:len(lines[li].lead)-1]
388 }
389 }
390
391 // Now we'll pick off any trailing comments and attribute assignments
392 // to shuffle off into the "comment" and "assign" cells.
393 for i := range lines {
394 line := &lines[i]
395
396 if len(line.lead) == 0 {
397 // if the line is empty then there's nothing for us to do
398 // (this should happen only for the final line, because all other
399 // lines would have a newline token of some kind)
400 continue
401 }
402
403 if len(line.lead) > 1 && line.lead[len(line.lead)-1].Type == hclsyntax.TokenComment {

Callers 2

TestLinesForFormatFunction · 0.85
formatFunction · 0.85

Calls 2

tokenIsNewlineFunction · 0.85
tokenBracketChangeFunction · 0.85

Tested by 1

TestLinesForFormatFunction · 0.68