Prototype: yaml-fix-indentation
parent
1f1757ced4
commit
5cad95ba4b
@ -0,0 +1,50 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euf
|
||||
|
||||
DIR=$(dirname "$(readlink -f $0)")
|
||||
|
||||
fix_one_problem_in_file() {
|
||||
local filename=$1
|
||||
local error
|
||||
error=$(yamllint -f parsable "$filename" | grep 'wrong indentation: expected' \
|
||||
| head -n 1)
|
||||
if [ -z "$error" ]; then
|
||||
return 1
|
||||
fi
|
||||
local line=$(echo $error | cut -d: -f2)
|
||||
local expected=$(echo $error | cut -d: -f5 | sed 's/.* expected //;s/ but found.*//')
|
||||
local found=$(echo $error | cut -d: -f5 | sed 's/.*but found //;s/(inde.*//')
|
||||
"$DIR/yaml-remove-indentation" "$filename" $line $expected $found
|
||||
return 0
|
||||
}
|
||||
|
||||
reformat_yaml() {
|
||||
local in=$1
|
||||
local out=$2
|
||||
python -c 'import sys, yaml; yaml.dump(yaml.load(sys.stdin), sys.stdout)' <"$in" >"$out"
|
||||
}
|
||||
|
||||
fix_one_file() {
|
||||
local filename=$1
|
||||
local backup=$(mktemp originalXXXXX)
|
||||
cp "$filename" "$backup"
|
||||
echo "FIXING $file"
|
||||
while fix_one_problem_in_file "$filename"; do continue; done
|
||||
echo "CHECKING $file"
|
||||
local tmp_old=$(mktemp oldXXXXX)
|
||||
local tmp_new=$(mktemp newXXXXX)
|
||||
reformat_yaml "$backup" "$tmp_old"
|
||||
reformat_yaml "$filename" "$tmp_new"
|
||||
if ! diff -q "$tmp_old" "$tmp_new" &>/dev/null; then
|
||||
echo "error: after reformating, the file contents is detected different."
|
||||
echo "diff $backup $filename"
|
||||
echo "diff $tmp_old $tmp_new"
|
||||
exit 1
|
||||
fi
|
||||
rm "$backup" "$tmp_old" "$tmp_new"
|
||||
}
|
||||
|
||||
for file in "$@"; do
|
||||
fix_one_file "$file"
|
||||
done
|
@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
file = sys.argv[1]
|
||||
line = int(sys.argv[2]) - 1
|
||||
indent_expected = int(sys.argv[3])
|
||||
indent_found = int(sys.argv[4])
|
||||
|
||||
with open(file) as f:
|
||||
lines = f.readlines()
|
||||
|
||||
before = lines[:line]
|
||||
|
||||
is_a_list = lines[line].strip()[0] == '-'
|
||||
|
||||
i = line
|
||||
while (i < len(lines) and
|
||||
(lines[i].strip() == '' or
|
||||
(not is_a_list and lines[i].startswith(indent_found * ' ')) or
|
||||
(is_a_list and (lines[i].startswith(indent_found * ' ' + '-') or
|
||||
lines[i].startswith(indent_found * ' ' + ' '))))):
|
||||
i += 1
|
||||
|
||||
contents = lines[line:i]
|
||||
after = lines[i:]
|
||||
|
||||
new_contents = []
|
||||
for line in contents:
|
||||
if line.strip() != '':
|
||||
line = (indent_expected * ' ') + line[indent_found:]
|
||||
new_contents.append(line)
|
||||
|
||||
with open(file, 'w') as f:
|
||||
f.write(''.join(before))
|
||||
f.write(''.join(new_contents))
|
||||
f.write(''.join(after))
|
Loading…
Reference in New Issue