Skip to content

Commit

Permalink
add nested package declaration and simple indent prittification
Browse files Browse the repository at this point in the history
  • Loading branch information
colinbendell committed Mar 22, 2024
1 parent 0fecc74 commit bf45b2e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 23 deletions.
15 changes: 8 additions & 7 deletions bin/protoboeuf
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
#!/bin/env ruby
#!env ruby
# frozen_string_literal: true

require "protoboeuf/codegen"
require "protoboeuf/parser"
require_relative "../lib/protoboeuf/codegen"
require_relative "../lib/protoboeuf/parser"
require "optparse"

op = OptionParser.new { |opts|
op = OptionParser.new do |opts|
opts.banner = "Usage: protoboeuf file.proto"
}
end
op.parse!

if ARGV[0] && File.exist?(ARGV[0])
unit = ProtoBoeuf.parse_file ARGV[0]
gen = ProtoBoeuf::CodeGen.new unit
unit = ProtoBoeuf.parse_file(ARGV[0])
gen = ProtoBoeuf::CodeGen.new(unit)
puts gen.to_ruby
else
$stderr.puts op
Expand Down
31 changes: 15 additions & 16 deletions lib/protoboeuf/codegen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -754,26 +754,25 @@ def initialize(ast)
end

def to_ruby
head = "# frozen_string_literal: true\n"
head += if @ast.package
"module " + @ast.package.split('_').map(&:capitalize).join + "\n"
else
""
end
# This is a poorman's indent prettier.
# TODO: We really should build a ruby AST and then apply a ruby serializer that pretties appropriately

tail = if @ast.package
"end"
else
""
end
indent_level = 0
indent = -> { " " * ((indent_level += 1) - 1) }
unindent = -> { " " * ((indent_level -= 1) + 1) }
indent_lines = ->(body) { body.split("\n").map { |line| (" " * indent_level) + line }.join("\n") }

packages = (@ast.package || "").split(".").reject(&:empty?)
head = "# frozen_string_literal: true\n\n"
head += packages.map { |m| indent.call + "module " + m.split("_").map(&:capitalize).join + "\n" }.join

toplevel_enums = @ast.enums.group_by(&:name)
body = indent_lines.call(@ast.enums.map { |enum| EnumCompiler.result(enum) }.join) + "\n"
body += indent_lines.call(@ast.messages.map { |message| MessageCompiler.result(message, toplevel_enums) }.join)

tail = packages.map { unindent.call + "end" }.join("\n")

head + @ast.enums.map { |enum|
EnumCompiler.result(enum)
}.join + @ast.messages.map { |message|
MessageCompiler.result(message, toplevel_enums)
}.join + tail
head + body + tail
end
end
end

0 comments on commit bf45b2e

Please sign in to comment.