From 88876909c1d80b60b02415c8a270e5f0668cc65f Mon Sep 17 00:00:00 2001 From: Kazuki Nishikawa Date: Tue, 11 Feb 2025 11:08:05 +0900 Subject: [PATCH] feat: allow formatting code with different base level of indentation ref: #333 --- lib/rufo/formatter.rb | 15 +++++++++++++ spec/lib/rufo/formatter_spec.rb | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/lib/rufo/formatter.rb b/lib/rufo/formatter.rb index 935ef2ac..6946db25 100644 --- a/lib/rufo/formatter.rb +++ b/lib/rufo/formatter.rb @@ -4,6 +4,7 @@ class Rufo::Formatter include Rufo::Settings INDENT_SIZE = 2 + DEFAULT_BASE_INDENTATION = 0 EMPTY_STRING = [:string_literal, [:string_content]] EMPTY_HASH = [:hash, nil] @@ -171,6 +172,8 @@ def initialize(code, **options) # can be added appropriately for heredocs for example. @literal_elements_level = nil + @base_indentation = options.delete(:base_indentation) || DEFAULT_BASE_INDENTATION + init_settings(options) end @@ -186,6 +189,9 @@ def format remove_lines_before_inline_declarations @output.lstrip! @output = "\n" if @output.empty? + if @base_indentation > 0 + insert_base_indent(@base_indentation) + end end def visit(node) @@ -4214,4 +4220,13 @@ def block_arg_type(node) node end end + + def insert_base_indent(identation) + spaces = " " * identation + lines = @output.lines + lines.each do |line| + line.insert(0, spaces) + end + @output = lines.join + end end diff --git a/spec/lib/rufo/formatter_spec.rb b/spec/lib/rufo/formatter_spec.rb index 182ec9b7..64dd4d6b 100644 --- a/spec/lib/rufo/formatter_spec.rb +++ b/spec/lib/rufo/formatter_spec.rb @@ -111,4 +111,41 @@ def assert_format(code, expected = code, **options) }.to raise_error(Rufo::UnknownSyntaxError) end end + + describe "base_indentation option" do + it "formats with different indentation levels" do + source = <<~SOURCE + def foo + puts "a" + end + SOURCE + + # default identation level + expect(Rufo.format(source)).to eq source + + # level 2 + expected = <<-EXPECTED + def foo + puts "a" + end + EXPECTED + expect(Rufo.format(source, base_indentation: 2)).to eq expected + + # level 4 + expected = <<-EXPECTED + def foo + puts "a" + end + EXPECTED + expect(Rufo.format(source, base_indentation: 4)).to eq expected + + # level 6 + expected = <<-EXPECTED + def foo + puts "a" + end + EXPECTED + expect(Rufo.format(source, base_indentation: 6)).to eq expected + end + end end