save.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Package save decides where a book is written and writes it there safely.
  2. //
  3. // It implements the -SAVE rules from the README: folder versus file targets,
  4. // the .epub / .kepub.epub extension, creation of missing folders, and
  5. // overwrite protection unless -FORCE is given. Writes are atomic, so a failed
  6. // run never leaves a partial file behind.
  7. package save
  8. import (
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/fs"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "unicode"
  17. "golang.org/x/text/unicode/norm"
  18. )
  19. const (
  20. extEPUB = ".epub"
  21. extKEPUB = ".kepub.epub"
  22. // maxSlugLen caps generated filenames well below filesystem limits.
  23. maxSlugLen = 80
  24. // fallbackName is used when a title produces an empty slug, for example
  25. // a title written entirely in a non-Latin script.
  26. fallbackName = "article"
  27. )
  28. // ErrExists reports that the output file already exists and overwriting was
  29. // not allowed.
  30. var ErrExists = errors.New("already exists")
  31. // ErrKEPUBName reports a .kepub.epub output path without KEPUB output
  32. // enabled. Kobo would open such a plain EPUB in its KEPUB renderer.
  33. var ErrKEPUBName = errors.New("a .kepub.epub file needs -KEPUB (or use a .epub filename)")
  34. // Target is a resolved -SAVE value. The final filename is known up front for
  35. // file targets; for folder targets it depends on the article title.
  36. type Target struct {
  37. file string // absolute file path, set for file targets
  38. dir string // absolute folder, set for folder targets
  39. ext string // extension used for folder targets
  40. // Note is a message for the user about an adjustment made to the path,
  41. // or empty.
  42. Note string
  43. }
  44. // Resolve interprets the -SAVE argument. kepub selects the .kepub.epub
  45. // extension.
  46. func Resolve(arg string, kepub bool) (Target, error) {
  47. if arg == "" {
  48. return Target{}, errors.New("empty path")
  49. }
  50. arg, err := expandHome(arg)
  51. if err != nil {
  52. return Target{}, err
  53. }
  54. ext := extEPUB
  55. if kepub {
  56. ext = extKEPUB
  57. }
  58. if isFolder(arg) {
  59. dir, err := filepath.Abs(arg)
  60. if err != nil {
  61. return Target{}, err
  62. }
  63. return Target{dir: dir, ext: ext}, nil
  64. }
  65. var note string
  66. lower := strings.ToLower(arg)
  67. switch {
  68. case strings.HasSuffix(lower, extKEPUB):
  69. if !kepub {
  70. return Target{}, fmt.Errorf("%s: %w", arg, ErrKEPUBName)
  71. }
  72. case strings.HasSuffix(lower, extEPUB):
  73. if kepub {
  74. renamed := arg[:len(arg)-len(extEPUB)] + extKEPUB
  75. note = fmt.Sprintf("saving as %s so Kobo opens it with the KEPUB renderer", filepath.Base(renamed))
  76. arg = renamed
  77. }
  78. default:
  79. arg += ext
  80. }
  81. file, err := filepath.Abs(arg)
  82. if err != nil {
  83. return Target{}, err
  84. }
  85. return Target{file: file, Note: note}, nil
  86. }
  87. // Known reports whether the output filename is known before the article
  88. // title is, which allows checking for an existing file before fetching.
  89. func (t Target) Known() bool {
  90. return t.file != ""
  91. }
  92. // Path returns the output file path. title is only used for folder targets.
  93. func (t Target) Path(title string) string {
  94. if t.file != "" {
  95. return t.file
  96. }
  97. return filepath.Join(t.dir, Slug(title)+t.ext)
  98. }
  99. // isFolder reports whether arg names a folder: it ends in a path separator
  100. // or is an existing directory.
  101. func isFolder(arg string) bool {
  102. if os.IsPathSeparator(arg[len(arg)-1]) {
  103. return true
  104. }
  105. info, err := os.Stat(arg)
  106. return err == nil && info.IsDir()
  107. }
  108. // expandHome replaces a leading "~" with the user's home directory, for
  109. // paths the shell did not expand (for example, quoted ones).
  110. func expandHome(arg string) (string, error) {
  111. if arg != "~" && !(len(arg) > 1 && arg[0] == '~' && os.IsPathSeparator(arg[1])) {
  112. return arg, nil
  113. }
  114. home, err := os.UserHomeDir()
  115. if err != nil {
  116. return "", fmt.Errorf("expanding ~: %w", err)
  117. }
  118. return home + arg[1:], nil
  119. }
  120. // Slug turns a title into a safe filename stem: lowercase ASCII letters and
  121. // digits separated by single dashes, at most 80 characters. Accents are
  122. // removed ("Café" → "cafe"). It never contains path separators, so a title
  123. // cannot move the file out of the chosen folder.
  124. func Slug(title string) string {
  125. var b strings.Builder
  126. dash := false
  127. for _, r := range norm.NFD.String(title) {
  128. switch {
  129. case unicode.Is(unicode.Mn, r):
  130. // Combining accent left over from NFD; drop it.
  131. case r < unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r)):
  132. if dash && b.Len() > 0 {
  133. b.WriteByte('-')
  134. }
  135. dash = false
  136. b.WriteRune(unicode.ToLower(r))
  137. default:
  138. dash = true
  139. }
  140. }
  141. s := b.String()
  142. if len(s) > maxSlugLen {
  143. s = strings.TrimRight(s[:maxSlugLen], "-")
  144. }
  145. if s == "" {
  146. return fallbackName
  147. }
  148. return s
  149. }
  150. // CheckExists returns an error wrapping ErrExists if path already exists.
  151. // It is the early check made before work is done; Write repeats the check
  152. // atomically.
  153. func CheckExists(path string) error {
  154. info, err := os.Lstat(path)
  155. switch {
  156. case errors.Is(err, fs.ErrNotExist):
  157. return nil
  158. case err != nil:
  159. return err
  160. case info.IsDir():
  161. return fmt.Errorf("%s is a folder", path)
  162. default:
  163. return fmt.Errorf("%s %w", path, ErrExists)
  164. }
  165. }
  166. // Write writes src to path, creating missing folders. Unless force is set,
  167. // an existing file is never modified and an error wrapping ErrExists is
  168. // returned. The content is written to a temporary file and renamed into
  169. // place, so path never holds a partial book; on failure, nothing the run
  170. // created is left behind.
  171. func Write(path string, src io.WriterTo, force bool) (err error) {
  172. dir := filepath.Dir(path)
  173. if err := os.MkdirAll(dir, 0o755); err != nil {
  174. return fmt.Errorf("creating folder: %w", err)
  175. }
  176. // Without force, claim the name first. O_EXCL fails if the file exists,
  177. // including one created by another program since CheckExists ran.
  178. reserved := false
  179. if !force {
  180. f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
  181. if errors.Is(err, fs.ErrExist) {
  182. return fmt.Errorf("%s %w", path, ErrExists)
  183. }
  184. if err != nil {
  185. return err
  186. }
  187. if err := f.Close(); err != nil {
  188. os.Remove(path)
  189. return err
  190. }
  191. reserved = true
  192. }
  193. tmp, err := os.CreateTemp(dir, ".rekopub-*.tmp")
  194. if err != nil {
  195. if reserved {
  196. os.Remove(path)
  197. }
  198. return err
  199. }
  200. defer func() {
  201. if err != nil {
  202. tmp.Close()
  203. os.Remove(tmp.Name())
  204. if reserved {
  205. os.Remove(path)
  206. }
  207. }
  208. }()
  209. if _, err := src.WriteTo(tmp); err != nil {
  210. return err
  211. }
  212. if err := tmp.Sync(); err != nil {
  213. return err
  214. }
  215. if err := tmp.Close(); err != nil {
  216. return err
  217. }
  218. // CreateTemp uses mode 0600; books should be readable like any other
  219. // file. Best effort: FAT32 (a Kobo over USB) has no permissions.
  220. _ = os.Chmod(tmp.Name(), 0o644)
  221. return os.Rename(tmp.Name(), path)
  222. }