staticmd.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package staticmd
  2. import (
  3. "os"
  4. "os/exec"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. func init() {
  11. runnable = cmd{}
  12. }
  13. // logger component for printing status messages to stderr
  14. type logger interface {
  15. Debug(string, ...interface{})
  16. Error(string, ...interface{})
  17. Info(string, ...interface{})
  18. }
  19. var stat = os.Stat
  20. var isNotExist = os.IsNotExist
  21. type runner interface {
  22. Run(string, ...string) ([]byte, error)
  23. }
  24. var runnable runner
  25. type cmd struct{}
  26. func (self cmd) Run(command string, args ...string) ([]byte, error) {
  27. return exec.Command(command, args...).Output()
  28. }
  29. // check that a path exists
  30. // does not care if it is a directory
  31. // will not say whether user has rw access, but
  32. // will throw an error if the user cannot read the parent directory
  33. func exists(path string) (bool, error) {
  34. _, err := stat(path)
  35. if err == nil {
  36. return true, nil
  37. }
  38. if isNotExist(err) {
  39. return false, nil
  40. }
  41. return false, err
  42. }
  43. // if within a git repo, gets git version as a short-hash
  44. // otherwise falls back to a unix timestamp
  45. func version(dir string) string {
  46. version := strconv.FormatInt(time.Now().Unix(), 10)
  47. out, err := runnable.Run("sh", "-c", "git", "-C", dir, "rev-parse", "--short", "HEAD")
  48. if err == nil {
  49. version = strings.Trim(string(out), "\n")
  50. }
  51. return version
  52. }
  53. // remove the path and extension from a given filename
  54. func basename(name string) string {
  55. return filepath.Base(strings.TrimSuffix(name, filepath.Ext(name)))
  56. }