php2go/main.go

73 lines
1.4 KiB
Go
Raw Normal View History

2020-04-05 04:35:44 +00:00
package main
import (
"errors"
"flag"
"fmt"
"go/format"
"io/ioutil"
"os"
"github.com/z7zmey/php-parser/parser"
"github.com/z7zmey/php-parser/visitor"
)
func ConvertFile(filename string) (string, error) {
inputFile, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
namespaces := visitor.NewNamespaceResolver()
// scope := NewScope()
state := conversionState{}
2020-04-05 04:35:44 +00:00
p, err := parser.NewParser([]byte(inputFile), "7.4")
if err != nil {
panic(err)
}
p.Parse()
for _, err := range p.GetErrors() {
return "", errors.New(err.String())
}
// Walk and print JSON...
if fh, err := os.OpenFile(filename+`.parse.json`, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644); err == nil {
v := visitor.NewPrettyJsonDumper(fh, namespaces)
p.GetRootNode().Walk(v)
fh.Close()
}
// Walk and print (converted)
ret, err := state.convert(p.GetRootNode())
2020-04-05 04:35:44 +00:00
if err != nil {
return "", err
}
// Gofmt output
// TODO pass flags to get -s/-r equivalent for more agressive simplification
formatted, err := format.Source([]byte(ret))
if err != nil {
ret += "// Gofmt failed: " + err.Error()
return ret, nil
}
return string(formatted), nil
}
func main() {
filename := flag.String("InFile", "", "Select file to convert")
flag.Parse()
ret, err := ConvertFile(*filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(ret)
}