aboutsummaryrefslogtreecommitdiffstats
path: root/ast.go
blob: 41ab3dff8effbf0b8ae2b7e9770c6581382162e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

import (
	"bytes"
	"fmt"
	"go/parser"
	"go/printer"
	"go/token"
	"io/ioutil"
	"os"

	"github.com/mgutz/ansi"
	"golang.org/x/tools/go/ast/astutil"
)

// ProcessFileAST processes the files using golang's AST parser
func ProcessFileAST(filePath string, from string, to string) {

	//Colors to be used on the console
	red := ansi.ColorCode("red+bh")
	white := ansi.ColorCode("white+bh")
	yellow := ansi.ColorCode("yellow+bh")
	blackOnWhite := ansi.ColorCode("black+b:white+h")
	//Reset the color
	reset := ansi.ColorCode("reset")

	fmt.Println(blackOnWhite+"Processing file", filePath, "in SAFE MODE", reset)

	// New FileSet to parse the go file to
	fSet := token.NewFileSet()

	// Parse the file
	file, err := parser.ParseFile(fSet, filePath, nil, parser.ParseComments)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Keep track of number of changes
	changed := false
	if changed = astutil.RewriteImport(fSet, file, from, to); changed {
		fmt.Println(red +
			"Updating import " +
			reset + white +
			from +
			reset + red +
			" to " +
			reset + white +
			to +
			reset)
	}

	// If the number of changes are more than 0, write file
	if changed {
		// Print the new AST tree to a new output buffer. These Config settings intended to match gofmt.
		printerMode := printer.TabIndent | printer.UseSpaces
		printConfig := &printer.Config{Mode: printerMode, Tabwidth: 8}

		var outputBuffer bytes.Buffer
		err := printConfig.Fprint(&outputBuffer, fSet, file)
		if err != nil {
			fmt.Println(err)
			return
		}

		ioutil.WriteFile(filePath, outputBuffer.Bytes(), os.ModePerm)
		fmt.Println(yellow+
			"File",
			filePath,
			"saved",
			reset, "\n\n")
	} else {
		fmt.Println(yellow+
			"No changes to write on this file.",
			reset, "\n\n")
	}
}