-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaygo.go
103 lines (86 loc) · 2.26 KB
/
playgo.go
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
package playgo
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
)
func Main() int {
// set up output, especially stderr, so we can use it in preparation steps
init := Initializer{
Stdout: os.Stdout,
Stderr: os.Stderr,
}
dataDir := os.Getenv("XDG_DATA_HOME")
if dataDir == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
fmt.Fprintln(init.Stderr, "unable to identify either $XDG_DATA_HOME or home directory; using the current directory instead")
} else {
dataDir = filepath.Join(homeDir, ".local", "share")
}
}
init.Directory = filepath.Join(dataDir, "scratches")
err := init.Init()
if err != nil {
return 1
}
return 0
}
// Initializer initializes a new go module so that users can
// quickly get a sandbox environment for their Golang development
// needs.
type Initializer struct {
Stdout io.Writer
Stderr io.Writer
// Directory is the parent directory in which to put
// the new module. Note that a directory with the name
// of the module will be created within this directory -
// it is not the name of the directory where the go.mod
// will be added.
Directory string
// Module is the name of the module that you wish to create.
// If none is provided, one will be made up.
Module string
}
// Init initializes a new go module using the configuration of
// the associated [Initializer].
func (i Initializer) Init() error {
if i.Module == "" {
i.Module = GenerateRandomName()
}
cmd := exec.Command("go", "mod", "init", i.Module)
path, err := filepath.Abs(filepath.Join(i.Directory, i.Module))
if err != nil {
fmt.Fprintln(i.Stderr, err.Error())
return err
}
err = os.MkdirAll(path, os.ModePerm)
if err != nil {
fmt.Fprintln(i.Stderr, err.Error())
return err
}
cmd.Dir = path
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintln(i.Stderr, string(out))
return err
}
fmt.Fprintf(i.Stdout, "Created module %q in directory %q\n", i.Module, path)
mainContent := []byte(main_file)
mainPath := filepath.Join(path, "main.go")
err = os.WriteFile(mainPath, mainContent, 0644)
if err != nil {
i.Stderr.Write([]byte(out))
return err
}
fmt.Fprintf(i.Stdout, "Created main.go in directory %q\n", path)
return nil
}
const main_file = `package main
import "fmt"
func main() {
fmt.Println("Hello, Play-Go!")
}
`