1#!/bin/ksh -p
2#
3# This file and its contents are supplied under the terms of the
4# Common Development and Distribution License ("CDDL"), version 1.0.
5# You may only use this file in accordance with the terms of version
6# 1.0 of the CDDL.
7#
8# A full copy of the text of the CDDL should have accompanied this
9# source. A copy of the CDDL is also available via the Internet at
10# http://www.illumos.org/license/CDDL.
11
12# Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
13
14SED=${SED:=/usr/bin/sed}
15
16function fatal {
17	echo "[FATAL] $*" > /dev/stderr
18	exit 1
19}
20
21function runtest {
22	typeset script="$1"
23	typeset expect="$2"
24	typeset files="${3:-$input1}"
25
26	typeset ef=`mktemp`
27	[[ -n "$expect" ]] && printf "%s\n" $expect > $ef
28
29	$SED -n "$script" $files > $output
30	if [[ $? -eq 0 ]] && cmp -s $output $ef; then
31		echo "[PASS] sed $script $files"
32	else
33		echo "[FAIL] sed $script $files"
34		diff -u $ef $output
35		err=1
36	fi
37	rm -f $ef
38}
39
40for f in input1 input2 output; do
41	tf=`mktemp`
42	[[ -n "$tf" && -f "$tf" ]] || fatal "Could not create temp file $f"
43	eval $f=$tf
44done
45
46typeset err=0
47
48printf "%s\n" a b c d e f g h a j > $input1
49[[ $? -eq 0 && -s "$input1" ]] || fatal "Could not populate input1 file"
50printf "%s\n" m n o p q z > $input2
51[[ $? -eq 0 && -s "$input2" ]] || fatal "Could not populate input2 file"
52
53# Simple
54runtest "3p" "c"
55runtest "\$p" "j"
56runtest "7,\$p" "g h a j"
57runtest "/d/p" "d"
58runtest "/a/p" "a a"
59
60# Ranges
61runtest "5,7p" "e f g"
62runtest "5,4p" "e"
63runtest "/a/,4p" "a b c d a"
64runtest "0,/b/p" ""
65runtest "4,/a/p" "d e f g h a"
66runtest "/d/,/g/p" "d e f g"
67
68# Relative ranges
69runtest "3,+0p" "c"
70runtest "3,+1p" "c d"
71runtest "5,+3p" "e f g h"
72runtest "6,+3p" "f g h a"
73runtest "7,+3p" "g h a j"
74runtest "8,+3p" "h a j"
75runtest "/a/,+1p" "a b a j"
76runtest "/a/,+8p" "a b c d e f g h a"
77runtest "/a/,+9p" "a b c d e f g h a j"
78
79# Negative
80runtest "4,7!p" "a b c h a j"
81runtest "6,+3!p" "a b c d e j"
82runtest "7,+3!p" "a b c d e f"
83runtest "8,+3!p" "a b c d e f g"
84
85# Branch
86runtest "4,7 { /e/b
87		p
88	}" "d f g"
89runtest "4,+3 { /e/b
90		p
91	}" "d f g"
92
93# stdin
94cat $input2 $input2 | runtest "\$p" "z" " "
95
96# Multi-file
97for fileset in \
98	"$input1 $input2" \
99	"$input1 /dev/null $input2" \
100	"/dev/null $input1 $input2" \
101	"$input1 $input2 /dev/null" \
102	"$input1 /dev/null $input2 /dev/null" \
103	"/dev/null $input1 /dev/null $input2" \
104	"$input1 $input2 /dev/null /dev/null" \
105	"$input1 /dev/null /dev/null $input2 /dev/null" \
106	"/dev/null $input1 /dev/null /dev/null $input2" \
107; do
108	runtest "\$p" "z" "$fileset"
109	runtest "3p" "c" "$fileset"
110	runtest "13p" "o" "$fileset"
111done
112
113rm -f $input1 $input2 $output
114
115[[ $err -eq 0 ]] && echo "--- All sed_addr tests passed"
116
117exit $err
118