aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/go2go/main.go
blob: a3543613ab487f1824bd18fe15e080e218081fc6 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"go/go2go"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
)

var gotool = filepath.Join(runtime.GOROOT(), "bin", "go")

var cmds = map[string]bool{
	"build":     true,
	"run":       true,
	"test":      true,
	"translate": true,
}

func main() {
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()
	if len(args) < 1 {
		usage()
	}

	if !cmds[args[0]] {
		usage()
	}

	importerTmpdir, err := ioutil.TempDir("", "go2go")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(importerTmpdir)

	importer := go2go.NewImporter(importerTmpdir)

	var rundir string
	if args[0] == "run" {
		tmpdir := copyToTmpdir(args[1:])
		defer os.RemoveAll(tmpdir)
		translate(importer, tmpdir)
		nargs := []string{"run"}
		for _, arg := range args[1:] {
			base := filepath.Base(arg)
			f := strings.TrimSuffix(base, ".go2") + ".go"
			nargs = append(nargs, f)
		}
		args = nargs
		rundir = tmpdir
	} else if args[0] == "translate" && isGo2Files(args[1:]...) {
		for _, arg := range args[1:] {
			translateFile(importer, arg)
		}
	} else {
		for _, dir := range expandPackages(args[1:]) {
			translate(importer, dir)
		}
	}

	if args[0] != "translate" {
		cmd := exec.Command(gotool, args...)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		cmd.Dir = rundir
		gopath := importerTmpdir
		if go2path := os.Getenv("GO2PATH"); go2path != "" {
			gopath += string(os.PathListSeparator) + go2path
		}
		if oldGopath := os.Getenv("GOPATH"); oldGopath != "" {
			gopath += string(os.PathListSeparator) + oldGopath
		}
		cmd.Env = append(os.Environ(),
			"GOPATH="+gopath,
			"GO111MODULE=off",
		)
		if err := cmd.Run(); err != nil {
			die(fmt.Sprintf("%s %v failed: %v", gotool, args, err))
		}
	}
}

// isGo2Files reports whether the arguments are a list of .go2 files.
func isGo2Files(args ...string) bool {
	for _, arg := range args {
		if filepath.Ext(arg) != ".go2" {
			return false
		}
	}
	return true
}

// expandPackages returns a list of directories expanded from packages.
func expandPackages(pkgs []string) []string {
	if len(pkgs) == 0 {
		return []string{"."}
	}
	go2path := os.Getenv("GO2PATH")
	var dirs []string
pkgloop:
	for _, pkg := range pkgs {
		if go2path != "" {
			for _, pd := range strings.Split(go2path, string(os.PathListSeparator)) {
				d := filepath.Join(pd, "src", pkg)
				if fi, err := os.Stat(d); err == nil && fi.IsDir() {
					dirs = append(dirs, d)
					continue pkgloop
				}
			}
		}

		cmd := exec.Command(gotool, "list", "-f", "{{.Dir}}", pkg)
		cmd.Stderr = os.Stderr
		if go2path != "" {
			gopath := go2path
			if oldGopath := os.Getenv("GOPATH"); oldGopath != "" {
				gopath += string(os.PathListSeparator) + oldGopath
			}
			cmd.Env = append(os.Environ(),
				"GOPATH="+gopath,
				"GO111MODULE=off",
			)
		}
		out, err := cmd.Output()
		if err != nil {
			die(fmt.Sprintf("%s list %q failed: %v", gotool, pkg, err))
		}
		dirs = append(dirs, strings.Split(string(out), "\n")...)
	}
	return dirs
}

// copyToTmpdir copies files into a temporary directory.
func copyToTmpdir(files []string) string {
	if len(files) == 0 {
		die("no files to run")
	}
	tmpdir, err := ioutil.TempDir("", "go2go-run")
	if err != nil {
		die(err.Error())
	}
	for _, file := range files {
		data, err := ioutil.ReadFile(file)
		if err != nil {
			die(err.Error())
		}
		if err := ioutil.WriteFile(filepath.Join(tmpdir, filepath.Base(file)), data, 0444); err != nil {
			die(err.Error())
		}
	}
	return tmpdir
}

// usage reports a usage message and exits with failure.
func usage() {
	fmt.Fprint(os.Stderr, `Usage: go2go <command> [arguments]

The commands are:

	build      translate and build packages
	run        translate and run list of files
	test       translate and test packages
	translate  translate .go2 files into .go files
`)
	os.Exit(2)
}

// die reports an error and exits.
func die(msg string) {
	fmt.Fprintln(os.Stderr, msg)
	os.Exit(1)
}