跳过 TT 自动化脚本中的解决方案文件夹

Skipping solution folders in TT automation script

我有一个文本模板片段,它生成一个 Solution class 和一个 Assemblies 属性 来列出 Visual Studio 解决方案中的所有项目程序集帮助 IoC 容器配置 (GitHub, NuGet)。但是,当项目放置在解决方案文件夹中时,它会失败。如何使此脚本的解决方案文件夹透明?有问题的代码是:

<#+

    class SolutionAssemblyNames : IEnumerable<string>
    {
        public SolutionAssemblyNames(ITextTemplatingEngineHost host)
        {
            Host = host;
        }

        public IEnumerator<string> GetEnumerator() => Assemblies.GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        IEnumerable<string> Assemblies => Projects
            .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
            .Distinct().Where(a => !string.IsNullOrWhiteSpace(a));

        IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();
        DTE VisualStudio => (Host as IServiceProvider).GetService(typeof(DTE)) as DTE;
        ITextTemplatingEngineHost Host { get; }
    }
#>

DTE 没有 return 项目的平面列表,因此您需要主动检查解决方案文件夹,然后递归地读取其子项目(因为您可以在解决方案文件夹中包含解决方案文件夹,等等)

    IEnumerable<string> Assemblies => Projects
        .SelectMany(GetProjectAndSubProjects) // ################# Flatten the list of projects
        .Select(p => p?.Properties?.Item("AssemblyName")?.Value as string)
        .Distinct()
        .Where(a => !string.IsNullOrWhiteSpace(a));

    IEnumerable<Project> Projects => VisualStudio.Solution.Projects.OfType<Project>();

    private static IEnumerable<EnvDTE.Project> GetProjectAndSubProjects(EnvDTE.Project project)
    {
        if (project.Kind == VsProjectKindSolutionFolder)
        {
            return project.ProjectItems
                .OfType<EnvDTE.ProjectItem>()
                .Select(p => p.SubProject)
                .Where(p => p != null)
                .SelectMany(GetProjectAndSubProjects);
        }

        return new[] { project };
    }

    // Copied from EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder
    private const string VsProjectKindSolutionFolder = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";