1local function current_script_dir()
2 local source = debug.getinfo(1, "S").source
3 local script_path = source:match("^@(.+)$")
4 return script_path:match("^(.*)[/\\].-$")
5end
6
7local function list_action_scripts(path)
8 local files = {}
9 local index = 0
10
11 while true do
12 local file_name = reaper.EnumerateFiles(path, index)
13 if file_name == nil then
14 break
15 end
16
17 if file_name:match("%.lua$") then
18 files[#files + 1] = file_name
19 end
20
21 index = index + 1
22 end
23
24 table.sort(files)
25 return files
26end
27
28local function add_script(path, commit)
29 local command_id = reaper.AddRemoveReaScript(true, 0, path, commit)
30 if command_id == 0 then
31 error("failed to register " .. path)
32 end
33
34 local named = reaper.ReverseNamedCommandLookup(command_id)
35 if named ~= nil and named ~= "" then
36 return "_" .. named
37 end
38
39 return tostring(command_id)
40end
41
42local function remove_script(path, commit)
43 reaper.AddRemoveReaScript(false, 0, path, commit)
44end
45
46local function ext_state_key_for_file(file_name)
47 local stem = file_name:match("^(.*)%.lua$")
48 if stem == nil or stem == "" then
49 error("invalid action file name: " .. file_name)
50 end
51
52 return stem .. "_command_id"
53end
54
55local script_dir = current_script_dir()
56local actions_dir = script_dir .. "/scripts"
57local files = list_action_scripts(actions_dir)
58
59if #files == 0 then
60 error("no action scripts found in " .. actions_dir)
61end
62
63for _, file_name in ipairs(files) do
64 remove_script(actions_dir .. "/" .. file_name, false)
65end
66
67for index, file_name in ipairs(files) do
68 local command_id = add_script(actions_dir .. "/" .. file_name, index == #files)
69 reaper.SetExtState("meow", ext_state_key_for_file(file_name), command_id, true)
70end