Copy yaml formatting (indent) from one file to another

2.3k views Asked by At

A translator completely messed up a yaml file by copying everything into word (don't ask).

I have already cleaned up the file using regexes, but the indent (spacing) is now missing; everything starts at the first character:

es:
default_blocks:
thank_you_html: "thank you text"

instead of

en:
  default_blocks:
    thank_you_html: "thank you text"

Do you have a good idea on how to automatically copy the format/structure/indent from the correct file (say en.yml) to the corrupt one (say es.yml)? (I'm using textmate 2.0 as editor)

Thanks!

1

There are 1 answers

1
kwood On BEST ANSWER

Assuming the original and the translation contain exactly the same strings per line (except for the indentation problem), a quick&dirty script scanning the leading whitespace may solve this:

#!/usr/bin/env ruby
# encoding: UTF-8

indented = File.readlines(ARGV[0]).map do |l|
  l.scan(/^\s+/)[0]
end.zip(File.readlines(ARGV[1])).map { |e| e.join }.join

File.open(ARGV[1], "w") { |io| io.write(indented) }

Save it, make it executable and call

./script_name.rb en.yml es.yml

Wouldn't mess with Textmate if this is not a regular task, but you could easily transform this to a command and either prompt for the two files via a dialog or select both in the file browser, open one of them in the current tab and differentiate them via environment variables ($TM_FILEPATH, $TM_SELECTED_FILES)