我有数百个文件,其中也有数百个“应该”陈述。
是否有某种自动方式将这些文件更新为新语法?
我想要既能创建新文件又能内联修改现有文件的选项。
最佳答案
sed 是一个很好的工具。
以下将处理当前目录中的所有文件并将它们写入 _spec_seded
目录中的新文件。这目前处理了大约 99% 以上的更改,但可能仍然需要您进行一些手动更改(数量将取决于您的代码和编码风格)。
与 sed 脚本一样,您应该检查结果、运行差异并手动查看文件。理想情况下,您使用的是 git,这有助于使差异更容易。
filenum=1
find . -type f -name '*_spec.rb' | while read file; do
mkdir -p ../_spec_seded/"${file%/*}"
echo "next file...$filenum...$file"
let filenum+=1
cp "$file" ../_spec_seded/"$file"
sed -i ' # Exclude:
/^ *describe .*do/! { # -describe...do descriptions
/^ *it .*do/! { # -it...do descriptions
/^[[:blank:]]*\#/! { # -comments
/^ *def .*\.should.*/! { # -inline methods
/\.should/ {
s/\.should/)\.to/ # Change .should to .to
s/\(\S\)/expect(\1/ # Add expect( at start of line.
/\.to\( \|_not \)>\=/ s/>\=/be >\=/ # Change operators for
/\.to\( \|_not \)>[^=]/ s/>/be >/ # >, >=, <, <= and !=
/\.to\( \|_not \)<\=/ s/<\=/be <\=/
/\.to\( \|_not \)<[^=]/ s/</be </
/\.to\( \|_not \)\!\=/ s/\!\=/be \!\=/
}
/\.to +==\( +\|$\)/ s/==/eq/
/=\~/ { # Change match operator
s/=\~/match(/
s/$/ )/
s/\[ )$/\[/
}
s/[^}.to|end.to]\.to /).to / # Add paren
/eq ({.*} )/ s/ ({/ ( {/ # Add space
/to\(_\|_not_\)receive/ s/_receive/ receive/ # receive
/\.to eq \[.*\]/ {
s/ eq \[/ match_array([/
s/\]$/\])/
}
/expect.*(.*lambda.*{.*})/ { # Remove unneeded lambdas
s/( *lambda *{/{/
s/ })\.to / }\.to /
}
/expect *{ *.*(.*) *})\.to/ { # Fix extra end paren
s/})\.to/}\.to/
}
}
}
}
}' ../_spec_seded/"$file"
done
请谨慎使用。目前,该脚本在 _seded/
中创建新文件以供首先审查以确保安全。该脚本位于 /spec
目录中并从那里运行。
如果您有数百个文件,这可以节省您数小时或数天的工作时间!
如果您使用它,我建议“第 2 步”是手动将文件从 _spec_seded
复制到 spec
本身并运行它们。我建议您不要只是重命名整个目录。一方面,spec_helper.rb
等文件当前未复制到 _spec_seded
。
11/18/2013 注意:我继续升级这个脚本。覆盖更多的边缘情况并使匹配更具体并排除更多的边缘情况,例如注释行。
附言可以通过(从项目目录根目录)查看应审查的差异:
diff -r /spec /_spec_seded
git 也有很好的 diff 选项,但我喜欢在将文件添加到 git 之前先看一下。
关于ruby - RSpec - 从 'should' 升级到 'expect' 语法的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570644/