Merge pull request #4 from fatih/align-attributes

printer: aligned adjacent attributes, closes #3
This commit is contained in:
Fatih Arslan 2015-11-04 16:29:11 +02:00
commit 2e450506d2
6 changed files with 29 additions and 20 deletions

View File

@ -323,11 +323,19 @@ func (p *printer) objectType(o *ast.ObjectType) []byte {
func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
var buf bytes.Buffer
var longestLine int
// find the longest key and value length, needed for alignment
var longestKeyLen int // longest key length
var longestValLen int // longest value length
for _, item := range items {
lineLen := len(item.Keys[0].Token.Text) + len(p.output(item.Val))
if lineLen > longestLine {
longestLine = lineLen
key := len(item.Keys[0].Token.Text)
val := len(p.output(item.Val))
if key > longestKeyLen {
longestKeyLen = key
}
if val > longestValLen {
longestValLen = val
}
}
@ -339,25 +347,26 @@ func (p *printer) alignedItems(items []*ast.ObjectItem) []byte {
}
}
curLen := 0
for i, k := range item.Keys {
keyLen := len(k.Token.Text)
buf.WriteString(k.Token.Text)
buf.WriteByte(blank)
for i := 0; i < longestKeyLen-keyLen+1; i++ {
buf.WriteByte(blank)
}
// reach end of key
if i == len(item.Keys)-1 && len(item.Keys) == 1 {
buf.WriteString("=")
buf.WriteByte(blank)
}
curLen = len(k.Token.Text) // two blanks and one assign
}
val := p.output(item.Val)
valLen := len(val)
buf.Write(val)
curLen += len(val)
if item.Val.Pos().Line == item.Keys[0].Pos().Line && item.LineComment != nil {
for i := 0; i < longestLine-curLen+1; i++ {
for i := 0; i < longestValLen-valLen+1; i++ {
buf.WriteByte(blank)
}

View File

@ -4,7 +4,7 @@
variable "foo" {
# Standalone comment should be still here
default = "bar"
default = "bar"
description = "bar" # yooo
}

View File

@ -1,8 +1,8 @@
aligned = {
# We have some aligned items below
foo = "bar" # yoo1
default = "bar" # yoo2
bar = "bar" # yoo3
foo = "fatih" # yoo1
default = "bar" # yoo2
bar = "bar and foo" # yoo3
default = {
bar = "example"

View File

@ -1,8 +1,8 @@
aligned {
# We have some aligned items below
foo = "bar" # yoo1
foo = "fatih" # yoo1
default = "bar" # yoo2
bar = "bar" # yoo3
bar = "bar and foo" # yoo3
default = {
bar = "example"
}

View File

@ -3,7 +3,7 @@
aligned = {
# Standalone 1
a = "bar" # yoo1
a = "bar" # yoo1
default = "bar" # yoo2
# Standalone 2

View File

@ -1,5 +1,5 @@
variable "foo" {
default = "bar"
default = "bar"
description = "bar"
}
@ -28,13 +28,13 @@ resource aws_instance "web" {
network_interface = {
device_index = 0
description = "Main network interface"
description = "Main network interface"
}
}
resource "aws_instance" "db" {
security_groups = "${aws_security_group.firewall.*.id}"
VPC = "foo"
VPC = "foo"
depends_on = ["aws_instance.web"]
}