found all execs in all GOPATH/bin dirs

This commit is contained in:
Stephen McQuay 2014-10-13 01:04:19 +02:00
commit c3a724cec4

98
main.go Normal file
View File

@ -0,0 +1,98 @@
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
func main() {
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
binDirs := []string{}
for _, env := range os.Environ() {
if strings.HasPrefix(env, "GOPATH=") {
i := strings.Index(env, "=")
paths := filepath.SplitList(env[i+1:])
for _, path := range paths {
binDirs = append(binDirs, filepath.Join(path, "bin"))
}
}
}
files := map[string]os.FileInfo{}
for _, binDir := range binDirs {
fi, err := os.Stat(binDir)
if err != nil {
log.Printf("%+v", err)
continue
}
if !fi.IsDir() {
log.Printf("%s is not a directory!", binDir)
continue
}
dirInfo, err := ioutil.ReadDir(binDir)
if err != nil {
log.Printf("%+v", err)
continue
}
for _, di := range dirInfo {
files[filepath.Join(binDir, di.Name())] = di
}
}
execs := []string{}
buf := &bytes.Buffer{}
for name, _ := range files {
buf.Reset()
if !exists(name) {
log.Fatal("this should never happen: file we just found isn't there now")
}
if fi, err := os.Stat(name); fi.IsDir() {
if err != nil {
log.Fatal(err)
}
continue
}
fi, err := os.Open(name)
if err != nil {
log.Fatal(err)
}
lr := &io.LimitedReader{
R: fi,
N: 2,
}
_, err = io.Copy(buf, lr)
if err != nil {
log.Fatal(err)
}
execPatterns := [][]byte{
{0x7f, 0x45},
{0xcf, 0xfa},
}
for _, b := range execPatterns {
if bytes.Equal(buf.Bytes(), b) {
execs = append(execs, name)
}
}
}
for _, exec := range execs {
fmt.Println(exec)
}
}
func exists(path string) bool {
if _, err := os.Stat(path); err != nil {
return false
} else if os.IsNotExist(err) {
return false
}
return true
}