]> ruderich.org/simon Gitweb - config/dotfiles.git/commitdiff
lib.sh: Add simple_cpp() to replace "defines".
authorSimon Ruderich <simon@ruderich.org>
Tue, 22 Oct 2013 20:50:15 +0000 (22:50 +0200)
committerSimon Ruderich <simon@ruderich.org>
Tue, 22 Oct 2013 20:50:15 +0000 (22:50 +0200)
Also add perl_line_filter() which is used by simple_cpp().

lib.sh

diff --git a/lib.sh b/lib.sh
index 72040244499bd585ebfbbd6a2edac57048331ddc..7bb1d5c9ea9851a6e55e032dd9e5509cdc86fd26 100644 (file)
--- a/lib.sh
+++ b/lib.sh
@@ -73,6 +73,37 @@ sed_i() {
     cmd_i sed "$@"
 }
 
+# Usage: perl_line_filter <cmd> ...
+#
+# Run the perl command cmd on each line before printing it.
+perl_line_filter() {
+    cmd="$1"
+    shift
+
+    # Can't use -pe because it uses <> which treats the arguments as files.
+    perl -e "use strict; use warnings; while (<STDIN>) { $cmd; print; }" "$@"
+}
+
+# Usage: simple_cpp <FIRST> <SECOND> .. -- <replacement-for-first> ...
+#
+# Replaces each FIRST (on word boundaries) with <replacement-for-first> like a
+# simple cpp replacement.
+simple_cpp() {
+    cmd='my $i = 0;'
+
+    for x; do
+        shift
+
+        if test x"$x" = x--; then
+            break
+        fi
+
+        cmd="$cmd s/\b$x\b/\$ARGV[\$i]/g; \$i++;"
+    done
+
+    perl_line_filter "$cmd" -- "$@"
+}
+
 # Print the current OS. The following OS are supported at the moment:
 # - Debian (debian)
 # - Gentoo (gentoo)