如何根据几个简单的规则缩进源代码?
作为示例,我使用 sed 并要求将 selenium HTML 源表转换为以下类似 rspec 的代码。我怎样才能一致地缩进describe
和之间的行end
?理想情况下,我希望能够添加缩进
describe "Landing" do
visit("http://some_url/url_reset")
visit("http://some_url/url_3_step_minimal_foundation")
# comments
expect(css_vehicle1_auto_year) to be_visible
end
describe "Stage1" do
wait_for_element_present(css_vehicle1_auto_year option_auto_year)
select(auto_year, from: css_vehicle1_auto_year)
...
end
describe "Stage2" do
fill_in(css_driver1_first_name, with: driver1_first_name)
fill_in(css_driver1_last_name, with: driver1_last_name)
...
submit(css_policy_form)
expect(css_vehicle1_coverage_type) to be_visible
end
describe "Stage3" do
wait_for_element_present(css_vehicle1_coverage_type)
select(coverage_type, from: css_vehicle1_coverage_type)
find(css_has_auto_insurance).click
...
submit(css_policy_form)
expect(css_quotes) to be_visible
end
所以我有
describe "Landing" do
visit("http://some_url/url_reset")
visit("http://some_url/url_3_step_minimal_foundation")
# comments
expect(css_vehicle1_auto_year) to be_visible
end
describe "Stage1" do
wait_for_element_present(css_vehicle1_auto_year option_auto_year)
select(auto_year, from: css_vehicle1_auto_year)
...
end
describe "Stage2" do
fill_in(css_driver1_first_name, with: driver1_first_name)
fill_in(css_driver1_last_name, with: driver1_last_name)
...
submit(css_policy_form)
expect(css_vehicle1_coverage_type) to be_visible
end
describe "Stage3" do
wait_for_element_present(css_vehicle1_coverage_type)
select(coverage_type, from: css_vehicle1_coverage_type)
find(css_has_auto_insurance).click
...
submit(css_policy_form)
expect(css_quotes) to be_visible
end
现有 sed 和 awk 的源代码位于https://jsfiddle.net/4gbj5mh4/但这真的很混乱,不是我要问的。我已经掌握了简单的 sed 和 awk 的窍门,但不知道从哪里开始。
如果它也能处理递归那就太好了。对我来说并不重要,但概括可能对其使用此问题的其他人有用,即
describe "a" do
describe "b" do
stuff
more stuff
end
end
到
describe "a" do
describe "b" do
stuff
more stuff
end
end
顺便说一句,我也在做这个自定义转换,部分原因是我在 selenium 中使用变量作为页面对象,并且它们阻止了到 rspec 的内置导出。
答案1
和awk
:
awk '
/^end/ { sub(" ", "", indent) } # Or { indent = substr(indent, 3) }
{ print indent $0 }
/^describe/ { indent = indent" " }
' <file