首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用gRPC工具生成代码

如何使用gRPC工具生成代码
EN

Stack Overflow用户
提问于 2018-06-05 03:14:15
回答 1查看 11.1K关注 0票数 13

我已经阅读了教程,并且能够生成.cs文件,但它不包含我的任何服务或rpc定义。

我已经将protoc添加到我的路径中,并从项目目录中进行添加。

protoc project1.proto --csharp_out="C:\output" --plugin=protoc-gen-grpc="c:\Users\me\.nuget\packages\grpc.tools\1.8.0\tools\windows_x64\grpc_csharp_plugin.exe"

控制台中无错误输出

EN

回答 1

Stack Overflow用户

发布于 2018-08-19 14:53:00

对于其他发现这一点的人来说,这里只是一个空洞的评论,关于这一点的文档非常过时,而且是完全错误的。

安装Grpc.Tools不会在包文件夹中安装任何东西;这是遗留行为,即使在windows上也不再是这样。

安装Grpc.Tools时,它将隐藏在本地程序包缓存中,您可以通过调用以下命令查看:

代码语言:javascript
复制
$ dotnet nuget locals all --list
info : http-cache: /Users/doug/.local/share/NuGet/v3-cache
info : global-packages: /Users/doug/.nuget/packages/
info : temp: /var/folders/xx/s2hnzbrj3yn4hp1bg8q9gb_m0000gn/T/NuGetScratch

您需要的二进制文件将位于其中一个文件夹中。

最简单的方法是直接从nuget下载Grpc.Tools包,并将其安装到本地。

我已经破解了这个小助手脚本来做这件事,它在windows/mac/linux上工作,这可能会减轻其他人开始使用它的难度:

代码语言:javascript
复制
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Mono.Unix;

namespace BuildProtocol
{
  public class Program
  {
    private const string ToolsUrl = "https://www.nuget.org/api/v2/package/Grpc.Tools/";
    private const string Service = "Greeter";
    private static string ProtocolPath = Path.Combine("..", "protos");
    private static string Protocol = Path.Combine(ProtocolPath, "helloworld.proto");
    private static string Output = Path.Combine("..", "Greeter");

    public static void Main(string[] args)
    {
      RequireTools().Wait();

      var protoc = ProtocPath();
      var plugin = ProtocPluginPath();

      Console.WriteLine($"Using: {protoc}");
      Console.WriteLine($"Using: {plugin}");

      var command = new string[]
      {
        $"-I{ProtocolPath}",
        $"--csharp_out={Output}",
        $"--grpc_out={Output}",
        $"--plugin=protoc-gen-grpc=\"{plugin}\"",
        Protocol,
      };

      Console.WriteLine($"Exec: {protoc} {string.Join(' ', command)}");

      var process = new Process
      {
        StartInfo = new ProcessStartInfo
        {
          UseShellExecute = false,
          FileName = protoc,
          Arguments = string.Join(' ', command)
        }
      };

      process.Start();
      process.WaitForExit();

      Console.WriteLine($"Completed status: {process.ExitCode}");
    }

    public static async Task RequireTools()
    {
      if (!Directory.Exists("Tools"))
      {
        Console.WriteLine("No local tools found, downloading binaries from nuget...");
        Directory.CreateDirectory("Tools");
        await DownloadTools();
        ExtractTools();
      }
    }

    private static void ExtractTools()
    {
      ZipFile.ExtractToDirectory(Path.Combine("Tools", "tools.zip"), Path.Combine("Tools", "bin"));
    }

    private static async Task DownloadTools()
    {
      using (var client = new HttpClient())
      {
        Console.WriteLine($"Fetching: {ToolsUrl}");
        using (var result = await client.GetAsync(ToolsUrl))
        {
          if (!result.IsSuccessStatusCode) throw new Exception($"Unable to download tools ({result.StatusCode}), check URL");
          var localArchive = Path.Combine("Tools", "tools.zip");
          Console.WriteLine($"Saving to: {localArchive}");
          File.WriteAllBytes(localArchive, await result.Content.ReadAsByteArrayAsync());
        }
      }
    }

    private static string ProtocPath()
    {
      var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "protoc");
      RequireExecutablePermission(path);
      return WithExeExtensionIfRequired(path);
    }

    private static string ProtocPluginPath()
    {
      var path = Path.Combine("Tools", "bin", "tools", DetermineArch(), "grpc_csharp_plugin");
      RequireExecutablePermission(path);
      return WithExeExtensionIfRequired(path);
    }

    private static void RequireExecutablePermission(string path)
    {
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;
      Console.WriteLine($"Ensuring +x on {path}");
      var unixFileInfo = new UnixFileInfo(path);
      unixFileInfo.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.UserExecute;
    }

    private static string WithExeExtensionIfRequired(string path)
    {
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
      {
        path += ".exe";
      }

      return path;
    }

    private static string DetermineArch()
    {
      var arch = RuntimeInformation.OSArchitecture;
      if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
      {
        return WithArch("windows_", arch);
      }

      if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
      {
        return WithArch("macosx_", arch);
      }

      if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
      {
        return WithArch("linux_", arch);
      }

      throw new Exception("Unable to determine runtime");
    }

    private static string WithArch(string platform, Architecture arch)
    {
      switch (arch)
      {
        case Architecture.X64:
          return $"{platform}x86";
        case Architecture.X86:
          return $"{platform}x64";
        default:
          throw new ArgumentOutOfRangeException(nameof(arch), arch, null);
      }
    }
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50687335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档