5
5
"fmt"
6
6
"go/build"
7
7
"io/ioutil"
8
- "log"
9
8
"os"
10
9
"os/exec"
11
10
@@ -22,42 +21,56 @@ func usage() {
22
21
fmt .Println ("The resulting build will have the package name of <mainPkg>" )
23
22
}
24
23
25
- func main () {
26
- flag .Usage = usage
27
- flag .Parse ()
28
-
29
- if len (flag .Args ()) == 0 {
30
- fmt .Println ("missing arguments" )
31
- usage ()
32
- os .Exit (- 1 )
33
- }
34
-
35
- pkgs := gotool .ImportPaths (flag .Args ())
24
+ func multibuild (packages []string ) (error , int ) {
25
+ // parse the names of the paths/packages provided on the command-line
26
+ pkgs := gotool .ImportPaths (packages )
36
27
28
+ // parse the main package: we need the package name and the path
37
29
mainpkg , err := build .Import (pkgs [0 ], "." , 0 )
38
30
if err != nil {
39
- log .Printf ("unable to import main package %s: %s" , pkgs [0 ], err )
40
- os .Exit (- 2 )
31
+ return fmt .Errorf ("unable to import main package %s: %s" , pkgs [0 ], err ), - 2
41
32
}
42
33
34
+ // create the linker file in the main package directory, so that it will be
35
+ // compiled and linked with the main package when we `go build` is invoked
36
+ // the linker file is a go file in the same package of the main package that
37
+ // imports all additional packages (normally for their side-effects)
43
38
tmpFile , err := ioutil .TempFile (mainpkg .Dir , "pluggo" )
44
39
if err != nil {
45
- log .Printf ("unable to create temporary file: %s" , err )
46
- os .Exit (- 3 )
40
+ return fmt .Errorf ("unable to create temporary file: %s" , err ), - 3
47
41
}
48
42
49
43
fmt .Fprintf (tmpFile , "package %s\n " , mainpkg .Name )
50
- for _ , pkgname := range os . Args [ 2 :] {
44
+ for _ , pkgname := range pkgs [ 1 :] {
51
45
fmt .Fprintf (tmpFile , "import _ \" %s\" \n " , pkgname )
52
46
}
53
47
54
48
tmpFile .Close ()
55
49
os .Rename (tmpFile .Name (), tmpFile .Name ()+ ".go" )
56
50
defer os .Remove (tmpFile .Name () + ".go" )
57
51
58
- output , err := exec .Command ("go" , "build" , flag .Args ()[0 ]).CombinedOutput ()
52
+ // run go build on the main package
53
+ output , err := exec .Command ("go" , "build" , packages [0 ]).CombinedOutput ()
54
+ if err != nil {
55
+ return fmt .Errorf ("error executing go build: %s\n go build output:\n %s" , err , string (output )), - 4
56
+ }
57
+
58
+ return nil , 0
59
+ }
60
+
61
+ func main () {
62
+ flag .Usage = usage
63
+ flag .Parse ()
64
+
65
+ if len (flag .Args ()) == 0 {
66
+ fmt .Println ("missing arguments" )
67
+ usage ()
68
+ os .Exit (- 1 )
69
+ }
70
+
71
+ err , rv := multibuild (flag .Args ())
59
72
if err != nil {
60
- fmt .Print ( string ( output ) )
61
- os .Exit (- 4 )
73
+ fmt .Println ( err )
74
+ os .Exit (rv )
62
75
}
63
76
}
0 commit comments