Skip to content

Commit

Permalink
(chocolatey#2572) Discover and register commands in assemblies
Browse files Browse the repository at this point in the history
This commit updates the way that commands are registered
by handling this automatically by iterating through the entire
Chocolatey CLI assembly and any valid extensions to find
commands that inherit from ICommand and add these to
the pending registration list.
  • Loading branch information
AdmiringWorm committed Aug 11, 2022
1 parent 0a0f28f commit d81e219
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public IEnumerable<ExtensionInformation> RegisterComponents(Container container)
registrator.register_instance<filesystem.IFileSystem>(() => fileSystem);
registrator.register_instance(() => Config.get_configuration_settings());
mainRegistrator.register_dependencies(registrator, configuration);
//registrator.register_assembly_commands(Assembly.GetExecutingAssembly());
registrator.register_assembly_commands(Assembly.GetExecutingAssembly());
registrator.CanReplaceRegister = false;

var assemblies = fileSystem.get_extension_assemblies();
Expand Down Expand Up @@ -151,11 +151,11 @@ You can override this compatibility check and force loading the extension by pas
hasRegisteredDependencies = !clonedRegistrator.RegistrationFailed;
}

//if (hasRegisteredDependencies)
//{
// clonedRegistrator.register_assembly_commands(assembly);
// hasRegisteredDependencies = !clonedRegistrator.RegistrationFailed;
//}
if (hasRegisteredDependencies)
{
clonedRegistrator.register_assembly_commands(assembly);
hasRegisteredDependencies = !clonedRegistrator.RegistrationFailed;
}

if (hasRegisteredDependencies && !clonedRegistrator.RegistrationFailed)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,31 @@ public object Clone()
return cloned;
}

public void register_assembly_commands(IAssembly assembly)
{
try
{
var types = assembly.get_loadable_types()
.Where(t => t.IsClass && !t.IsAbstract && typeof(ICommand).IsAssignableFrom(t) && t.GetCustomAttribute<CommandForAttribute>() != null);

foreach (var t in types)
{
if (RegistrationFailed)
{
break;
}

register_command(t);
}
}
catch (Exception ex)
{
this.Log().Warn("Unable to register commands for '{0}'. Continuing without registering commands!", assembly.GetName().Name);
this.Log().Warn(ex.Message);
RegistrationFailed = true;
}
}

public void register_command(Type commandType)
{
ensure_not_built();
Expand Down

0 comments on commit d81e219

Please sign in to comment.