Immediately execute ModuleLoaded hooks for already loaded modules

This is trickier than expected because ModuleLoaded hooks can (as
any other hooks) use arbitrary regular expressions for their filter.

Fixes #4841
This commit is contained in:
Maxime Coste 2023-02-14 21:31:29 +11:00
parent 85ceef29bd
commit 458e3ef20a
9 changed files with 80 additions and 32 deletions

View File

@ -90,6 +90,13 @@ void CommandManager::load_module(StringView module_name, Context& context)
context.hooks().run_hook(Hook::ModuleLoaded, module_name, context); context.hooks().run_hook(Hook::ModuleLoaded, module_name, context);
} }
HashSet<String> CommandManager::loaded_modules() const
{
return m_modules | filter([](auto&& elem) { return elem.value.state == Module::State::Loaded; })
| transform([](auto&& elem) { return elem.key; })
| gather<HashSet>();
}
struct parse_error : runtime_error struct parse_error : runtime_error
{ {
parse_error(StringView error) parse_error(StringView error)

View File

@ -123,6 +123,7 @@ public:
void register_module(String module_name, String commands); void register_module(String module_name, String commands);
void load_module(StringView module_name, Context& context); void load_module(StringView module_name, Context& context);
HashSet<String> loaded_modules() const;
Completions complete_module_name(StringView query) const; Completions complete_module_name(StringView query) const;

View File

@ -1127,7 +1127,7 @@ const CommandDesc add_hook_cmd = {
const auto flags = (parser.get_switch("always") ? HookFlags::Always : HookFlags::None) | const auto flags = (parser.get_switch("always") ? HookFlags::Always : HookFlags::None) |
(parser.get_switch("once") ? HookFlags::Once : HookFlags::None); (parser.get_switch("once") ? HookFlags::Once : HookFlags::None);
get_scope(parser[0], context).hooks().add_hook(it->value, group.str(), flags, get_scope(parser[0], context).hooks().add_hook(it->value, group.str(), flags,
std::move(regex), command); std::move(regex), command, context);
} }
}; };

View File

