首页 > 解决方案 > 缩进空格到制表符

问题描述

我在阅读带有空格的代码时确实遇到了问题,因此我在阅读之前使用 Visual Studio 代码编辑器将代码从空格缩进到制表符。

但问题是rails文件很多,我必须重复做同样的操作。所以,我想用它Dir.glob来遍历所有这些并将空格隐藏到选项卡并覆盖这些文件。这是一个可怕的想法,但仍然......

目前我的 String#spaces_to_tabs() 方法如下所示:

代码

# A method that works for now...
String.define_method(:spaces_to_tabs) do
    each_line.map do |x|
        match = x.match(/^([^\S\t\n\r]*)/)[0]
        m_len = match.length
        (m_len > 0 && m_len % 2 == 0) ? ?\t * (m_len / 2) + x[m_len .. -1] : x
    end.join
end

什么样的作品

这是一个测试:

# Put some content that will get converted to space
content = <<~EOF << '# Hello!'
  def x
    'Hello World'
  end

  p x

  module X
    refine Array do
      define_method(:tally2) do
        uniq.reduce({}) { |h, x| h.merge!( x => count(x) ) }
      end
    end
  end

  using X
  [1, 2, 3, 4, 4, 4,?a, ?b, ?a].tally2
  p [1, 2, 3, 4, 4, 4,?a, ?b, ?a].tally2
  \r\r\t\t # Some invalid content
EOF

puts content.spaces_to_tabs

输出:

def x
    'Hello World'
end

p x

module X
    refine Array do
        define_method(:tally2) do
            uniq.reduce({}) { |h, x| h.merge!( x => count(x) ) }
        end
    end
end

using X
[1, 2, 3, 4, 4, 4,?a, ?b, ?a].tally2
p [1, 2, 3, 4, 4, 4,?a, ?b, ?a].tally2
         # Some invalid content
# Hello!

目前它没有:

  1. 影响空格以外的空格(\t、\r、\n)。
  2. 影响代码的输出,仅将空格转换为制表符。

我不能使用我的编辑器,因为:

  1. 使用 Dir.glob(未包含在此示例中),我只能迭代 .rb、.js、.erb、.html、.css 和 .scss 文件。

此外,这很慢,但我最多可以有 1000 个文件(扩展名以上),每个文件有 1000 行代码,但这是最大的,而且不太实用,我通常有 < 100 个文件和几百行代码. 代码可能需要 10 秒,这在这里不是问题,因为我需要为一个项目运行一次代码......

有更好的方法吗?


编辑

这是用于转换 Rails 中所有主要文件的完整代码:

#!/usr/bin/ruby -w
String.define_method(:bold) { "\e[1m#{self}" }

String.define_method(:spaces_to_tabs) do
    each_line.map do |x|
        match = x.match(/^([^\S\t\n\r]*)/)[0]
        m_len = match.length
        (m_len > 0 && m_len % 2 == 0) ? ?\t * (m_len / 2) + x[m_len .. -1] : x
    end.join
end

GREEN = "\e[38;2;85;160;10m".freeze
BLUE = "\e[38;2;0;125;255m".freeze
TURQUOISE = "\e[38;2;60;230;180m".freeze
RESET = "\e[0m".freeze
BLINK = "\e[5m".freeze

dry_test = ARGV.any? { |x| x[/^\-(\-dry\-test|d)$/] }
puts "#{TURQUOISE.bold}:: Info:#{RESET}#{TURQUOISE} Running in Dry Test mode. Files will not be changed.#{RESET}\n\n" if dry_test

Dir.glob("{app,config,db,lib,public}/**/**.{rb,erb,js,css,scss,html}").map do |y|
    if File.file?(y) && File.readable?(y)
        read = IO.read(y)
        converted = read.spaces_to_tabs

        unless read == converted
            puts "#{BLINK}#{BLUE.bold}:: Converting#{RESET}#{GREEN} indentation to tabs of #{y}#{RESET}"
            IO.write(y, converted) unless dry_test
        end
    end
end

标签: regexruby

解决方案


如果这只是关于制表符缩进算法的智力练习,那很好。如果您确实无法查看文件,请使用 Rubocop。它具有允许您美化代码的配置选项,以及它生成的空格类型和它应用的缩进程度。我将它与 Atom 和 atom-beautify 一起使用,但我确信它也有一个用于 VS 代码的插件。https://docs.rubocop.org/rubocop/0.86/cops_layout.html#layoutindentationconsistency


推荐阅读