io.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // This package defines several top level IO functions for interacting with
  2. // issues and collections of issues.
  3. //
  4. // Examples:
  5. //
  6. // To check if a folder is spec compliant:
  7. // ...
  8. // if issues.IsIssue(path_to_folder) {
  9. // process_issue(path_to_folder)
  10. // }
  11. //
  12. // Additionally, to check if a folder is a collection of spec compliant issues:
  13. // ...
  14. // if issues.IsIssueCollection(path_to_folder) {
  15. // process_collection(path_to_folder)
  16. // }
  17. //
  18. // To write an [Issue] object to disk:
  19. // ...
  20. // // NOT IMPLEMENTED
  21. //
  22. // To remove an [Issue] object from disk:
  23. // ...
  24. // // NOT IMPLEMENTED
  25. package issues
  26. import (
  27. "errors"
  28. "fmt"
  29. "log"
  30. "math/rand"
  31. "os"
  32. "os/exec"
  33. "path/filepath"
  34. "slices"
  35. "strings"
  36. "time"
  37. "github.com/google/shlex"
  38. )
  39. // converts file from []string to string, reports errors
  40. func readPath(path string) (output string, err error) { // TODO DEPRECATE
  41. content, err := os.ReadFile(path)
  42. if err != nil {
  43. return "", err
  44. }
  45. for _, line := range content {
  46. output = output + string(line)
  47. }
  48. return output, nil
  49. }
  50. // The quote string used to generate a template description
  51. type Template string
  52. var DescriptionTemplate = Template(`# Please provide a short, one line description.
  53. # Include any additional comments here.
  54. # -----------
  55. # Note: Lines beginning with "#" are automatically ignored.
  56. # Note: It is recommended to leave a blank line after the short description.`)
  57. // generates template description files
  58. func GenerateTemplate(t Template, path string) error {
  59. err := os.WriteFile(path, []byte(DescriptionTemplate), 0755)
  60. return err
  61. }
  62. // parses template description files, removing any lines beginning with #
  63. //
  64. // Note: the function deletes the template file upon completion.
  65. func ReadTemplate(path string) (lines []string, err error) {
  66. data, err := os.ReadFile(path)
  67. if err != nil {
  68. return []string{}, err
  69. }
  70. sdata := string(data)
  71. slines := strings.SplitSeq(sdata, "\n")
  72. for line := range slines {
  73. line = line + "\n"
  74. if string(line[0]) != "#" {
  75. lines = append(lines, line)
  76. }
  77. }
  78. return lines, err
  79. }
  80. // InvokeEditor invokes the system's configured editor on the specified path,
  81. // and reports any errors.
  82. //
  83. // InvokeEditor will attempt to determine the editor command in the following
  84. // order:
  85. //
  86. // 1. The $ISSUES_EDITOR environment variable
  87. //
  88. // 2. The $GIT_CONFIG environment variable
  89. //
  90. // 3. The $EDITOR environment variable
  91. //
  92. // Finally, if no configured editor is found, the program will exit with status
  93. // code 2
  94. //
  95. // TODO(InvokeEditor) implement a channel & goroutine based concurrency lifecycle
  96. func InvokeEditor(path string) error {
  97. // determine editor
  98. // 1. Git config
  99. // 2. $EDITOR
  100. // 3. Panic?
  101. editor := os.Getenv("ISSUES_EDITOR")
  102. // if issue editor wasn't present, check git editor
  103. if editor == "" {
  104. editor = os.Getenv("GIT_EDITOR")
  105. }
  106. // if git editor wasn't present, check if editor set
  107. if editor == "" {
  108. editor = os.Getenv("EDITOR")
  109. }
  110. // if editor wasn't present, error out
  111. if editor == "" {
  112. log.Fatal("no editor set by system")
  113. os.Exit(2)
  114. }
  115. // execute editor
  116. editorCmd, err := shlex.Split(editor)
  117. if err != nil {
  118. log.Fatal("could not parse editor")
  119. os.Exit(2)
  120. }
  121. editorCmd = append(editorCmd, path)
  122. cmd := exec.Command(editorCmd[0], editorCmd[1:]...)
  123. cmd.Stdin = os.Stdin // pass stdin to cmd
  124. cmd.Stdout = os.Stdout // pass stdout to cmd
  125. cmd.Stderr = os.Stderr // pass stderr to cmd
  126. // wait for cmd and error out if err
  127. if err := cmd.Run(); err != nil {
  128. return fmt.Errorf("editor execution failed: %w", err)
  129. }
  130. return nil
  131. }
  132. // EditTemplate wraps GenerateTemplate and ReadTemplate, providing
  133. // both with a tempfile. EditTemplate then reports the content of the tempfile
  134. // after any modifications made by the editFunc callback and any encountered
  135. // errors.
  136. //
  137. // Note: A pre-built editor callback is provided. See InvokeEditor for more.
  138. func EditTemplate(t Template, editFunc func(path string) error) (data []string, err error) {
  139. // note: wraps writeText
  140. var seededRand = rand.New(
  141. rand.NewSource(time.Now().UnixNano()))
  142. makeID := func(length int) string {
  143. var charset = "abcdefghijklmnopqrstuvwxyz" +
  144. "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  145. b := make([]byte, length)
  146. for i := range b {
  147. b[i] = charset[seededRand.Intn(len(charset))]
  148. }
  149. return string(b)
  150. }
  151. // get get temp file
  152. tempfile, err := os.CreateTemp("", makeID(8))
  153. if err != nil {
  154. return []string{}, nil
  155. }
  156. cleanup := func() {
  157. err = os.Remove(tempfile.Name())
  158. if err != nil {
  159. panic(err)
  160. }
  161. }
  162. defer cleanup()
  163. err = GenerateTemplate(DescriptionTemplate, tempfile.Name())
  164. if err != nil {
  165. return []string{}, nil
  166. }
  167. // invoke editor
  168. err = editFunc(tempfile.Name())
  169. if err != nil {
  170. return []string{}, nil
  171. }
  172. // get data
  173. result, err := ReadTemplate(tempfile.Name())
  174. return result, err
  175. }
  176. // Reports true when the specified path conforms to the minimum Poorman spec
  177. func IsIssue(path string) bool {
  178. files, err := os.ReadDir(path)
  179. if err != nil {
  180. return false
  181. }
  182. var specFiles []bool
  183. for _, file := range files {
  184. if file.Name() == "description" || file.Name() == "status" {
  185. specFiles = append(specFiles, true)
  186. }
  187. }
  188. if len(specFiles) >= 2 {
  189. return true
  190. }
  191. return false
  192. }
  193. // Reports true when the specified path is a directory of Issues
  194. func IsIssueCollection(path string) bool {
  195. if IsIssue(path) {
  196. return false
  197. }
  198. files, err := os.ReadDir(path)
  199. if err != nil {
  200. return false
  201. }
  202. var isIssue []bool
  203. for _, file := range files {
  204. if IsIssue(path + "/" + file.Name()) {
  205. isIssue = append(isIssue, true)
  206. }
  207. }
  208. if len(isIssue) > 0 {
  209. return true
  210. }
  211. return false
  212. }
  213. // Writes a issue to disk
  214. func WriteIssue(issue Issue, overwrite bool) (success bool, err error) {
  215. if IsIssue(issue.Path) && !overwrite {
  216. return false, errors.New("path exists")
  217. }
  218. // make base directory (effectively, the title)
  219. err = os.Mkdir(issue.Path, 0755)
  220. if err != nil && !overwrite {
  221. return false, err
  222. }
  223. // Write Fields
  224. f := []Field{issue.Description, issue.Status}
  225. for _, field := range f {
  226. if len(field.Path) > 0 { // skip empty paths
  227. path := filepath.Join(issue.Path, field.Path)
  228. err = os.WriteFile(path, []byte(field.Data), 0755)
  229. if err != nil {
  230. return false, err // test by overwrite path
  231. }
  232. }
  233. }
  234. // Write Tags
  235. if len(issue.Tags.Path) > 0 { // skip tags with no path init
  236. err = os.Mkdir(filepath.Join(issue.Path, issue.Tags.Path), 0755)
  237. if err != nil && !overwrite {
  238. return false, err
  239. }
  240. for _, field := range issue.Tags.Fields {
  241. if len(field.Path) > 0 { // skip empty paths
  242. path := filepath.Join(issue.Path, issue.Tags.Path, field.Path)
  243. err = os.WriteFile(path, []byte(field.Data), 0755)
  244. if err != nil {
  245. return false, err // test by overwrite path
  246. }
  247. }
  248. }
  249. }
  250. // Write Blockedby
  251. if len(issue.Blockedby.Path) > 0 { // skip blockedby with no path init
  252. err = os.Mkdir(filepath.Join(issue.Path, issue.Blockedby.Path), 0755)
  253. if err != nil && !overwrite {
  254. return false, err
  255. }
  256. for _, field := range issue.Blockedby.Fields {
  257. if len(field.Path) > 0 { // skip empty paths
  258. path := filepath.Join(issue.Path, issue.Blockedby.Path, field.Path)
  259. err = os.WriteFile(path, []byte(field.Data), 0755)
  260. if err != nil {
  261. return false, err // test by overwrite path
  262. }
  263. }
  264. }
  265. if err != nil && !overwrite {
  266. return false, err
  267. }
  268. }
  269. return true, nil
  270. }
  271. // Removes any fields from disk from a VariadicField that are not represented
  272. // in memory and reports the first error encountered.
  273. func (vf VariadicField) CleanDisk(issue Issue, ignoreData bool) error {
  274. dirContents, err := os.ReadDir(filepath.Join(issue.Path, vf.Path))
  275. if err != nil {
  276. return err
  277. }
  278. var fieldsInMemory []string
  279. for _, field := range vf.Fields {
  280. fieldsInMemory = append(fieldsInMemory, field.Path)
  281. }
  282. for _, file := range dirContents {
  283. if !slices.Contains(fieldsInMemory, file.Name()) {
  284. // check if has data
  285. bytes, err := os.ReadFile(filepath.Join(issue.Path, vf.Path, file.Name()))
  286. if err != nil {
  287. return err
  288. }
  289. // if has data, and not ignore data
  290. if len(bytes) > 0 && ignoreData {
  291. return fmt.Errorf("%s has data, will not remove",
  292. filepath.Join(issue.Path, vf.Path, file.Name()))
  293. }
  294. // remove file
  295. err = os.Remove(filepath.Join(issue.Path, vf.Path, file.Name()))
  296. if err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. return nil
  302. }