@ -20,16 +20,62 @@ struct HookManager::HookData
HookFlags flags; HookFlags flags;
Regex filter; Regex filter;
String commands; String commands;
bool should_run(bool only_always, const Regex& disabled_hooks, StringView param,
MatchResults<const char*>& captures) const
{
return (not only_always or (flags & HookFlags::Always)) and
(group.empty() or disabled_hooks.empty() or
not regex_match(group.begin(), group.end(), disabled_hooks))
and regex_match(param.begin(), param.end(), captures, filter);
}
void exec(Hook hook, StringView param, Context& context, const MatchResults<const char*>& captures)
{
if (context.options()["debug"].get<DebugFlags>() & DebugFlags::Hooks)
write_to_debug_buffer(format("hook {}({})/{}",
enum_desc(Meta::Type<Hook>{})[to_underlying(hook)].name,
param, group));
ScopedSetBool disable_history{context.history_disabled()};
EnvVarMap env_vars{ {"hook_param", param.str()} };
for (size_t i = 0; i < captures.size(); ++i)
env_vars.insert({format("hook_param_capture_{}", i),
{captures[i].first, captures[i].second}});
for (auto& c : filter.impl()->named_captures)
env_vars.insert({format("hook_param_capture_{}", c.name),
{captures[c.index].first, captures[c.index].second}});
CommandManager::instance().execute(commands, context, {{}, std::move(env_vars)});
}
}; };
HookManager::HookManager() : m_parent(nullptr) {} HookManager::HookManager() : m_parent(nullptr) {}
HookManager::HookManager(HookManager& parent) : SafeCountable{}, m_parent(&parent) {} HookManager::HookManager(HookManager& parent) : SafeCountable{}, m_parent(&parent) {}
HookManager::~HookManager() = default; HookManager::~HookManager() = default;
void HookManager::add_hook(Hook hook, String group, HookFlags flags, Regex filter, String commands) void HookManager::add_hook(Hook hook, String group, HookFlags flags, Regex filter, String commands, Context& context)
{ {
auto& hooks = m_hooks[to_underlying(hook)]; std::unique_ptr<HookData> hook_data{new HookData{std::move(group), flags, std::move(filter), std::move(commands)}};
hooks.emplace_back(new HookData{std::move(group), flags, std::move(filter), std::move(commands)}); if (hook == Hook::ModuleLoaded)
{
const bool only_always = context.hooks_disabled();
auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
for (auto&& name : CommandManager::instance().loaded_modules())
{
MatchResults<const char*> captures;
if (hook_data->should_run(only_always, disabled_hooks, name, captures))
{
hook_data->exec(hook, name, context, captures);
if (hook_data->flags & HookFlags::Once)
return;
}
}
}
m_hooks[to_underlying(hook)].push_back(std::move(hook_data));
} }
void HookManager::remove_hooks(const Regex& regex) void HookManager::remove_hooks(const Regex& regex)
@ -62,21 +108,16 @@ CandidateList HookManager::complete_hook_group(StringView prefix, ByteCount pos_
void HookManager::run_hook(Hook hook, StringView param, Context& context) void HookManager::run_hook(Hook hook, StringView param, Context& context)
{ {
auto& hook_list = m_hooks[to_underlying(hook)];
const bool only_always = context.hooks_disabled(); const bool only_always = context.hooks_disabled();
auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>(); auto& disabled_hooks = context.options()["disabled_hooks"].get<Regex>();
struct ToRun { HookData* hook; MatchResults<const char*> captures; }; struct ToRun { HookData* hook; MatchResults<const char*> captures; };
Vector<ToRun> hooks_to_run; // The m_hooks_trash vector ensure hooks wont die during this method Vector<ToRun> hooks_to_run; // The m_hooks_trash vector ensure hooks wont die during this method
for (auto& hook : hook_list) for (auto& hook : m_hooks[to_underlying(hook)])
{ {
MatchResults<const char*> captures; MatchResults<const char*> captures;
if ((not only_always or (hook->flags & HookFlags::Always)) and if (hook->should_run(only_always, disabled_hooks, param, captures))
(hook->group.empty() or disabled_hooks.empty() or hooks_to_run.push_back({hook.get(), std::move(captures)});
not regex_match(hook->group.begin(), hook->group.end(), disabled_hooks))
and regex_match(param.begin(), param.end(), captures, hook->filter))
hooks_to_run.push_back({ hook.get(), std::move(captures) });
} }
if (m_parent) if (m_parent)
@ -106,26 +147,12 @@ void HookManager::run_hook(Hook hook, StringView param, Context& context)
{ {
try try
{ {
if (debug_flags & DebugFlags::Hooks) to_run.hook->exec(hook, param, context, to_run.captures);
write_to_debug_buffer(format("hook {}({})/{}", hook_name, param, to_run.hook->group));
ScopedSetBool disable_history{context.history_disabled()};
EnvVarMap env_vars{ {"hook_param", param.str()} };
for (size_t i = 0; i < to_run.captures.size(); ++i)
env_vars.insert({format("hook_param_capture_{}", i),
{to_run.captures[i].first, to_run.captures[i].second}});
for (auto& c : to_run.hook->filter.impl()->named_captures)
env_vars.insert({format("hook_param_capture_{}", c.name),
{to_run.captures[c.index].first, to_run.captures[c.index].second}});
CommandManager::instance().execute(to_run.hook->commands, context,
{ {}, std::move(env_vars) });
if (to_run.hook->flags & HookFlags::Once) if (to_run.hook->flags & HookFlags::Once)
{ {
auto it = find(hook_list, to_run.hook); auto& hook_list = m_hooks[to_underlying(hook)];
if (it != hook_list.end()) if (auto it = find(hook_list, to_run.hook); it != hook_list.end())
{ {
m_hooks_trash.push_back(std::move(*it)); m_hooks_trash.push_back(std::move(*it));
hook_list.erase(it); hook_list.erase(it);

View File

@ -120,18 +120,18 @@ public:
~HookManager(); ~HookManager();
void add_hook(Hook hook, String group, HookFlags flags, void add_hook(Hook hook, String group, HookFlags flags,
Regex filter, String commands); Regex filter, String commands, Context& context);
void remove_hooks(const Regex& regex); void remove_hooks(const Regex& regex);
CandidateList complete_hook_group(StringView prefix, ByteCount pos_in_token); CandidateList complete_hook_group(StringView prefix, ByteCount pos_in_token);
void run_hook(Hook hook, StringView param, Context& context); void run_hook(Hook hook, StringView param, Context& context);
private: private:
struct HookData;
HookManager(); HookManager();
// the only one allowed to construct a root hook manager // the only one allowed to construct a root hook manager
friend class Scope; friend class Scope;
struct HookData;
SafePtr<HookManager> m_parent; SafePtr<HookManager> m_parent;
Array<Vector<std::unique_ptr<HookData>, MemoryDomain::Hooks>, enum_desc(Meta::Type<Hook>{}).size()> m_hooks; Array<Vector<std::unique_ptr<HookData>, MemoryDomain::Hooks>, enum_desc(Meta::Type<Hook>{}).size()> m_hooks;

View File

@ -0,0 +1 @@
"a<a-P>i<space><esc>

View File

@ -0,0 +1 @@

View File

@ -0,0 +1 @@
literal regex regex-once regex literal-late late-regex late-regex late-regex-once

View File

@ -0,0 +1,10 @@
provide-module foo %{ }
provide-module foobar %{ }
hook global ModuleLoaded foo %{ set-register a %reg{a} literal }
hook global ModuleLoaded f.* %{ set-register a %reg{a} regex }
hook -once global ModuleLoaded f.* %{ set-register a %reg{a} regex-once }
require-module foo
require-module foobar
hook global ModuleLoaded foo %{ set-register a %reg{a} literal-late }
hook global ModuleLoaded f.* %{ set-register a %reg{a} late-regex }
hook -once global ModuleLoaded f.* %{ set-register a %reg{a} late-regex-once }