如何使用Codesmith工具将生成的文件添加到多个项目
-
24-10-2019 - |
题
我正在我当前的项目上使用Codesmith,并且正在尝试找出一个问题。对于我的Codesmith项目(.CSP),我可以选择一个选项,以使其自动将所有生成的文件添加到当前项目(.CSPROJ)。但是我希望能够将输出添加到多个项目(.csproj)中。 Codesmith内部是否有一个选项可以允许这样做?还是有一个很好的方法可以通过编程方式做到这一点?
谢谢。
解决方案
我无法找到一种使代码匠自动处理此问题的方法,因此我最终在文件背后的代码中编写了一种自定义方法来处理此问题。
一些注释: - proj文件是XML,因此非常易于编辑,但是实际的“ ItemGroup”节点保存了项目中包含的文件列表,实际上并未以任何特殊方式标记。我最终选择了具有“包含”子节点的“ ItemGroup”节点,但是可能有一种更好的方法来确定您应该使用哪个节点。 - 我建议一次更改所有PROJ文件,而不是创建/更新每个文件。否则,如果您从Visual Studio推出一代,您可能会淹没“此项目已更改,您想重新加载” - 如果您的文件处于源头控制之下(他们是,对吗?!),您将要去需要处理检查文件并将它们添加到源控制以及编辑ProJ文件的同时。
这是(或多或少)我用来向项目添加文件的代码:
/// <summary>
/// Adds the given file to the indicated project
/// </summary>
/// <param name="project">The path of the proj file</param>
/// <param name="projectSubDir">The subdirectory of the project that the
/// file is located in, otherwise an empty string if it is at the project root</param>
/// <param name="file">The name of the file to be added to the project</param>
/// <param name="parent">The name of the parent to group the file to, an
/// empty string if there is no parent file</param>
public static void AddFileToProject(string project, string projectSubDir,
string file, string parent)
{
XDocument proj = XDocument.Load(project);
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var itemGroup = proj.Descendants(ns + "ItemGroup").FirstOrDefault(x => x.Descendants(ns + "Compile").Count() > 0);
if (itemGroup == null)
throw new Exception(string.Format("Unable to find an ItemGroup to add the file {1} to the {0} project", project, file));
//If the file is already listed, don't bother adding it again
if(itemGroup.Descendants(ns + "Compile").Where(x=>x.Attribute("Include").Value.ToString() == file).Count() > 0)
return;
XElement item = new XElement(ns + "Compile",
new XAttribute("Include", Path.Combine(projectSubDir,file)));
//This is used to group files together, in this case the file that is
//regenerated is grouped as a dependent of the user-editable file that
//is not changed by the code generator
if (string.IsNullOrEmpty(parent) == false)
item.Add(new XElement(ns + "DependentUpon", parent));
itemGroup.Add(item);
proj.Save(project);
}
其他提示
您是否考虑过仅编译成共享的组件(DLL),然后您所有项目都可以引用该组件?
我知道这可能不适合您的要求,但我认为这将是实现您所有项目都可以使用的单一来源的最佳方法之一,并且只需根据需要维护一个代码库。
不隶属于 StackOverflow