staticmd.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. type runner interface {
  20. Run(string, ...string) ([]byte, error)
  21. }
  22. var stat = os.Stat
  23. var isNotExist = os.IsNotExist
  24. var extensions = []string{".md", ".mkd", ".markdown"}
  25. var runnable runner
  26. type cmd struct{}
  27. // a command runner to abstract exec
  28. func (self cmd) Run(command string, args ...string) ([]byte, error) {
  29. return exec.Command(command, args...).Output()
  30. }
  31. // check that a path exists
  32. // does not care if it is a directory
  33. // will not say whether user has rw access, but
  34. // will throw an error if the user cannot read the parent directory
  35. func exists(path string) (bool, error) {
  36. _, err := stat(path)
  37. if err == nil {
  38. return true, nil
  39. }
  40. if isNotExist(err) {
  41. return false, nil
  42. }
  43. return false, err
  44. }
  45. // if within a git repo, gets git version as a short-hash
  46. // otherwise falls back to a unix timestamp
  47. func version(dir string) string {
  48. version := strconv.FormatInt(time.Now().Unix(), 10)
  49. out, err := runnable.Run("sh", "-c", "git", "-C", dir, "rev-parse", "--short", "HEAD")
  50. if err == nil {
  51. version = strings.Trim(string(out), "\n")
  52. }
  53. return version
  54. }
  55. // remove the path and extension from a given filename
  56. func basename(name string) string {
  57. return filepath.Base(strings.TrimSuffix(name, filepath.Ext(name)))
  58. }
  59. // check for markdown in supported extensions array
  60. func isMarkdown(path string) bool {
  61. for i := range extensions {
  62. if strings.HasSuffix(path, extensions[i]) {
  63. return true
  64. }
  65. }
  66. return false
  67. }