package main /**************************************************************************** GG - builder for go projects ***************************************************************************** http://www.manatlan.com/page/gg released under the terms of BSD License Copyright (c) 2009, manatlan.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** changelog : 0.7 : - updated to current release of go (2010/02/11) 0.6 : - bugfix: full rebuild process was breaked when many packages 0.5 : - patchs from Steve (cosmetic) - remove the space at the beginning of the error (gedit is happy now) - bugfix: exe weren't rebuilded after a module rebuilded - throw an error for non-wellformed gg'makefile 0.4 : - respect order of modules(.a) for build operations 0.3 : - bugfix: in relative files - incremental build (based on mtime) - new flag 'f' for full rebuild (no incremental) 0.2 : can use comments in yaml gg'makefile (with '#') 0.1 : initial public release *****************************************************************************/ import ( "flag"; "fmt"; "os"; "io"; "path"; "strings"; "regexp"; "bytes"; ) var VERSION string = "0.7" //====================================================================== // Utils //====================================================================== func error(m string) { println("ERROR:\n"+m);;os.Exit(-1); } func concat(l1, l2 []string) []string { result := make([]string, len(l1)+len(l2)); ind := 0; for _, v := range l1 { result[ind] = v; ind++; } for _, v := range l2 { result[ind] = v; ind++; } return result; } func stripExt(f string) string { return f[0 : len(f)-len(path.Ext(f))] } func run(args []string, verbose bool) string { if verbose { println("$",strings.Join(args," ")); } r, w, err := os.Pipe(); if err != nil { error(err.String()); } fds := []*os.File{nil, w, w}; pid,err :=os.ForkExec(args[0],args,os.Environ(),".",fds); defer r.Close(); w.Close(); if err != nil { error(err.String()); } var buf bytes.Buffer; io.Copy(&buf, r); _, e := os.Wait(pid, 0); if err != nil { error(e.String()); } return buf.String(); } func isNeeded(fs,fd string) (v bool) { // return true if fs is more recent than fd, or if fd doesn't exists ds,es:=os.Stat(fs); dd,ed:=os.Stat(fd); if ed!=nil || es!=nil { v=true; } else { v= ds.Mtime_ns > dd.Mtime_ns; } return v; } func isNeededs(s []string, fd string) bool { // same as isNeeded(), but with list as source for _, fs := range s { if isNeeded(fs, fd) { return true } } return false; } //====================================================================== // YAML's methods //====================================================================== func yamline(doc string) ([]string, map[string][]string) { // fmt.Printf("DOC:%#v\n",doc); order := []string{}; r := make(map[string][]string, 100); l := strings.Split(doc, ",", 0); for _, v := range l { ll := strings.Split(v, ":", 0); if len(ll)!=2 {error("gg'makefile is not wellformed !")} name := strings.TrimSpace(ll[0]); r[name] = strings.Split(strings.TrimSpace(ll[1]), " ", 0); order = concat(order, []string{name}); } return order, r; } var whiteSpaceRE = regexp.MustCompile("[ \t\r]") var commentRE = regexp.MustCompile("#.*$") func yamldoc(doc string) ([]string, map[string][]string) { l := strings.Split(doc, "\n", 0); sdoc := ""; for _, v := range l { v := commentRE.ReplaceAllString(v, ""); // remove comments line := whiteSpaceRE.ReplaceAllString(v, ""); if line != "" { if strings.HasSuffix(line, ":") { if sdoc != "" { sdoc += "," } } else { if sdoc != "" { sdoc += " " } } sdoc += line; } } return yamline(strings.TrimSpace(sdoc)); } //====================================================================== // GG Object, to access GoBin //====================================================================== type GG struct { verbose, full bool; } func (this *GG) compileEach(l []string) { for _, v := range l { if this.full || isNeeded(v, this.fobj(v)) { err := run([]string{this.g(), "-o", this.fobj(v), v}, this.verbose); if err != "" { error(err) } } } } func (this *GG) compileAll(l []string) { first := l[0]; if this.full || isNeededs(l, this.fobj(first)) { // compile all go'files in the first, for output a ".8" err := run(concat([]string{this.g(), "-o", this.fobj(first)}, l), this.verbose); if err != "" { error(err) } } } func (this *GG) makePack(pack string, l []string) bool { ll := this.fobjs(l); if this.full || isNeededs(ll, pack) { err := run(concat([]string{this.p(), "grc", pack}, this.fobjs(l)), this.verbose); if err != "" { error(err); return false; } return true; } return false; } func (this *GG) build(exe string, l []string, aModuleHasChanged bool) { first := l[0]; // link the first only, see compileAll if this.full || aModuleHasChanged || isNeeded(this.fobj(first), exe) { err := run([]string{this.l(), "-o", exe, this.fobj(first)}, this.verbose); if err != "" { error(err) } } } func (this *GG) num() string { switch os.Getenv("GOARCH") { case "386": return "8" case "arm": return "5" } return "6"; } func (this *GG) g() string { return path.Join(os.Getenv("GOBIN"), this.num()+"g") } func (this *GG) p() string { return path.Join(os.Getenv("GOBIN"), "gopack") } func (this *GG) l() string { return path.Join(os.Getenv("GOBIN"), this.num()+"l") } func (this *GG) fobj(file string) string { n := this.num(); return stripExt(file) + "." + n; } func (this *GG) fobjs(l []string) []string { // return files 'l' with object extensions (ex: .8) result := make([]string, len(l)); ind := 0; for _, file := range l { result[ind] = this.fobj(file); ind++; } return result; } //====================================================================== func builder(order []string, doc map[string][]string, verbose, isFull bool) []string { //====================================================================== // fmt.Printf("YAML: %#v\n",*doc); l := ""; gg := new(GG); gg.verbose = verbose; gg.full = isFull; needRebuildExe := false; // will handle if a module was rebuilded // compile module for _, k := range order { if strings.HasSuffix(strings.ToLower(k), ".a") { v := doc[k]; gg.compileEach(v); if gg.makePack(k, v) { needRebuildExe=true; } } } // build exe for _, k := range order { if !strings.HasSuffix(strings.ToLower(k), ".a") { v := doc[k]; gg.compileAll(v); gg.build(k, v, needRebuildExe); if l != "" { l += "," } //FIXME: do better l += k; } } return strings.Split(l, ",", 0); } //====================================================================== func clearer(doc map[string][]string, verbose bool) { //====================================================================== // fmt.Printf("YAML: %#v\n",*doc); var l []string; gg := new(GG); gg.verbose = verbose; for k, v := range doc { if strings.HasSuffix(strings.ToLower(k), ".a") { l = concat(l, []string{k}); l = concat(l, gg.fobjs(v)); } } for k, v := range doc { if !strings.HasSuffix(strings.ToLower(k), ".a") { l = concat(l, []string{k}); l = concat(l, gg.fobjs(v)); } } for _, v := range l { fd, _ := os.Open(v, os.O_RDONLY, 0777); //TODO: another thing to test if file exists ? if fd != nil { fd.Close(); if verbose { println("delete", v) } os.Remove(v); } } } func ReadFile(filename string) ([]byte, os.Error) { f, err := os.Open(filename, os.O_RDONLY, 0); if err != nil { return nil, err } defer f.Close(); d, err := f.Stat(); if err != nil { return nil, err } buf := make([]byte, d.Size); _, err = io.ReadFull(f, buf); if err != nil { return nil, err } return buf,err } func process(file string, isVerbose, isDontRun, isClear, isFull bool) { var order []string; var doc map[string][]string; c, e := ReadFile(file); if e != nil { error(e.String()) } if strings.ToLower(path.Ext(file)) == ".go" { l := strings.Split(string(c), "\n", 0); r, _ := regexp.Compile("gg:{([^}]+)}"); ll := r.MatchStrings(l[0]); var sdoc string; if len(ll)>0 { sdoc=ll[1]; if(isVerbose) {println("GG shebang in '",file,"'");} } else { name := stripExt(file); sdoc=fmt.Sprintf("%s: %s",name,file); if(isVerbose) {println("GG run '",file,"'");} } order,doc=yamline(sdoc); } else { if(isVerbose) {println("GG makefile '",file,"'");} order,doc=yamldoc(string(c)); } if isClear { clearer(doc, isVerbose) } else { lExe := builder(order, doc, isVerbose, isFull); if !isDontRun { switch { case len(lExe)==0: println("No executable to run"); case len(lExe)==1: println("Running",lExe[0]); os.Exec(lExe[0],lExe,os.Environ()); default: println("Too many executables to run once"); } } } } func do() { if os.Getenv("GOARCH") == "" || os.Getenv("GOBIN") == "" { panic("You need to set GOBIN and GOARCH in environment!") } var Usage = func() { _,basename := path.Split(os.Args[0]); fmt.Fprintf(os.Stderr, `USAGE: %s [options] Build google's go projects by providing a go file or a yaml makefile. http://www.manatlan.com (C)2009 - V%s - BSD License. file: can be a .go file, or a yaml makefile. if the .go file contains a shebang describing a yaml project, it will be builded and run, else it will just build and run the go file. options: `,basename,VERSION); flag.PrintDefaults(); }; var bVerb *bool = flag.Bool("v", false, "verbose mode"); var bDontRun *bool = flag.Bool("m", false, "just make (don't run)"); var bClear *bool = flag.Bool("c", false, "just clear"); var bFull *bool = flag.Bool("f", false, "full rebuild (no incremental)"); flag.Parse(); if len(flag.Args()) != 1 { Usage() } else { process(flag.Arg(0), *bVerb, *bDontRun, *bClear, *bFull); os.Exit(0); } } func main() { do() }