github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/cmd/structlayout-pretty/main.go (about)

     1  // structlayout-pretty formats the output of structlayout with ASCII
     2  // art.
     3  package main
     4  
     5  import (
     6  	"encoding/json"
     7  	"flag"
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  	"strings"
    12  
    13  	"github.com/amarpal/go-tools/lintcmd/version"
    14  	st "github.com/amarpal/go-tools/structlayout"
    15  )
    16  
    17  var (
    18  	fVerbose bool
    19  	fVersion bool
    20  )
    21  
    22  func init() {
    23  	flag.BoolVar(&fVerbose, "v", false, "Do not compact consecutive bytes of fields")
    24  	flag.BoolVar(&fVersion, "version", false, "Print version and exit")
    25  }
    26  
    27  func main() {
    28  	log.SetFlags(0)
    29  	flag.Parse()
    30  
    31  	if fVersion {
    32  		version.Print(version.Version, version.MachineVersion)
    33  		os.Exit(0)
    34  	}
    35  
    36  	var fields []st.Field
    37  	if err := json.NewDecoder(os.Stdin).Decode(&fields); err != nil {
    38  		log.Fatal(err)
    39  	}
    40  	if len(fields) == 0 {
    41  		return
    42  	}
    43  	max := fields[len(fields)-1].End
    44  	maxLength := len(fmt.Sprintf("%d", max))
    45  	padding := strings.Repeat(" ", maxLength+2)
    46  	format := fmt.Sprintf(" %%%dd ", maxLength)
    47  	pos := int64(0)
    48  	fmt.Println(padding + "+--------+")
    49  	for _, field := range fields {
    50  		name := field.Name + " " + field.Type
    51  		if field.IsPadding {
    52  			name = "padding"
    53  		}
    54  		fmt.Printf(format+"|        | <- %s (size %d, align %d)\n", pos, name, field.Size, field.Align)
    55  		fmt.Println(padding + "+--------+")
    56  
    57  		if fVerbose {
    58  			for i := int64(0); i < field.Size-1; i++ {
    59  				fmt.Printf(format+"|        |\n", pos+i+1)
    60  				fmt.Println(padding + "+--------+")
    61  			}
    62  		} else {
    63  			if field.Size > 2 {
    64  				fmt.Println(padding + "-........-")
    65  				fmt.Println(padding + "+--------+")
    66  				fmt.Printf(format+"|        |\n", pos+field.Size-1)
    67  				fmt.Println(padding + "+--------+")
    68  			}
    69  		}
    70  		pos += field.Size
    71  	}
    72  }