github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/src/cmd/cgo/util.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "bytes" 9 "fmt" 10 "go/token" 11 "os" 12 "os/exec" 13 ) 14 15 // run runs the command argv, feeding in stdin on standard input. 16 // It returns the output to standard output and standard error. 17 // ok indicates whether the command exited successfully. 18 func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) { 19 p := exec.Command(argv[0], argv[1:]...) 20 p.Stdin = bytes.NewReader(stdin) 21 var bout, berr bytes.Buffer 22 p.Stdout = &bout 23 p.Stderr = &berr 24 err := p.Run() 25 if _, ok := err.(*exec.ExitError); err != nil && !ok { 26 fatalf("%s", err) 27 } 28 ok = p.ProcessState.Success() 29 stdout, stderr = bout.Bytes(), berr.Bytes() 30 return 31 } 32 33 func lineno(pos token.Pos) string { 34 return fset.Position(pos).String() 35 } 36 37 // Die with an error message. 38 func fatalf(msg string, args ...interface{}) { 39 // If we've already printed other errors, they might have 40 // caused the fatal condition. Assume they're enough. 41 if nerrors == 0 { 42 fmt.Fprintf(os.Stderr, msg+"\n", args...) 43 } 44 os.Exit(2) 45 } 46 47 var nerrors int 48 49 func error_(pos token.Pos, msg string, args ...interface{}) { 50 nerrors++ 51 if pos.IsValid() { 52 fmt.Fprintf(os.Stderr, "%s: ", fset.Position(pos).String()) 53 } 54 fmt.Fprintf(os.Stderr, msg, args...) 55 fmt.Fprintf(os.Stderr, "\n") 56 } 57 58 // isName returns true if s is a valid C identifier 59 func isName(s string) bool { 60 for i, v := range s { 61 if v != '_' && (v < 'A' || v > 'Z') && (v < 'a' || v > 'z') && (v < '0' || v > '9') { 62 return false 63 } 64 if i == 0 && '0' <= v && v <= '9' { 65 return false 66 } 67 } 68 return s != "" 69 } 70 71 func creat(name string) *os.File { 72 f, err := os.Create(name) 73 if err != nil { 74 fatalf("%s", err) 75 } 76 return f 77 } 78 79 func slashToUnderscore(c rune) rune { 80 if c == '/' || c == '\\' || c == ':' { 81 c = '_' 82 } 83 return c 84 }