irongit

Configure synchronization of files and directories through a plugin.

67 lines2.0 KBLua
1local log = require("syncmap.log")
2local simple_cmd = require("syncmap.simple_cmd")
3local M = {
4 opts = require("syncmap.default"),
5}
6
7---Runs rsync
8---@param args RsyncParams
9function M.run(args)
10 local cmd = { "rsync", unpack(args.flags), args.src, args.dst }
11 local result = vim.fn.system(cmd)
12 if vim.v.shell_error ~= 0 then
13 log.error(
14 string.format(
15 "Failed to run the the following rsync command.\n%s\nResult: %s",
16 table.concat(cmd, " "),
17 result
18 )
19 )
20 else
21 log.debug("Successfully ran the following rsync command.\n" .. table.concat(cmd, " "))
22 end
23 return result
24end
25
26---@param args RsyncParams
27function M.spawn_watcher(args)
28 if M.opts.reverse_sync_on_startup then
29 M.run({
30 src = args.dst,
31 dst = args.src,
32 reverse_sync_on_spawn = args.reverse_sync_on_spawn,
33 flags = args.flags,
34 })
35 end
36
37 local cmd = "while inotifywait "
38 local stat = vim.uv.fs_stat(args.src)
39 if stat and stat.type == "directory" then
40 log.debug(string.format("Setting up inotify for a file.\n%s", args.src))
41 cmd = cmd .. string.format("-r -e modify,create,delete %q; ", args.src)
42 elseif stat and stat.type == "file" then
43 log.debug(string.format("Setting up inotify for a file.\n%s", args.src))
44 cmd = cmd .. string.format("-e modify %q; ", args.src)
45 else
46 log.error(string.format("Could not stat %s", args.src))
47 return "NO STAT"
48 end
49 cmd = cmd .. string.format("do rsync %s %q %q; done", table.concat(args.flags, " "), args.src, args.dst)
50 local cmd_str_for_log = "sh -c '" .. cmd .. "'"
51
52 local handle, pid = simple_cmd.spawn("sh", {
53 args = { "-c", cmd },
54 path = "sh",
55 callback = function(code, status, _, pid)
56 log.debug(string.format("%s\n%d completed with %d code and %d status", cmd_str_for_log, pid, code, status))
57 end,
58 })
59 if not handle then
60 log.error(string.format("Failed to start the following command.\n%s\nErr: %s", cmd_str_for_log, pid))
61 else
62 log.debug(string.format("Started the following command with pid %d\n%s", pid, cmd_str_for_log))
63 end
64 return pid, cmd_str_for_log
65end
66
67return M