NuGet: Possibility of adding a line of code via Powershell?

笑着哭i 提交于 2020-01-05 01:09:00

问题


I have a few NuGet packages that I've put together, with one of them being a common project referenced by all the others.

This common project inserts a configuration class into the App_Start folder, and a method on this class is then invoked by WebActivator.

For one of the other packages I wish to add one more line of code to this method but I'm struggling to find a way to do this.

I know that I could very simply add an additional class which contains just this one line of code but I'd prefer, if possible, to use an Install.ps1 powershell script to add the line of code to the existing configuration class.

Using a pro-processed *.cs.pp file will overwrite the existing file (or add a new one), and *.cs.transform doesn't work on such a file.

I know where the class is and what it's called, and I know what the method is called, so does Powershell offer a means of adding a line to the end of said method?


回答1:


This is possible but not trivial to do. You also have to be very careful since deleting someone's code from a NuGet package is not going to make them very happy.

When installing a NuGet package you have access to the Visual Studio object model (EnvDTE). The $project variable can be used to access the specific project item you need. From that you can use the FileCodeModel which represents the code in the file. You would then need to find the class and its method. Then create an edit point and insert the text.

The following will find a class called Class1 and insert a line of code into its Foo method. Note that the line of code inserted will not be correctly indented, you would need to find that out by looking at the document.

$project.ProjectItems.Item("Class1.cs")
$namespace = $item.FileCodeModel.CodeElements | ? {$_.Kind -eq 5}
$namespace.Members.Item("Class1")
$method = $class.Members.Item("Foo")
$endPoint = $method.GetEndpoint([EnvDTE.vsCMPart]::vsCMPartBody)
$editPoint = $endpoint.CreateEditPoint()
$editPoint.Insert("int a = 0;")

Also the above code does not do any error handling.



来源:https://stackoverflow.com/questions/28983749/nuget-possibility-of-adding-a-line-of-code-via-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!