From f00781edb4c338804fa47645726857124d62b66b Mon Sep 17 00:00:00 2001 From: Ev Bogdanov Date: Thu, 17 Aug 2017 01:04:01 +0300 Subject: [PATCH] Farewell Perl. Hello Python --- bin/s2t | 39 +++++++++++++++++++++++++-------------- bin/t2s | 54 +++++++++++++++++++----------------------------------- 2 files changed, 44 insertions(+), 49 deletions(-) diff --git a/bin/s2t b/bin/s2t index 3237780..9b67677 100755 --- a/bin/s2t +++ b/bin/s2t @@ -1,19 +1,30 @@ -#!/usr/bin/env perl +#!/usr/bin/env python3 -use strict; -use warnings; +import sys -my $N_SPACES = $ARGV[0] || 4; +DEFAULT_N_SPACES = 4 +TAB, SPACE = ' ', ' ' -while (my $line = ) { - # Skip empty lines - print "\n" and next if $line !~ m/\S/; +try: + n_spaces = int(sys.argv[1]) +except: + n_spaces = DEFAULT_N_SPACES - $line =~ m/^(\s*)(.+)$/; - my $n_spaces = length($1); - my $n_tabs = ($n_spaces > 0 and $n_spaces < $N_SPACES) - ? 1 - : int($n_spaces / $N_SPACES); +if n_spaces < 1: + n_spaces = DEFAULT_N_SPACES - print "\t" x $n_tabs . "$2\n"; -} +for line in sys.stdin: + line = line.rstrip() + n_leading_spaces = 0 + + for ch in line: + if ch != SPACE: + break + n_leading_spaces += 1 + + if 0 < n_leading_spaces < n_spaces: + n_tabs = 1 + else: + n_tabs = n_leading_spaces // n_spaces + + print(TAB * n_tabs, line[n_leading_spaces:], sep='') diff --git a/bin/t2s b/bin/t2s index f80ca53..9a1fecd 100755 --- a/bin/t2s +++ b/bin/t2s @@ -1,42 +1,26 @@ -#!/usr/bin/env bash +#!/usr/bin/env python3 -n_spaces="$1" +import sys -if [ ! "$n_spaces" ]; then - n_spaces=4 -fi +DEFAULT_N_SPACES = 4 +TAB, SPACE = ' ', ' ' -if [ $n_spaces -lt 1 ]; then - echo 'Sorry. Number of spaces should be a positive number' - exit 1 -fi +try: + n_spaces = int(sys.argv[1]) +except: + n_spaces = DEFAULT_N_SPACES -space='' -i=0 -while [ true ]; do - space="$space " - i=$(( $i + 1 )) - if [ $i -eq $n_spaces ]; then - break - fi -done +if n_spaces < 1: + n_spaces = DEFAULT_N_SPACES -while IFS='' read -r line || [[ -n "$line" ]]; do - if [[ ${line:0:1} != ' ' ]]; then - echo "$line" - continue - fi +for line in sys.stdin: + line = line.rstrip() + n_tabs = 0 - # Line length - line_len=${#line} + for ch in line: + if ch != TAB: + break + n_tabs += 1 - # Get leading tabs and their length - tabs=$(echo "$line" | sed -n 's/^\( *\)\(.*\)$/\1/p') - tabs_len=${#tabs} - - line_without_tabs_len=$(( $line_len - $tabs_len )) - line_without_tabs=${line:$tabs_len:$line_without_tabs_len} - - spaces=$(echo "$tabs" | sed "s/ /$space/g") - echo "$spaces$line_without_tabs" -done + spaces = SPACE * n_spaces * n_tabs + print(spaces, line[n_tabs:], sep='')