Skip to content

Commit

Permalink
Add format option
Browse files Browse the repository at this point in the history
  • Loading branch information
tamayika committed Nov 25, 2018
1 parent 8c744e6 commit 95fcc3b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
29 changes: 25 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
Expand All @@ -15,7 +16,23 @@ import (

var version = "dev"

func printText(source []byte, fset *token.FileSet, nodes []ast.Node) {
for _, node := range nodes {
pos := fset.Position(node.Pos())
end := fset.Position(node.End())
fmt.Println(string(source[pos.Offset:end.Offset]))
}
}

func printPos(nodes []ast.Node) {
for _, node := range nodes {
fmt.Printf("%d,%d\n", node.Pos(), node.End())
}
}

func main() {
var format string

rootCmd := &cobra.Command{
Use: "gaq <Query>",
Short: "gaq is the cli tool to query ast node. STDIN needed as go code.",
Expand All @@ -41,13 +58,17 @@ Please see details at https://github.com/tamayika/gaq`,

q := query.MustParse(args[0])
nodes := node.QuerySelectorAll(q)
for _, node := range nodes {
pos := fset.Position(node.Pos())
end := fset.Position(node.End())
fmt.Println(string(data[pos.Offset:end.Offset]))
switch format {
case "text":
printText(data, fset, nodes)
case "pos":
printPos(nodes)
default:
log.Fatalf("Format: %s is not supported.", format)
}
},
}
rootCmd.PersistentFlags().StringVarP(&format, "format", "f", "text", "Output format, 'text' or 'pos'. Default is 'text'")
rootCmd.SetVersionTemplate(`{{printf "%s" .Version}}`)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
Expand Down
3 changes: 1 addition & 2 deletions pkg/gaq/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,8 +587,7 @@ func TestNode_QuerySelectorAll(t *testing.T) {
args{
query.MustParse("TypeSpec:root"),
},
[]ast.Node{
},
[]ast.Node{},
},
}
for _, tt := range tests {
Expand Down

0 comments on commit 95fcc3b

Please sign in to comment.