请选择 进入手机版 | 继续访问电脑版

技术控

    今日:204| 主题:57264
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Adding a verb to the dotnet CLI tooling

[复制链接]
失去才懂得拥有 发表于 2016-10-4 06:09:54
190 1
The dotnet CLI tooling comes with several built-in cmds such as build , run and test , but it turns out it’s possible to add your own verb to that list.
  Arbitrary cmds

   From Intro to .NET Core CLI - Design
   The way the dotnet driver finds the command it is instructed to run using dotnet {command} is via a convention;  any executable that is placed in the PATH and is named dotnet-{command} will be available to the driver  . For example, when you install the CLI toolchain there will be an executable called dotnet-build in your PATH; when you run dotnet build , the driver will run the dotnet-build executable. All of the arguments following the command are passed to the command being invoked. So, in the invocation of dotnet build --native , the --native switch will be passed to dotnet-build executable that will do some action based on it (in this case, produce a single native binary).
   This is also the basics of the current extensibility model of the toolchain.  Any executable found in the PATH named in this way, that is as dotnet-{command} , will be invoked by the dotnet driver.  
   Fun fact:This means that it’s actually possible to make a dotnet go command! You just need to make a copy of go.exe and rename it to dotnet-go.exe
   

Adding a verb to the dotnet CLI tooling

Adding a verb to the dotnet CLI tooling-1-技术控-available,following,possible,command,produce

   Yay dotnet go (I know, completely useless, but fun none-the-less)!!
   

Adding a verb to the dotnet CLI tooling

Adding a verb to the dotnet CLI tooling-2-技术控-available,following,possible,command,produce

   (and yes before you ask, you can also make dotnet dotnet work, but please don’t do that!!)
   With regards to documentation, there’s further information in the ‘Adding a Command’ section of the Developer Guide. Also the source code of the dotnet test command is a really useful reference and helped me out several times.
   Before I go any further I just want to acknowledge the 2 blog posts listed below. They show you how to build a custom command that will compresses all the images in the current directory and how to make it available to the dotnet tooling as a NuGet package:
  
       
  • Using nuget packages in ASP.NET Core   
  • Building a custom dotnet cli tool  
  However they don’t explain how to interact with the current project or access it’s output. This is what I wanted to do, so this post will pick up where those posts left off.
  Information about the current Project

   Any effective dotnet verb needs to know about the project it is running in and helpfully those kind developers at Microsoft have created some useful classes that will parse and examine a project.json file (available in the Microsoft.DotNet.ProjectModel NuGet package). It’s pretty simple to work with, just a few lines of code and you’re able to access the entire Project model :
  1. Project project;
  2. var currentDirectory = Directory.GetCurrentDirectory();
  3. if (ProjectReader.TryGetProject(currentDirectory, out project))
  4. {
  5.     if (project.Files.SourceFiles.Any())
  6.     {
  7.         Console.WriteLine("Files:");
  8.         foreach (var file in project.Files.SourceFiles)
  9.             Console.WriteLine("  {0}", file.Replace(currentDirectory, ""));
  10.     }
  11.     if (project.Dependencies.Any())
  12.     {
  13.         Console.WriteLine("Dependencies:");
  14.         foreach (var dependancy in project.Dependencies)
  15.         {
  16.             Console.WriteLine("  {0} - Line:{1}, Column:{2}",
  17.                     dependancy.SourceFilePath.Replace(currentDirectory, ""),
  18.                     dependancy.SourceLine,
  19.                     dependancy.SourceColumn);
  20.         }
  21.     }
  22.     ...
  23. }
复制代码
Building a Project

   In addition to knowing about the current project, we need to ensure it successfully builds before we can do anything else with it. Fortunately this is also simple thanks to the Microsoft.DotNet.Cli.Utils NuGet package (along with further help from Microsoft.DotNet.ProjectModel which provides the BuildWorkspace ):
  1. // Create a workspace
  2. var workspace = new BuildWorkspace(ProjectReaderSettings.ReadFromEnvironment());
  3. // Fetch the ProjectContexts
  4. var projectPath = project.ProjectFilePath;
  5. var runtimeIdentifiers =
  6.     RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers();
  7. var projectContexts = workspace.GetProjectContextCollection(projectPath)
  8.        .EnsureValid(projectPath)
  9.        .FrameworkOnlyContexts
  10.        .Select(c => workspace.GetRuntimeContext(c, runtimeIdentifiers))
  11.        .ToList();
  12. // Setup the build arguments
  13. var projectContextToBuild = projectContexts.First();
  14. var cmdArgs = new List<string>
  15. {
  16.     projectPath,
  17.     "--configuration", "Release",
  18.     "--framework", projectContextToBuild.TargetFramework.ToString()
  19. };
  20. // Build!!
  21. Console.WriteLine("Building Project for {0}", projectContextToBuild.RuntimeIdentifier);
  22. var result = Command.CreateDotNet("build", cmdArgs).Execute();
  23. Console.WriteLine("Build {0}", result.ExitCode == 0 ? "SUCCEEDED" : "FAILED");
