reexec.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package reexec
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. )
  8. var registeredInitializers = make(map[string]func())
  9. // Register adds an initialization func under the specified name
  10. func Register(name string, initializer func()) {
  11. if _, exists := registeredInitializers[name]; exists {
  12. panic(fmt.Sprintf("reexec func already registered under name %q", name))
  13. }
  14. registeredInitializers[name] = initializer
  15. }
  16. // Init is called as the first part of the exec process and returns true if an
  17. // initialization function was called.
  18. func Init() bool {
  19. initializer, exists := registeredInitializers[os.Args[0]]
  20. if exists {
  21. initializer()
  22. return true
  23. }
  24. return false
  25. }
  26. func naiveSelf() string {
  27. name := os.Args[0]
  28. if filepath.Base(name) == name {
  29. if lp, err := exec.LookPath(name); err == nil {
  30. return lp
  31. }
  32. }
  33. // handle conversion of relative paths to absolute
  34. if absName, err := filepath.Abs(name); err == nil {
  35. return absName
  36. }
  37. // if we couldn't get absolute name, return original
  38. // (NOTE: Go only errors on Abs() if os.Getwd fails)
  39. return name
  40. }