From 5cad95ba4b2b97de0db7f3125e02ad719851b430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Verg=C3=A9?= Date: Wed, 3 Feb 2016 18:32:01 +0100 Subject: [PATCH] Prototype: yaml-fix-indentation --- yaml-fix-indentation | 50 +++++++++++++++++++++++++++++++++++++++++ yaml-remove-indentation | 37 ++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100755 yaml-fix-indentation create mode 100755 yaml-remove-indentation diff --git a/yaml-fix-indentation b/yaml-fix-indentation new file mode 100755 index 0000000..dac8b44 --- /dev/null +++ b/yaml-fix-indentation @@ -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 diff --git a/yaml-remove-indentation b/yaml-remove-indentation new file mode 100755 index 0000000..91b0de1 --- /dev/null +++ b/yaml-remove-indentation @@ -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))