org-persist.el 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. ;;; org-persist.el --- Persist data across Emacs sessions -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2021-2022 Free Software Foundation, Inc.
  3. ;; Author: Ihor Radchenko <yantar92 at gmail dot com>
  4. ;; Keywords: cache, storage
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; This file implements persistant data storage across Emacs sessions.
  19. ;; Both global and buffer-local data can be stored.
  20. ;;
  21. ;; Most common data type is variable data. However, other data types
  22. ;; can also be stored.
  23. ;;
  24. ;; Persistent data is stored in individual files. Each of the files
  25. ;; can contain a collection of related data, which is particularly
  26. ;; useful when, say, several variables cross-reference each-other's
  27. ;; data-cells and we want to preserve their circular structure.
  28. ;;
  29. ;; Each data collection can be associated with a local or remote file,
  30. ;; its inode number, or contents hash. The persistent data collection
  31. ;; can later be accessed using either file bufer, file, inode, or
  32. ;; contents hash.
  33. ;;
  34. ;; The data collections can be versioned and removed upon expiry.
  35. ;;
  36. ;; In the code below I will use the following naming conventions:
  37. ;; 1. Container :: a type of data to be stored
  38. ;; Containers can store elisp variables, files, and version
  39. ;; numbers. Each container can be customized with container
  40. ;; options. For example, "elisp" container is customized with
  41. ;; variable symbol. ("elisp" variable) is a container storing
  42. ;; Lisp variable value. Similarly, ("version" "2.0") container
  43. ;; will store version number.
  44. ;; 2. Associated :: an object the container is associated with. The
  45. ;; object can be a buffer, file, inode number, file contents hash,
  46. ;; a generic key, or multiple of them. Associated can also be nil.
  47. ;; 3. Data collection :: a list of containers linked to an associated
  48. ;; object/objects. Each data collection can also have auxiliary
  49. ;; records. Their only purpose is readability of the collection
  50. ;; index.
  51. ;; 4. Index file :: a file listing all the stored data collections.
  52. ;; 5. Persist file :: a file holding data values or references to
  53. ;; actual data values for a single data collection. This file
  54. ;; contains an alist associating each data container in data
  55. ;; collection with its value or a reference to the actual value.
  56. ;;
  57. ;; All the persistent data is stored in `org-persist-directory'. The data
  58. ;; collections are listed in `org-persist-index-file' and the actual data is
  59. ;; stored in UID-style subfolders.
  60. ;;
  61. ;; The `org-persist-index-file' stores the value of `org-persist--index'.
  62. ;;
  63. ;; Each collection is represented as a plist containing the following
  64. ;; properties:
  65. ;; - `:container' : list of data continers to be stored in single
  66. ;; file;
  67. ;; - `:persist-file': data file name;
  68. ;; - `:associated' : list of associated objects;
  69. ;; - `:last-access' : last date when the container has been read;
  70. ;; - `:expiry' : list of expiry conditions.
  71. ;; - all other keywords are ignored
  72. ;;
  73. ;; The available types of data containers are:
  74. ;; 1. ("elisp" variable-symbol) or just variable-symbol :: Storing
  75. ;; elisp variable data.
  76. ;; 2. ("file") :: Store a copy of the associated file preserving the
  77. ;; extension.
  78. ;; 3. ("version" "version number") :: Version the data collection.
  79. ;; If the stored collection has different version than "version
  80. ;; number", disregard it.
  81. ;; 4. ("url") :: Store a downloaded copy of URL object.
  82. ;;
  83. ;; The data collections can expire, in which case they will be removed
  84. ;; from the persistent storage at the end of Emacs session. The
  85. ;; expiry condition can be set when saving/registering data
  86. ;; containers. The expirty condition can be `never' - data will never
  87. ;; expire; `nil' - data will expire at the end of current Emacs session;
  88. ;; a number - data will expire after the number days from last access;
  89. ;; a function - data will expire if the function, called with a single
  90. ;; argument - collection, returns non-nil.
  91. ;;; Code:
  92. (require 'org-compat)
  93. (require 'org-id)
  94. (require 'xdg nil t)
  95. (defconst org-persist--storage-version "2.1"
  96. "Persistent storage layout version.")
  97. (defgroup org-persist nil
  98. "Persistent cache for Org mode."
  99. :tag "Org persist"
  100. :group 'org)
  101. (defcustom org-persist-directory (expand-file-name
  102. (org-file-name-concat
  103. (let ((cache-dir (when (fboundp 'xdg-cache-home)
  104. (xdg-cache-home))))
  105. (if (or (seq-empty-p cache-dir)
  106. (not (file-exists-p cache-dir))
  107. (file-exists-p (org-file-name-concat
  108. user-emacs-directory
  109. "org-persist")))
  110. user-emacs-directory
  111. cache-dir))
  112. "org-persist/"))
  113. "Directory where the data is stored."
  114. :group 'org-persist
  115. :type 'directory)
  116. (defcustom org-persist-remote-files 100
  117. "Whether to keep persistent data for remote files.
  118. When this variable is nil, never save persitent data associated with
  119. remote files. When `t', always keep the data. When
  120. `check-existence', contact remote server containing the file and only
  121. keep the data when the file exists on the server. When a number, keep
  122. up to that number persistent values for remote files.
  123. Note that the last option `check-existence' may cause Emacs to show
  124. password prompts to log in."
  125. :group 'org-persist
  126. :type '(choice (const :tag "Never" nil)
  127. (const :tag "Always" t)
  128. (number :tag "Keep not more than X files")
  129. (const :tag "Check if exist on remote" 'check-existence)))
  130. (defcustom org-persist-default-expiry 30
  131. "Default expiry condition for persistent data.
  132. When this variable is `nil', all the data vanishes at the end of Emacs
  133. session. When `never', the data never vanishes. When a number, the
  134. data is deleted that number days after last access. When a function,
  135. it should be a function returning non-nil when the data is expired. The
  136. function will be called with a single argument - collection."
  137. :group 'org-persist
  138. :type '(choice (const :tag "Never" 'never)
  139. (const :tag "Always" nil)
  140. (number :tag "Keep N days")
  141. (function :tag "Function")))
  142. (defconst org-persist-index-file "index"
  143. "File name used to store the data index.")
  144. (defvar org-persist-before-write-hook nil
  145. "Abnormal hook ran before saving data.
  146. The hook must accept the same arguments as `org-persist-write'.
  147. The hooks will be evaluated until a hook returns non-nil.
  148. If any of the hooks return non-nil, do not save the data.")
  149. (defvar org-persist-before-read-hook nil
  150. "Abnormal hook ran before reading data.
  151. The hook must accept the same arguments as `org-persist-read'.
  152. The hooks will be evaluated until a hook returns non-nil.
  153. If any of the hooks return non-nil, do not read the data.")
  154. (defvar org-persist-after-read-hook nil
  155. "Abnormal hook ran after reading data.
  156. The hook must accept the same arguments as `org-persist-read'.")
  157. (defvar org-persist--index nil
  158. "Global index.
  159. The index is a list of plists. Each plist contains information about
  160. persistent data storage. Each plist contains the following
  161. properties:
  162. - `:container' : list of data continers to be stored in single file
  163. - `:persist-file': data file name
  164. - `:associated' : list of associated objects
  165. - `:last-access' : last date when the container has been read
  166. - `:expiry' : list of expiry conditions
  167. - all other keywords are ignored.")
  168. (defvar org-persist--index-hash nil
  169. "Hash table storing `org-persist--index'. Used for quick access.
  170. They keys are conses of (container . associated).")
  171. (defvar org-persist--report-time 0.5
  172. "Whether to report read/write time.
  173. When the value is a number, it is a threshold number of seconds. If
  174. the read/write time of a single variable exceeds the threashold, a
  175. message is displayed.
  176. When the value is a non-nil non-number, always display the message.
  177. When the value is nil, never diplay the message.")
  178. ;;;; Common functions
  179. (defun org-persist--display-time (duration format &rest args)
  180. "Report DURATION according to FORMAT + ARGS message.
  181. FORMAT and ARGS are passed to `message'."
  182. (when (or (and org-persist--report-time
  183. (numberp org-persist--report-time)
  184. (>= duration org-persist--report-time))
  185. (and org-persist--report-time
  186. (not (numberp org-persist--report-time))))
  187. (apply #'message
  188. (format "org-persist: %s took %%.2f sec" format)
  189. (append args (list duration)))))
  190. (defun org-persist--read-elisp-file (&optional buffer-or-file)
  191. "Read elisp data from BUFFER-OR-FILE or current buffer."
  192. (unless buffer-or-file (setq buffer-or-file (current-buffer)))
  193. (with-temp-buffer
  194. (if (bufferp buffer-or-file)
  195. (set-buffer buffer-or-file)
  196. (insert-file-contents buffer-or-file))
  197. (condition-case err
  198. (let ((coding-system-for-read 'utf-8)
  199. (read-circle t)
  200. (start-time (float-time)))
  201. ;; FIXME: Reading sometimes fails to read circular objects.
  202. ;; I suspect that it happens when we have object reference
  203. ;; #N# read before object definition #N=. If it is really
  204. ;; so, it should be Emacs bug - either in `read' or in
  205. ;; `prin1'. Meanwhile, just fail silently when `read'
  206. ;; fails to parse the saved cache object.
  207. (prog1
  208. (read (current-buffer))
  209. (org-persist--display-time
  210. (- (float-time) start-time)
  211. "Reading from %S" buffer-or-file)))
  212. ;; Recover gracefully if index file is corrupted.
  213. (error
  214. ;; Remove problematic file.
  215. (unless (bufferp buffer-or-file) (delete-file buffer-or-file))
  216. ;; Do not report the known error to user.
  217. (unless (string-match-p "Invalid read syntax" (error-message-string err))
  218. (warn "Emacs reader failed to read data in %S. The error was: %S"
  219. buffer-or-file (error-message-string err)))
  220. nil))))
  221. (defun org-persist--write-elisp-file (file data &optional no-circular pp)
  222. "Write elisp DATA to FILE."
  223. (let ((print-circle (not no-circular))
  224. print-level
  225. print-length
  226. print-quoted
  227. (print-escape-control-characters t)
  228. (print-escape-nonascii t)
  229. (print-continuous-numbering t)
  230. print-number-table
  231. (start-time (float-time)))
  232. (unless (file-exists-p (file-name-directory file))
  233. (make-directory (file-name-directory file) t))
  234. (with-temp-file file
  235. (if pp
  236. (pp data (current-buffer))
  237. (prin1 data (current-buffer))))
  238. (org-persist--display-time
  239. (- (float-time) start-time)
  240. "Writing to %S" file)))
  241. ;;;; Working with index
  242. (defmacro org-persist-collection-let (collection &rest body)
  243. "Bind container and associated from COLLECTION and execute BODY."
  244. (declare (debug (form body)) (indent 1))
  245. `(let* ((container (plist-get ,collection :container))
  246. (associated (plist-get ,collection :associated))
  247. (path (plist-get associated :file))
  248. (inode (plist-get associated :inode))
  249. (hash (plist-get associated :hash))
  250. (key (plist-get associated :key)))
  251. ,@body))
  252. (defun org-persist--find-index (collection)
  253. "Find COLLECTION in `org-persist--index'."
  254. (org-persist-collection-let collection
  255. (and org-persist--index-hash
  256. (catch :found
  257. (dolist (cont (cons container container))
  258. (let (r)
  259. (setq r (or (gethash (cons cont associated) org-persist--index-hash)
  260. (and path (gethash (cons cont (list :file path)) org-persist--index-hash))
  261. (and inode (gethash (cons cont (list :inode inode)) org-persist--index-hash))
  262. (and hash (gethash (cons cont (list :hash hash)) org-persist--index-hash))
  263. (and key (gethash (cons cont (list :key key)) org-persist--index-hash))))
  264. (when r (throw :found r))))))))
  265. (defun org-persist--add-to-index (collection &optional hash-only)
  266. "Add or update COLLECTION in `org-persist--index'.
  267. When optional HASH-ONLY is non-nil, only modify the hash table.
  268. Return PLIST."
  269. (org-persist-collection-let collection
  270. (let ((existing (org-persist--find-index collection)))
  271. (if existing
  272. (progn
  273. (plist-put existing :container container)
  274. (plist-put (plist-get existing :associated) :file path)
  275. (plist-put (plist-get existing :associated) :inode inode)
  276. (plist-put (plist-get existing :associated) :hash hash)
  277. (plist-put (plist-get existing :associated) :key key)
  278. existing)
  279. (unless hash-only (push collection org-persist--index))
  280. (unless org-persist--index-hash (setq org-persist--index-hash (make-hash-table :test 'equal)))
  281. (dolist (cont (cons container container))
  282. (puthash (cons cont associated) collection org-persist--index-hash)
  283. (when path (puthash (cons cont (list :file path)) collection org-persist--index-hash))
  284. (when inode (puthash (cons cont (list :inode inode)) collection org-persist--index-hash))
  285. (when hash (puthash (cons cont (list :hash inode)) collection org-persist--index-hash))
  286. (when key (puthash (cons cont (list :key inode)) collection org-persist--index-hash)))
  287. collection))))
  288. (defun org-persist--remove-from-index (collection)
  289. "Remove COLLECTION from `org-persist--index'."
  290. (let ((existing (org-persist--find-index collection)))
  291. (when existing
  292. (org-persist-collection-let collection
  293. (dolist (cont (cons container container))
  294. (org-persist-gc:generic cont collection)
  295. (remhash (cons cont associated) org-persist--index-hash)
  296. (when path (remhash (cons cont (list :file path)) org-persist--index-hash))
  297. (when inode (remhash (cons cont (list :inode inode)) org-persist--index-hash))
  298. (when hash (remhash (cons cont (list :hash hash)) org-persist--index-hash))
  299. (when key (remhash (cons cont (list :key key)) org-persist--index-hash))))
  300. (setq org-persist--index (delq existing org-persist--index)))))
  301. (defun org-persist--get-collection (container &optional associated &rest misc)
  302. "Return or create collection used to store CONTAINER for ASSOCIATED.
  303. When ASSOCIATED is nil, it is a global CONTAINER.
  304. ASSOCIATED can also be a (:buffer buffer) or buffer, (:file file-path)
  305. or file-path, (:inode inode), (:hash hash), or or (:key key)."
  306. (unless (and (listp container) (listp (car container)))
  307. (setq container (list container)))
  308. (setq associated (org-persist--normalize-associated associated))
  309. (unless (equal misc '(nil))
  310. (setq associated (append associated misc)))
  311. (or (org-persist--find-index
  312. `( :container ,(org-persist--normalize-container container)
  313. :associated ,associated))
  314. (org-persist--add-to-index
  315. (list :container (org-persist--normalize-container container)
  316. :persist-file
  317. (replace-regexp-in-string "^.." "\\&/" (org-id-uuid))
  318. :associated associated))))
  319. ;;;; Reading container data.
  320. (defun org-persist--normalize-container (container)
  321. "Normalize CONTAINER representation into (type . settings)."
  322. (if (and (listp container) (listp (car container)))
  323. (mapcar #'org-persist--normalize-container container)
  324. (pcase container
  325. ((pred symbolp)
  326. (list "elisp" container))
  327. ((pred stringp)
  328. (list container nil))
  329. (`(,(or "elisp" "version" "file" "index" "url") . ,_)
  330. container)
  331. (_ (error "org-persist: Unknown container type: %S" container)))))
  332. (defvar org-persist--associated-buffer-cache (make-hash-table :weakness 'key)
  333. "Buffer hash cache.")
  334. (defun org-persist--normalize-associated (associated)
  335. "Normalize ASSOCIATED representation into (:type value)."
  336. (pcase associated
  337. ((or (pred stringp) `(:file ,associated2))
  338. (when associated2 (setq associated associated2))
  339. (let* ((rtn `(:file ,associated))
  340. (inode (and (fboundp 'file-attribute-inode-number)
  341. (file-attribute-inode-number
  342. (file-attributes associated)))))
  343. (when inode (plist-put rtn :inode inode))
  344. rtn))
  345. ((or (pred bufferp) `(:buffer ,associated2))
  346. (when associated2 (setq associated associated2))
  347. (let ((cached (gethash associated org-persist--associated-buffer-cache))
  348. file inode hash)
  349. (if (and cached (eq (buffer-modified-tick associated)
  350. (car cached)))
  351. (progn
  352. (setq file (nth 1 cached)
  353. inode (nth 2 cached)
  354. hash (nth 3 cached)))
  355. (setq file (buffer-file-name
  356. (or (buffer-base-buffer associated)
  357. associated)))
  358. (setq inode (when (and file
  359. (fboundp 'file-attribute-inode-number))
  360. (file-attribute-inode-number
  361. (file-attributes file))))
  362. (setq hash (secure-hash 'md5 associated))
  363. (puthash associated
  364. (list (buffer-modified-tick associated)
  365. file inode hash)
  366. org-persist--associated-buffer-cache))
  367. (let ((rtn `(:hash ,hash)))
  368. (when file (setq rtn (plist-put rtn :file file)))
  369. (when inode (setq rtn (plist-put rtn :inode inode)))
  370. rtn)))
  371. ((pred listp)
  372. associated)
  373. (_ (error "Unknown associated object %S" associated))))
  374. (defmacro org-persist-read:generic (container reference-data collection)
  375. "Read and return the data stored in CONTAINER.
  376. REFERENCE-DATA is associated with CONTAINER in the persist file.
  377. COLLECTION is the plist holding data collectin."
  378. `(let* ((c (org-persist--normalize-container ,container))
  379. (read-func-symbol (intern (format "org-persist-read:%s" (car c)))))
  380. (setf ,collection (plist-put ,collection :last-access (float-time)))
  381. (unless (fboundp read-func-symbol)
  382. (error "org-persist: Read function %s not defined"
  383. read-func-symbol))
  384. (funcall read-func-symbol c ,reference-data ,collection)))
  385. (defun org-persist-read:elisp (_ lisp-value _)
  386. "Read elisp container and return the stored data."
  387. lisp-value)
  388. (defun org-persist-read:version (container _ _)
  389. "Read version container."
  390. (cadr container))
  391. (defun org-persist-read:file (_ path _)
  392. "Read file container."
  393. (when (and path (file-exists-p (concat org-persist-directory path)))
  394. (concat org-persist-directory path)))
  395. (defun org-persist-read:url (_ path _)
  396. "Read file container."
  397. (when (and path (file-exists-p (concat org-persist-directory path)))
  398. (concat org-persist-directory path)))
  399. (defun org-persist-read:index (cont index-file _)
  400. "Read index container."
  401. (when (file-exists-p index-file)
  402. (let ((index (org-persist--read-elisp-file index-file)))
  403. (when index
  404. (catch :found
  405. (dolist (collection index)
  406. (org-persist-collection-let collection
  407. (when (and (not associated)
  408. (pcase container
  409. (`(("index" ,version))
  410. (equal version (cadr cont)))
  411. (_ nil)))
  412. (throw :found index)))))))))
  413. ;;;; Applying container data for side effects.
  414. (defmacro org-persist-load:generic (container reference-data collection)
  415. "Load the data stored in CONTAINER for side effects.
  416. REFERENCE-DATA is associated with CONTAINER in the persist file.
  417. COLLECTION is the plist holding data collectin."
  418. `(let* ((container (org-persist--normalize-container ,container))
  419. (load-func-symbol (intern (format "org-persist-load:%s" (car container)))))
  420. (setf ,collection (plist-put ,collection :last-access (float-time)))
  421. (unless (fboundp load-func-symbol)
  422. (error "org-persist: Load function %s not defined"
  423. load-func-symbol))
  424. (funcall load-func-symbol container ,reference-data ,collection)))
  425. (defun org-persist-load:elisp (container lisp-value associated)
  426. "Load elisp variable container and assign the data to variable symbol."
  427. (let ((lisp-symbol (cadr container))
  428. (buffer (when (plist-get associated :file)
  429. (get-file-buffer (plist-get associated :file)))))
  430. (if buffer
  431. (with-current-buffer buffer
  432. (make-variable-buffer-local lisp-symbol)
  433. (set lisp-symbol lisp-value))
  434. (set lisp-symbol lisp-value))))
  435. (defalias 'org-persist-load:version #'org-persist-read:version)
  436. (defalias 'org-persist-load:file #'org-persist-read:file)
  437. (defun org-persist-load:index (container index-file _)
  438. "Load `org-persist--index'."
  439. (unless org-persist--index
  440. (setq org-persist--index (org-persist-read:index container index-file nil))
  441. (setq org-persist--index-hash nil)
  442. (if org-persist--index
  443. (mapc (lambda (collection) (org-persist--add-to-index collection 'hash)) org-persist--index)
  444. (setq org-persist--index nil)
  445. (when (file-exists-p org-persist-directory)
  446. (dolist (file (directory-files org-persist-directory 'absolute "^[^.][^.]"))
  447. (if (file-directory-p file)
  448. (delete-directory file t)
  449. (delete-file file))))
  450. (plist-put (org-persist--get-collection container) :expiry 'never))))
  451. (defun org-persist--load-index ()
  452. "Load `org-persist--index."
  453. (org-persist-load:index
  454. `("index" ,org-persist--storage-version)
  455. (org-file-name-concat org-persist-directory org-persist-index-file)
  456. nil))
  457. ;;;; Writing container data
  458. (defmacro org-persist-write:generic (container collection)
  459. "Write CONTAINER in COLLECTION."
  460. `(let* ((c (org-persist--normalize-container ,container))
  461. (write-func-symbol (intern (format "org-persist-write:%s" (car c)))))
  462. (unless (fboundp write-func-symbol)
  463. (error "org-persist: Write function %s not defined"
  464. write-func-symbol))
  465. (funcall write-func-symbol c ,collection)))
  466. (defun org-persist-write:elisp (container collection)
  467. "Write elisp CONTAINER."
  468. (if (and (plist-get (plist-get collection :associated) :file)
  469. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  470. (buffer-local-value
  471. (cadr container)
  472. (get-file-buffer (plist-get (plist-get collection :associated) :file)))
  473. (symbol-value (cadr container))))
  474. (defalias 'org-persist-write:version #'ignore)
  475. (defun org-persist-write:file (container collection)
  476. "Write file container."
  477. (org-persist-collection-let collection
  478. (when (and path (file-exists-p path))
  479. (let* ((persist-file (plist-get collection :persist-file))
  480. (ext (file-name-extension path))
  481. (file-copy (org-file-name-concat
  482. org-persist-directory
  483. (format "%s-file.%s" persist-file ext))))
  484. (unless (file-exists-p (file-name-directory file-copy))
  485. (make-directory (file-name-directory file-copy) t))
  486. (unless (file-exists-p file-copy)
  487. (copy-file path file-copy 'overwrite))
  488. (format "%s-file.%s" persist-file ext)))))
  489. (defun org-persist-write:url (container collection)
  490. "Write url container."
  491. (org-persist-collection-let collection
  492. (when path
  493. (let* ((persist-file (plist-get collection :persist-file))
  494. (ext (file-name-extension path))
  495. (file-copy (org-file-name-concat
  496. org-persist-directory
  497. (format "%s-file.%s" persist-file ext))))
  498. (unless (file-exists-p (file-name-directory file-copy))
  499. (make-directory (file-name-directory file-copy) t))
  500. (unless (file-exists-p file-copy)
  501. (url-copy-file path file-copy 'overwrite))
  502. (format "%s-file.%s" persist-file ext)))))
  503. (defun org-persist-write:index (container _)
  504. "Write index container."
  505. (org-persist--get-collection container)
  506. (unless (file-exists-p org-persist-directory)
  507. (make-directory org-persist-directory))
  508. (unless (file-exists-p org-persist-directory)
  509. (warn "Failed to create org-persist storage in %s."
  510. org-persist-directory)
  511. (let ((dir (directory-file-name
  512. (file-name-as-directory org-persist-directory))))
  513. (while (and (not (file-exists-p dir))
  514. (not (equal dir (setq dir (directory-file-name
  515. (file-name-directory dir)))))))
  516. (unless (file-writable-p dir)
  517. (message "Missing write access rights to org-persist-directory: %S"
  518. org-persist-directory))))
  519. (when (file-exists-p org-persist-directory)
  520. (org-persist--write-elisp-file
  521. (org-file-name-concat org-persist-directory org-persist-index-file)
  522. org-persist--index
  523. t t)
  524. t))
  525. (defun org-persist--save-index ()
  526. "Save `org-persist--index."
  527. (org-persist-write:index
  528. `("index" ,org-persist--storage-version) nil))
  529. ;;;; Public API
  530. (cl-defun org-persist-register (container &optional associated &rest misc &key inherit &key (expiry org-persist-default-expiry) &allow-other-keys)
  531. "Register CONTAINER in ASSOCIATED to be persistent across Emacs sessions.
  532. Optional key INHERIT makes CONTAINER dependent on another container.
  533. Such dependency means that data shared between variables will be
  534. preserved (see elisp#Circular Objects).
  535. Optional key EXPIRY will set the expiry condition of the container.
  536. It can be `never', `nil' - until end of session, a number of days since
  537. last access, or a function accepting a single argument - collection.
  538. EXPIRY key has no effect when INHERIT is non-nil."
  539. (unless org-persist--index (org-persist--load-index))
  540. (setq container (org-persist--normalize-container container))
  541. (when inherit
  542. (setq inherit (org-persist--normalize-container inherit))
  543. (let ((inherited-collection (org-persist--get-collection inherit associated))
  544. new-collection)
  545. (unless (member container (plist-get inherited-collection :container))
  546. (setq new-collection
  547. (plist-put (copy-sequence inherited-collection) :container
  548. (cons container (plist-get inherited-collection :container))))
  549. (org-persist--remove-from-index inherited-collection)
  550. (org-persist--add-to-index new-collection))))
  551. (let ((collection (org-persist--get-collection container associated misc)))
  552. (when (and expiry (not inherit))
  553. (when expiry (plist-put collection :expiry expiry))))
  554. (when (or (bufferp associated) (bufferp (plist-get associated :buffer)))
  555. (with-current-buffer (if (bufferp associated)
  556. associated
  557. (plist-get associated :buffer))
  558. (add-hook 'kill-buffer-hook #'org-persist-write-all-buffer nil 'local))))
  559. (defun org-persist-unregister (container &optional associated)
  560. "Unregister CONTAINER in ASSOCIATED to be persistent.
  561. When ASSOCIATED is `all', unregister CONTAINER everywhere."
  562. (unless org-persist--index (org-persist--load-index))
  563. (if (eq associated 'all)
  564. (mapc (lambda (collection)
  565. (when (member container (plist-get collection :container))
  566. (org-persist-unregister container (plist-get collection :associated))))
  567. org-persist--index)
  568. (let ((collection (org-persist--get-collection container associated)))
  569. (if (= (length (plist-get collection :container)) 1)
  570. (org-persist--remove-from-index collection)
  571. (plist-put collection :container
  572. (remove container (plist-get collection :container)))
  573. (org-persist--add-to-index collection)))))
  574. (defun org-persist-read (container &optional associated hash-must-match load?)
  575. "Restore CONTAINER data for ASSOCIATED.
  576. When HASH-MUST-MATCH is non-nil, do not restore data if hash for
  577. ASSOCIATED file or buffer does not match.
  578. ASSOCIATED can be a plist, a buffer, or a string.
  579. A buffer is treated as (:buffer ASSOCIATED).
  580. A string is treated as (:file ASSOCIATED)."
  581. (setq associated (org-persist--normalize-associated associated))
  582. (setq container (org-persist--normalize-container container))
  583. (let* ((collection (org-persist--get-collection container associated))
  584. (persist-file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
  585. (data nil))
  586. (when (and collection
  587. (file-exists-p persist-file)
  588. (or (not hash-must-match)
  589. (and (plist-get associated :hash)
  590. (equal (plist-get associated :hash)
  591. (plist-get (plist-get collection :associated) :hash)))))
  592. (unless (seq-find (lambda (v)
  593. (run-hook-with-args-until-success 'org-persist-before-read-hook v associated))
  594. (plist-get collection :container))
  595. (setq data (org-persist--read-elisp-file persist-file))
  596. (cl-loop for container in (plist-get collection :container)
  597. with result = nil
  598. do
  599. (if load?
  600. (push (org-persist-load:generic container (alist-get container data nil nil #'equal) collection) result)
  601. (push (org-persist-read:generic container (alist-get container data nil nil #'equal) collection) result))
  602. (run-hook-with-args 'org-persist-after-read-hook container associated)
  603. finally return (if (= 1 (length result)) (car result) result))))))
  604. (defun org-persist-load (container &optional associated hash-must-match)
  605. "Load CONTAINER data for ASSOCIATED.
  606. The arguments have the same meaning as in `org-persist-read'."
  607. (org-persist-read container associated hash-must-match t))
  608. (defun org-persist-load-all (&optional associated)
  609. "Restore all the persistent data associated with ASSOCIATED."
  610. (unless org-persist--index (org-persist--load-index))
  611. (setq associated (org-persist--normalize-associated associated))
  612. (let (all-containers)
  613. (dolist (collection org-persist--index)
  614. (when collection
  615. (cl-pushnew (plist-get collection :container) all-containers :test #'equal)))
  616. (dolist (container all-containers)
  617. (org-persist-load container associated t))))
  618. (defun org-persist-load-all-buffer ()
  619. "Call `org-persist-load-all' in current buffer."
  620. (org-persist-load-all (current-buffer)))
  621. (defun org-persist-write (container &optional associated)
  622. "Save CONTAINER according to ASSOCIATED.
  623. ASSOCIATED can be a plist, a buffer, or a string.
  624. A buffer is treated as (:buffer ASSOCIATED).
  625. A string is treated as (:file ASSOCIATED)."
  626. (setq associated (org-persist--normalize-associated associated))
  627. (let ((collection (org-persist--get-collection container associated)))
  628. (setf collection (plist-put collection :associated associated))
  629. (unless (seq-find (lambda (v)
  630. (run-hook-with-args-until-success 'org-persist-before-write-hook v associated))
  631. (plist-get collection :container))
  632. (when (or (file-exists-p org-persist-directory) (org-persist--save-index))
  633. (let ((file (org-file-name-concat org-persist-directory (plist-get collection :persist-file)))
  634. (data (mapcar (lambda (c) (cons c (org-persist-write:generic c collection)))
  635. (plist-get collection :container))))
  636. (org-persist--write-elisp-file file data))))))
  637. (defun org-persist-write-all (&optional associated)
  638. "Save all the persistent data."
  639. (unless org-persist--index (org-persist--load-index))
  640. (setq associated (org-persist--normalize-associated associated))
  641. (let (all-containers)
  642. (dolist (collection org-persist--index)
  643. (if associated
  644. (when collection
  645. (cl-pushnew (plist-get collection :container) all-containers :test #'equal))
  646. (org-persist-write (plist-get collection :container) (plist-get collection :associated))))
  647. (dolist (container all-containers)
  648. (when (org-persist--find-index `(:container ,container :associated ,associated))
  649. (org-persist-write container associated)))))
  650. (defun org-persist-write-all-buffer ()
  651. "Call `org-persist-write-all' in current buffer.
  652. Do nothing in an indirect buffer."
  653. (unless (buffer-base-buffer (current-buffer))
  654. (org-persist-write-all (current-buffer))))
  655. (defmacro org-persist-gc:generic (container collection)
  656. "Garbage collect CONTAINER data from COLLECTION."
  657. `(let* ((c (org-persist--normalize-container ,container))
  658. (gc-func-symbol (intern (format "org-persist-gc:%s" (car c)))))
  659. (unless (fboundp gc-func-symbol)
  660. (error "org-persist: GC function %s not defined"
  661. gc-func-symbol))
  662. (funcall gc-func-symbol c ,collection)))
  663. (defalias 'org-persist-gc:elisp #'ignore)
  664. (defalias 'org-persist-gc:index #'ignore)
  665. (defun org-persist-gc:file (container collection)
  666. "Garbage collect file container."
  667. (let ((file (org-persist-read container (plist-get collection :associated))))
  668. (when (file-exists-p file)
  669. (delete-file file))))
  670. (defun org-persist-gc:url (container collection)
  671. "Garbage collect url container."
  672. (let ((file (org-persist-read container (plist-get collection :associated))))
  673. (when (file-exists-p file)
  674. (delete-file file))))
  675. (defmacro org-persist--gc-persist-file (persist-file)
  676. "Garbage collect PERSIST-FILE."
  677. `(when (file-exists-p ,persist-file)
  678. (delete-file ,persist-file)
  679. (when (org-directory-empty-p (file-name-directory ,persist-file))
  680. (delete-directory (file-name-directory ,persist-file)))))
  681. (defmacro org-persist--gc-expired-p (cnd collection)
  682. "Check if expiry condition CND triggers."
  683. `(pcase ,cnd
  684. (`nil t)
  685. (`never nil)
  686. ((pred numberp)
  687. (when (plist-get ,collection :access-time)
  688. (<= (float-time) (+ (plist-get ,collection :access-time) (* ,cnd 24 60 60)))))
  689. ((pred functionp)
  690. (funcall ,cnd ,collection))
  691. (_ (error "org-persist: Unsupported expiry type %S" ,cnd))))
  692. (defun org-persist-gc ()
  693. "Remove expired or unregisted containers.
  694. Also, remove containers associated with non-existing files."
  695. (let (new-index (remote-files-num 0))
  696. (dolist (collection org-persist--index)
  697. (let* ((file (plist-get (plist-get collection :associated) :file))
  698. (file-remote (when file (file-remote-p file)))
  699. (persist-file (when (plist-get collection :persist-file)
  700. (org-file-name-concat
  701. org-persist-directory
  702. (plist-get collection :persist-file))))
  703. (expired? (org-persist--gc-expired-p
  704. (plist-get collection :expiry) collection)))
  705. (when persist-file
  706. (when file
  707. (when file-remote (cl-incf remote-files-num))
  708. (unless (if (not file-remote)
  709. (file-exists-p file)
  710. (pcase org-persist-remote-files
  711. ('t t)
  712. ('check-existence
  713. (file-exists-p file))
  714. ((pred #'numberp)
  715. (<= org-persist-remote-files remote-files-num))
  716. (_ nil)))
  717. (setq expired? t)))
  718. (if expired?
  719. (org-persist--gc-persist-file persist-file)
  720. (push collection new-index)))))
  721. (setq org-persist--index (nreverse new-index))))
  722. ;; Automatically write the data, but only when we have write access.
  723. (let ((dir (directory-file-name
  724. (file-name-as-directory org-persist-directory))))
  725. (while (and (not (file-exists-p dir))
  726. (not (equal dir (setq dir (directory-file-name
  727. (file-name-directory dir)))))))
  728. (if (not (file-writable-p dir))
  729. (message "Missing write access rights to org-persist-directory: %S"
  730. org-persist-directory)
  731. (add-hook 'kill-emacs-hook #'org-persist-write-all)
  732. ;; `org-persist-gc' should run before `org-persist-write-all'. So we are adding the
  733. ;; hook after `org-persist-write-all'.
  734. (add-hook 'kill-emacs-hook #'org-persist-gc)))
  735. (add-hook 'after-init-hook #'org-persist-load-all)
  736. (provide 'org-persist)
  737. ;;; org-persist.el ends here