Module: Rakit::Protobuf

Defined in:
lib/rakit/protobuf.rb

Class Method Summary collapse

Class Method Details

.generate(proto_dir:, ruby_out:, base_dir: Dir.pwd, protoc: "protoc") ⇒ Object

Generate Ruby from .proto files. proto_dir: directory containing .proto files (and -I root); may be relative to base_dir ruby_out: directory for generated *_pb.rb files; may be relative to base_dir base_dir: directory used to expand relative proto_dir and ruby_out (default: Dir.pwd) protoc: executable name/path (default: “protoc”) Returns ruby_out if generation ran, nil if no proto files found.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rakit/protobuf.rb', line 14

def self.generate(proto_dir:, ruby_out:, base_dir: Dir.pwd, protoc: "protoc")
  expanded_proto_dir = File.expand_path(proto_dir, base_dir)
  expanded_ruby_out = File.expand_path(ruby_out, base_dir)
  # output, in grey, "  generating code from .proto files..."
  puts "\e[30m  generating code from .proto files...\e[0m"
  proto_files = Dir[File.join(expanded_proto_dir, "**", "*.proto")]
  return nil if proto_files.empty?

  FileUtils.mkdir_p(expanded_ruby_out)
  args = ["-I", expanded_proto_dir, "--ruby_out=#{expanded_ruby_out}", *proto_files]
  selected_protoc = resolve_protoc(protoc)
  out, err, status = Open3.capture3(selected_protoc, *args)
  unless status.success?
    warn out unless out.to_s.empty?
    warn err unless err.to_s.empty?
    raise "protoc failed (#{selected_protoc})"
  end

  # output a green checkmark and the command that was run
  puts "\e[32m✓\e[0m #{selected_protoc} #{args.join(" ")}"
  # output that the files were generated
  #puts "  Generated #{proto_files.size} files in #{ruby_out}"
  # output the files that were generated (all files in the ruby_out directory), once per line
  ruby_out_files = Dir[File.join(expanded_ruby_out, "**", "*_pb.rb")]
  ruby_out_files.each do |file|
    # output, in grey, "  #{File.basename(file)}"
    puts "\e[30m  #{File.basename(file)}\e[0m"
  end
  # output the number of files that were generated
  #puts "  Generated #{ruby_out_files.size} files in #{expanded_ruby_out}"
  expanded_ruby_out
end

.resolve_protoc(protoc) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/rakit/protobuf.rb', line 47

def self.resolve_protoc(protoc)
  return protoc if system("which", protoc, out: File::NULL, err: File::NULL)

  grpc_tools = "grpc_tools_ruby_protoc"
  return grpc_tools if system("which", grpc_tools, out: File::NULL, err: File::NULL)

  raise "Neither '#{protoc}' nor '#{grpc_tools}' found on PATH"
end