From: Amadeusz Żołnowski <aide...@gentoo.org>

awk doesn't have the -i option like sed and if editing file in place is
desired, additional steps are required. eawk uses tmp file to make it
look to the caller editing happens in place.

New version of gawk (not stabilized yet) does support editing in place
but forcing user to install specific awk implementation is not desired.
---
 eclass/eutils.eclass        | 16 +++++++++++
 eclass/tests/eutils_eawk.sh | 65 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 81 insertions(+)
 create mode 100755 eclass/tests/eutils_eawk.sh

diff --git a/eclass/eutils.eclass b/eclass/eutils.eclass
index dbedffe..963a692 100644
--- a/eclass/eutils.eclass
+++ b/eclass/eutils.eclass
@@ -20,6 +20,22 @@ _EUTILS_ECLASS=1
 
 inherit multilib toolchain-funcs
 
+# @FUNCTION: eawk
+# @USAGE: <file> <args>
+# @DESCRIPTION:
+# Edit file <file> in place with awk. Pass all arguments following <file> to
+# awk.
+eawk() {
+       local f="$1"; shift
+       local tmpf="$(emktemp)"
+
+       awk "$@" "${f}" >"${tmpf}" || die -n 'awk failed' || return
+       # Following commands should always succeed unless something weird is 
going
+       # on.
+       cat "${tmpf}" >"${f}" || die 'failed to replace source file' || return
+       rm "${tmpf}" || die "failed to remove temporary file"
+}
+
 # @FUNCTION: eqawarn
 # @USAGE: [message]
 # @DESCRIPTION:
diff --git a/eclass/tests/eutils_eawk.sh b/eclass/tests/eutils_eawk.sh
new file mode 100755
index 0000000..b06f377
--- /dev/null
+++ b/eclass/tests/eutils_eawk.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# Copyright 1999-2016 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+# $Id$
+
+source tests-common.sh
+
+inherit eutils
+
+# Mock die so it doesn't break tests.
+die() {
+       echo "die: $*" 1>&2
+       return 1
+}
+
+tbegin "preserves permissions"
+
+cd "$(emktemp -d)"
+
+cat <<EOF >'test.txt'
+testme1
+testme2
+testme3
+EOF
+
+cat <<EOF >'test_expected.txt'
+testme1
+foo
+testme3
+EOF
+
+chmod 704 'test.txt'
+eumask_push 000
+eawk 'test.txt' '/^testme2$/ {print "foo"; next;} 1'
+eumask_pop
+
+diff 'test.txt' 'test_expected.txt'
+expected=$?
+
+[[ $(stat -c '%a' 'test.txt') = 704 ]]
+perms=$?
+
+[[ ${expected}${perms} = 00 ]]
+
+tend $?
+
+
+tbegin "doesn't alter file on failure"
+
+cd "$(emktemp -d)"
+
+cat <<EOF >'test.txt'
+testme1
+testme2
+testme3
+EOF
+
+cat 'test.txt' >'test_expected.txt'
+
+eawk 'test.txt' '/^testme2$/ print "foo"; next;} 1' 2>/dev/null
+diff 'test.txt' 'test_expected.txt'
+
+tend $?
+
+texit
-- 
2.8.2


Reply via email to