Command line client for Write.as https://write.as/apps/cli
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.0 KiB

  1. package fileutils
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strings"
  7. )
  8. // Exists returns whether or not the given file exists
  9. func Exists(p string) bool {
  10. if _, err := os.Stat(p); !os.IsNotExist(err) {
  11. return true
  12. }
  13. return false
  14. }
  15. // WriteData writes data to the given path, creating the file if necessary.
  16. func WriteData(path string, data []byte) {
  17. f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
  18. if err != nil {
  19. fmt.Println(err)
  20. }
  21. // TODO: check for Close() errors
  22. // https://github.com/ncw/swift/blob/master/swift.go#L170
  23. defer f.Close()
  24. _, err = f.Write(data)
  25. if err != nil {
  26. fmt.Println(err)
  27. }
  28. }
  29. // ReadData returns file data as an array of lines from the file.
  30. func ReadData(p string) *[]string {
  31. f, err := os.Open(p)
  32. if err != nil {
  33. return nil
  34. }
  35. defer f.Close()
  36. lines := []string{}
  37. scanner := bufio.NewScanner(f)
  38. for scanner.Scan() {
  39. lines = append(lines, scanner.Text())
  40. }
  41. if err := scanner.Err(); err != nil {
  42. return nil
  43. }
  44. return &lines
  45. }
  46. // RemoveLine searches for the line that starts with the given value and,
  47. // if found, removes it and saves the updated file.
  48. func RemoveLine(p, startsWith string) {
  49. f, err := os.Open(p)
  50. if err != nil {
  51. return
  52. }
  53. defer f.Close()
  54. var outText string
  55. found := false
  56. scanner := bufio.NewScanner(f)
  57. for scanner.Scan() {
  58. if strings.HasPrefix(scanner.Text(), startsWith) {
  59. found = true
  60. } else {
  61. outText += scanner.Text() + string('\n')
  62. }
  63. }
  64. if err := scanner.Err(); err != nil {
  65. return
  66. }
  67. if found {
  68. WriteData(p, []byte(outText))
  69. }
  70. }
  71. // FindLine searches the given file for a line that begins with the given
  72. // string.
  73. func FindLine(p, startsWith string) string {
  74. f, err := os.Open(p)
  75. if err != nil {
  76. return ""
  77. }
  78. defer f.Close()
  79. scanner := bufio.NewScanner(f)
  80. for scanner.Scan() {
  81. if strings.HasPrefix(scanner.Text(), startsWith) {
  82. return scanner.Text()
  83. }
  84. }
  85. if err := scanner.Err(); err != nil {
  86. return ""
  87. }
  88. return ""
  89. }
  90. func DeleteFile(p string) error {
  91. return os.Remove(p)
  92. }