about summary refs log tree commit diff
path: root/configs/shared/.emacs.d/wpc/fs.el
blob: b1a79e280a5700ed2db4df9e78bc6ed1b36140dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
;;; fs.el --- Make working with the filesystem easier -*- lexical-binding: t -*-
;; Author: William Carroll <wpcarro@gmail.com>

;;; Commentary:
;; Ergonomic alternatives for working with the filesystem.

;;; Code:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dependencies
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(require 'f)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun fs/ensure-file (path)
  "Ensure that a file and its directories in `PATH' exist.
Will error for inputs with a trailing slash."
  (when (s-ends-with? "/" path)
    (error (format "Input path has trailing slash: %s" path)))
  (->> path
       f-dirname
       fs/ensure-dir)
  (f-touch path))

(f-dirname "/tmp/a/b/file.txt")

(defun fs/ensure-dir (path)
  "Ensure that a directory and its ancestor directories in `PATH' exist."
  (->> path
       f-split
       (apply #'f-mkdir)))

(defun fs/ls (dir &optional full-path?)
  "List the files in `DIR' one-level deep.
Should behave similarly in spirit to the Unix command, ls.
If `FULL-PATH?' is set, return the full-path of the files."
  (-drop 2 (directory-files dir full-path?)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; TODO: Support `refute' function / macro.
(ert-deftest fs/test/ensure-file ()
  (let ((file "/tmp/file/a/b/c/file.txt"))
    ;; Ensure this file doesn't exist first to prevent false-positives.
    (f-delete file t)
    (fs/ensure-file file)
    (should (and (f-exists? file)
                 (f-file? file)))))

(ert-deftest fs/test/ensure-dir ()
  (let ((dir "/tmp/dir/a/b/c"))
    ;; Ensure the directory doesn't exist.
    (f-delete dir t)
    (fs/ensure-dir dir)
    (should (and (f-exists? dir)
                 (f-dir? dir)))))

(provide 'fs)
;;; fs.el ends here