Example #1
0
File: main.go Project: bjarneh/cmd
func matchFilter(dirs []os.FileInfo) (procs []os.FileInfo) {

	root := "/proc"

	for i := range dirs {
		status := filepath.Join(root, dirs[i].Name(), "status")
		cmdline := filepath.Join(root, dirs[i].Name(), "cmdline")
		if handy.IsFile(status) && handy.IsFile(cmdline) {
			if matchOK(cmdline) {
				procs = append(procs, dirs[i])
			}
		}
	}

	return procs
}
Example #2
0
File: main.go Project: bjarneh/cmd
func main() {

	var (
		args  []string
		total int
		files chan string
	)

	args = getopt.Parse(os.Args[1:])

	switch {
	case getopt.IsSet("-list"):
		listing()
	case getopt.IsSet("-help"):
		usage()
	case getopt.IsSet("-match"):
		addMatchFunc(getopt.Get("-match"))
	}

	if len(args) > 0 {
		root = args[0]
	}

	if handy.IsDir(root) {
		files = walker.ChanWalk(root)
		total = counter.NewLineFiles(getopt.IsSet("-verbose"), files)
	} else if handy.IsFile(root) {
		total = counter.NewLineFile(root)
	} else {
		log.Fatalf("[ERROR] '%s' neither file nor directory\n", root)
	}

	fmt.Printf("total: %6d\n", total)
}
Example #3
0
File: main.go Project: bjarneh/cmd
func printProcessInfo(files []os.FileInfo) {

	root := "/proc"
	pid := strconv.Itoa(os.Getpid())

	for i := range files {
		cmdline := filepath.Join(root, files[i].Name(), "cmdline")
		// some processes may have died..
		if handy.IsFile(cmdline) && pid != files[i].Name() {
			b := slurpStripNullByte(cmdline)
			fmt.Printf("%5s : %s\n", files[i].Name(), string(b))
		}
	}
}
Example #4
0
func Make(fname string, pkgs []*dag.Package, alien []string) {

	if handy.IsFile(fname) {

		modImport, iOk := hasModifiedImports(fname)
		if iOk {
			m[Imports] = modImport
		}

		modPlay, pOk := hasModifiedPlayground(fname)
		if pOk {
			m[Playground] = modPlay
		}

		if pOk || iOk {
			dn, fn := filepath.Split(fname)
			backupFname := filepath.Join(dn, "."+fn+".bak")
			e := os.Rename(fname, backupFname)
			if e != nil {
				log.Printf("[WARNING] failed to make backup of: %s\n", fname)
			}
		}
	}

	sb := stringbuffer.New()
	sb.Add(fmt.Sprintf(m[Header], time.UTC()))
	sb.Add(m[Imports])
	sb.Add(m[Targets])
	sb.Add("// PLAYGROUND START\n")
	sb.Add(m[Playground])
	sb.Add("// PLAYGROUND STOP\n")
	sb.Add(m[Init])
	for i := 0; i < len(alien); i++ {
		alien[i] = `"` + alien[i] + `"`
	}
	sb.Add(fmt.Sprintf(m[GoInstall], strings.Join(alien, ",")))
	sb.Add(m[Compile])
	sb.Add(m[PackageDef])
	sb.Add(m[PackageStart])
	for i := 0; i < len(pkgs); i++ {
		sb.Add(pkgs[i].Rep())
	}
	sb.Add("\n}\n")
	sb.Add(m[Main])
	ioutil.WriteFile(fname, sb.Bytes(), 0644)
}
Example #5
0
func DeleteObjects(dir string, pkgs []*dag.Package) {

	var stub, tmp string

	suffixes := []string{".8", ".6", ".5", ".o", ".vmo"}

	libdir := global.GetString("-lib")

	if libdir != "" {
		dir = libdir
	}

	for i := 0; i < len(pkgs); i++ {
		stub = filepath.Join(dir, pkgs[i].Name)
		for j := 0; j < len(suffixes); j++ {
			tmp = stub + suffixes[j]
			if handy.IsFile(tmp) {
				if global.GetBool("-dryrun") {
					say.Printf("[dryrun] rm: %s\n", tmp)
				} else {
					say.Printf("rm: %s\n", tmp)
					handy.Delete(tmp, false)
				}
			}
		}
	}

	// remove entire dir if empty after objects are deleted.
	// only do this if -lib is present, there is no reason to
	// do this (extra treewalk) if objects are in src directory
	if libdir != "" && handy.IsDir(dir) {
		walker.IncludeFile = func(s string) bool { return true }
		walker.IncludeDir = func(s string) bool { return true }
		if len(walker.PathWalk(dir)) == 0 {
			if global.GetBool("-dryrun") {
				fmt.Printf("[dryrun] rm: %s\n", dir)
			} else {
				say.Printf("rm: %s\n", dir)
				handy.RmRf(dir, true) // die on error
			}
		}
	}
}
Example #6
0
func ForkLink(output string, pkgs []*dag.Package, extra []*dag.Package, up2date bool) {

	var mainPKG *dag.Package

	gotMain := make([]*dag.Package, 0)

	for i := 0; i < len(pkgs); i++ {
		if pkgs[i].ShortName == "main" {
			gotMain = append(gotMain, pkgs[i])
		}
	}

	if len(gotMain) == 0 {
		log.Fatal("[ERROR] (linking) no main package found\n")
	}

	if len(gotMain) > 1 {
		choice := mainChoice(gotMain)
		mainPKG = gotMain[choice]
	} else {
		mainPKG = gotMain[0]
	}

	compiled := filepath.Join(libroot, mainPKG.Name) + suffix

	if up2date && !global.GetBool("-dryrun") && handy.IsFile(output) {
		if handy.ModifyTimestamp(compiled) < handy.ModifyTimestamp(output) {
			say.Printf("up 2 date: %s\n", output)
			return
		}
	}

	argv := make([]string, 0)
	argv = append(argv, pathLinker)

	switch global.GetString("-backend") {
	case "gc", "express":
		argv = append(argv, "-L")
		argv = append(argv, libroot)
	}

	argv = append(argv, "-o")
	argv = append(argv, output)

	// gcc get's this no matter what...
	if global.GetString("-backend") == "gcc" ||
		global.GetString("-backend") == "gccgo" {
		argv = append(argv, "-static")
	} else if global.GetBool("-static") {
		argv = append(argv, "-d")
	}

	switch global.GetString("-backend") {
	case "gccgo", "gcc":
		walker.IncludeFile = func(s string) bool {
			return strings.HasSuffix(s, ".o")
		}
		walker.IncludeDir = func(s string) bool { return true }

		for y := 0; y < len(includes); y++ {
			argv = append(argv, walker.PathWalk(includes[y])...)
		}
	case "gc", "express":
		for y := 0; y < len(includes); y++ {
			argv = append(argv, "-L")
			argv = append(argv, includes[y])
		}
	}

	argv = append(argv, compiled)

	if global.GetString("-backend") == "gcc" ||
		global.GetString("-backend") == "gccgo" {

		ss := stringset.New()

		if len(extra) > 0 {
			for j := 0; j < len(extra); j++ {
				// main package untestable using GCC
				if extra[j].ShortName != "main" {
					ss.Add(filepath.Join(libroot, extra[j].Name) + suffix)
				}
			}
		} else {
			for k := 0; k < len(pkgs); k++ {
				ss.Add(filepath.Join(libroot, pkgs[k].Name) + suffix)
			}
			ss.Remove(compiled)
		}

		if ss.Len() > 0 {
			argv = append(argv, ss.Slice()...)
		}
	}

	if global.GetBool("-dryrun") {
		linker := filepath.Base(pathLinker)
		fmt.Printf("%s %s || exit 1\n", linker, strings.Join(argv[1:], " "))
	} else {
		say.Println("linking  :", output)
		handy.StdExecve(argv, true)
	}
}
Example #7
0
func main() {

	var (
		ok, up2date bool
		e           error
		argv, args  []string
		config      [4]string
	)

	timer.Start("everything")
	defer reportTime()

	// possible config locations
	config[0] = filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "godag", "gdrc")
	config[1] = filepath.Join(os.Getenv("HOME"), ".config", "godag", "gdrc")
	config[2] = filepath.Join(os.Getenv("HOME"), ".gdrc")
	config[3] = filepath.Join(os.Getenv("PWD"), ".gdrc")

	for _, conf := range config {

		argv, ok = handy.ConfigToArgv(conf)

		if ok {
			args = parseArgv(argv)
			if len(args) > 0 {
				log.Print("[WARNING] non-option arguments in config file\n")
			}
		}
	}

	// small gorun version if single go-file is given
	if len(os.Args) > 1 && strings.HasSuffix(os.Args[1], ".go") && handy.IsFile(os.Args[1]) {
		say.Mute() // be silent unless error here
		single, name := dag.ParseSingle(os.Args[1])
		compiler.InitBackend()
		compiler.CreateArgv(single)
		up2date = compiler.Compile(single)
		if handy.GOOS() == "windows" {
			name = name + ".exe"
		}
		compiler.ForkLink(name, single, nil, up2date)
		args = os.Args[1:]
		args[0] = name
		handy.StdExecve(args, true)
		os.Exit(0)
	}

	// command line arguments overrides/appends config
	args = parseArgv(os.Args[1:])

	mkcomplete := global.GetString("-mkcomplete")
	if mkcomplete != "" {
		targets := dag.GetMakeTargets(mkcomplete)
		for _, t := range targets {
			fmt.Println(t)
		}
		os.Exit(0)
	}

	if len(args) > 0 {
		if len(args) > 1 {
			log.Print("[WARNING] len(input directories) > 1\n")
		}
		srcdir = args[0]
		if srcdir == "." {
			srcdir, e = os.Getwd()
			if e != nil {
				log.Fatal("[ERROR] can't find working directory\n")
			}
		}
	}

	// expand variables in includes
	for i := 0; i < len(includes); i++ {
		includes[i] = os.ExpandEnv(includes[i])
	}

	// expand variables in -lib
	global.SetString("-lib", os.ExpandEnv(global.GetString("-lib")))

	// expand variables in -output
	global.SetString("-output", os.ExpandEnv(global.GetString("-output")))

	if global.GetBool("-list") {
		printListing()
		os.Exit(0)
	}

	if global.GetBool("-help") {
		printHelp()
		os.Exit(0)
	}

	if global.GetBool("-version") {
		printVersion()
		os.Exit(0)
	}

	if len(args) == 0 {
		// give nice feedback if missing input dir
		if !handy.IsDir("src") {
			fmt.Printf("usage: gd [OPTIONS] src-directory\n")
			os.Exit(1)
		}
	}

	if global.GetBool("-quiet") {
		say.Mute()
	}

	handy.DirOrExit(srcdir)
	files = walker.PathWalk(filepath.Clean(srcdir))

	// gofmt on all files gathered
	if global.GetBool("-fmt") {
		compiler.FormatFiles(files)
		os.Exit(0)
	}

	// parse the source code, look for dependencies
	dgrph := dag.New()
	dgrph.Parse(srcdir, files)

	// print collected dependency info
	if global.GetBool("-print") {
		dgrph.PrintInfo()
		os.Exit(0)
	}

	// draw graphviz dot graph
	if global.GetString("-dot") != "" {
		dgrph.MakeDotGraph(global.GetString("-dot"))
		os.Exit(0)
	}

	// build  all external dependencies
	if global.GetBool("-external") {
		// update external dependencies
		if global.GetBool("-update-external") {
			dgrph.External(true)
		} else {
			dgrph.External(false)
		}
		os.Exit(0)
	}

	// sort graph based on dependencies
	dgrph.GraphBuilder()
	sorted := dgrph.Topsort()

	// clean only what we possibly could have generated…
	if global.GetBool("-clean") {
		compiler.DeleteObjects(srcdir, sorted)
		os.Exit(0)
	}

	// print packages sorted
	if global.GetBool("-sort") {
		for i := 0; i < len(sorted); i++ {
			fmt.Printf("%s\n", sorted[i].Name)
		}
		os.Exit(0)
	}

	// compile argv
	compiler.Init(srcdir, includes)
	if global.GetString("-lib") != "" {
		compiler.CreateLibArgv(sorted)
	} else {
		compiler.CreateArgv(sorted)
	}

	// gdmk
	if global.GetString("-gdmk") != "" {
		gdmake.Make(global.GetString("-gdmk"), sorted, dgrph.Alien().Slice())
		os.Exit(0)
	}

	// compile; up2date == true => 0 packages modified
	if global.GetBool("-dryrun") {
		compiler.Dryrun(sorted)
	} else {
		up2date = compiler.Compile(sorted) // updated parallel
	}

	// test
	if global.GetBool("-test") {
		os.Setenv("SRCROOT", srcdir)
		testMain, testDir, testLib := dgrph.MakeMainTest(srcdir)
		if global.GetString("-lib") != "" {
			compiler.CreateLibArgv(testMain)
		} else {
			compiler.CreateArgv(testMain)
		}
		if !global.GetBool("-dryrun") {
			compiler.Compile(testMain)
		}
		switch global.GetString("-backend") {
		case "gc", "express":
			compiler.ForkLink(global.GetString("-test-bin"), testMain, nil, false)
		case "gccgo", "gcc":
			compiler.ForkLink(global.GetString("-test-bin"), testMain, sorted, false)
		default:
			log.Fatalf("[ERROR] '%s' unknown back-end\n", global.GetString("-backend"))
		}
		compiler.DeletePackages(testMain)
		handy.Delete(testDir, false)
		if testLib != "" {
			handy.Delete(testLib, false)
		}
		testArgv := compiler.CreateTestArgv()
		if global.GetBool("-dryrun") {
			testArgv[0] = filepath.Base(testArgv[0])
			say.Printf("%s\n", strings.Join(testArgv, " "))
		} else {
			say.Printf("testing  : ")
			if global.GetBool("-verbose") || global.GetBool("-test.v") {
				say.Printf("\n")
			}
			ok = handy.StdExecve(testArgv, false)
			handy.Delete(global.GetString("-test-bin"), false)
			if !ok {
				os.Exit(1)
			}
		}

		// if packages contain both test-files and regular files
		// test-files should not be part of the objects, i.e. init
		// functions in test-packages can cause unexpected behaviour

		if compiler.ReCompile(sorted) {
			say.Printf("recompile: --tests\n")
			compiler.Compile(sorted)
		}

	}

	// link if ! up2date
	if global.GetString("-output") != "" {
		compiler.ForkLink(global.GetString("-output"), sorted, nil, up2date)
	} else if global.GetBool("-all") {
		compiler.ForkLinkAll(sorted, up2date)
	}

}