复制代码
  When this runs you get the familiar dotnet build output if it successfully builds or any error/diagnostic messages if not.
  Integrating with BenchmarkDotNet

   Now that we know the project has produced an .exe or .dll, we can finally wire-up BenchmarkDotNet and get it to execute the benchmarks for us:
  1. try
  2. {
  3.     Console.WriteLine("Running BenchmarkDotNet");
  4.     var benchmarkAssemblyPath =
  5.         projectContextToBuild.GetOutputPaths(config).RuntimeFiles.Assembly;
  6.     var benchmarkAssembly =
  7.         AssemblyLoadContext.Default.LoadFromAssemblyPath(benchmarkAssemblyPath);
  8.     Console.WriteLine("Successfully loaded: {0}\n", benchmarkAssembly);
  9.     var switcher = new BenchmarkSwitcher(benchmarkAssembly);
  10.     var summary = switcher.Run(args);
  11. }
  12. catch (Exception ex)
  13. {
  14.     Console.WriteLine("Error running BenchmarkDotNet");
  15.     Console.WriteLine(ex);
  16. }
复制代码
  Because BenchmarkDotNet is a command-line tool we don’t actually need to do much work. It’s just a case of creating a BenchmarkSwitcher , giving it a reference to the dll that contains the benchmarks and then passing in the command line arguments. BenchmarkDotNet will then do the rest of the work for us!
   However if you need to parse command line arguments yourself I’d recommend re-using the existing helper classes as they make life much easier and will ensure that your tool fits in with the dotnet tooling ethos.
  The final result

   Finally, to test it out, we’ll use a simple test app from the BenchmarkDotNet Getting Started Guide , with the following in the project.json file (note the added tools section):
  1. {
  2.   "version": "1.0.0-*",
  3.   "buildOptions": {
  4.     "emitEntryPoint": true
  5.   },
  6.   "dependencies": {
  7.     "Microsoft.NETCore.App": {
  8.       "type": "platform",
  9.       "version": "1.0.0-rc2-3002702"
  10.     },
  11.     "BenchmarkDotNet": "0.9.9"
  12.   },
  13.   "frameworks": {
  14.     "netcoreapp1.0": {
  15.       "imports": "dnxcore50"
  16.     }
  17.   },
  18.   "tools": {
  19.     "BenchmarkCommand": "1.0.0"
  20.   }
  21. }
复制代码
  Then after doing a dotnet restore , we can finally run our new dotnet benchmark command:
  1. λ dotnet benchmark --class Md5VsSha256
  2. Building Project - BenchmarkCommandTest
  3. Project BenchmarkCommandTest (.NETCoreApp,Version=v1.0) will be compiled because expected outputs are missing
  4. Compiling BenchmarkCommandTest for .NETCoreApp,Version=v1.0
  5. Compilation succeeded.
  6.     0 Warning(s)
  7.     0 Error(s)
  8. Time elapsed 00:00:00.9760886
  9. Build SUCCEEDED
  10. Running BenchmarkDotNet
  11. C:\Projects\BenchmarkCommandTest\bin\Release\netcoreapp1.0\BenchmarkCommandTest.dll
  12. Successfully loaded: BenchmarkCommandTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  13. Target type: Md5VsSha256
  14. // ***** BenchmarkRunner: Start   *****
  15. // Found benchmarks:
  16. //   Md5VsSha256_Sha256
  17. //   Md5VsSha256_Md5
  18. // Validating benchmarks:
  19. // **************************
  20. // Benchmark: Md5VsSha256_Sha256
  21. // *** Generate ***
  22. // Result = Success
  23. // BinariesDirectoryPath = C:\Projects\BDN.Auto\binaries
  24. // *** Build ***
  25. // Result = Success
  26. // *** Execute ***
  27. // Launch: 1
  28. // Benchmark Process Environment Information:
  29. // CLR=CORE, Arch=64-bit ? [RyuJIT]
  30. // GC=Concurrent Workstation
  31. ...
复制代码
  If you’ve used BenchmarkDotNet before you’ll recognise its output, if not it’s output is all the lines starting with // . A final note, currently the Console colours from the command aren’t displayed, but that should be fixed sometime soon , which is great because BenchmarkDotNet looks way better in full-colour!!



上一篇:Exfiltrating files with BusyBox
下一篇:How we improved Kubernetes Dashboard UI in 1.4 for your production needs​
填充层 发表于 2016-10-23 09:24:21
洗洗更白白,顶顶更健康!
回复 支持 反对

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表