summaryrefslogtreecommitdiff
path: root/config/essentials/vis/backup.lua
diff options
context:
space:
mode:
authorRaymaekers Luca <raymaekers.luca@gmail.com>2024-06-22 02:05:44 +0200
committerRaymaekers Luca <raymaekers.luca@gmail.com>2024-06-22 02:05:44 +0200
commit36d2972c60ec86b873fa496d1f5ea95cf748cf49 (patch)
treea6d6750fa17c2964cd241afa8e963cac6106b390 /config/essentials/vis/backup.lua
parent4914b43f642e2772a140a8f9b1f26b4e555ed88b (diff)
parent32256e087aaf7744348a5ba33e802d5c8d9d97dd (diff)
Merge branch 'main' of db:dotfiles
Diffstat (limited to 'config/essentials/vis/backup.lua')
-rw-r--r--config/essentials/vis/backup.lua47
1 files changed, 47 insertions, 0 deletions
diff --git a/config/essentials/vis/backup.lua b/config/essentials/vis/backup.lua
new file mode 100644
index 0000000..f48895f
--- /dev/null
+++ b/config/essentials/vis/backup.lua
@@ -0,0 +1,47 @@
+local backup = {}
+
+-- Return the backup path concatenated with the filename, replace / with %
+backup.entire_path_with_double_percentage_signs =
+ function(backup_dir, path)
+ return backup_dir .. "/" .. string.gsub(path, "/", "%%")
+ end
+
+-- Return the backup path concatenated with the filename, replace / with %
+-- and append the current time using time_format
+backup.entire_path_with_double_percentage_signs_and_timestamp = function(
+ backup_dir, path)
+ return backup_dir .. "/" .. os.date(backup.time_format) ..
+ string.gsub(path, "/", "%%")
+end
+
+-- Before saving the file, copy the current contents of the file to a backup file
+vis.events.subscribe(vis.events.FILE_SAVE_PRE, function(file, path)
+ if file.size > backup.byte_limit then return end
+
+ -- E.g. when editing stdin as an interactive filter
+ -- `vis -`
+ if path == nil then return end
+
+ local backup_path = backup.get_fname(backup.directory, path)
+
+ local backup_file = io.open(backup_path, "w")
+ local current_file = io.open(path)
+ if backup_file == nil or current_file == nil then return end
+
+ for line in current_file:lines() do backup_file:write(line .. "\n") end
+
+ backup_file:close()
+end)
+
+-- Set defaults
+backup.directory = os.getenv("XDG_DATA_HOME") .. "/Trash/vis-backups"
+
+backup.get_fname = backup.entire_path_with_double_percentage_signs
+
+backup.time_format = "%H-%M-"
+
+-- Do not make backups if the file is greater than this
+-- 1MB by default
+backup.byte_limit = 1000000
+
+return backup