Patch which respects "--color=auto"

On Fri, Oct 7, 2022 at 8:36 AM Knut Olav Bøhmer <[email protected]> wrote:
>
> On Thu, Oct 6, 2022 at 6:55 PM Knut Olav Bøhmer <[email protected]> wrote:
> >
> > On Thu, Oct 6, 2022 at 5:44 PM Tobias Girstmair <[email protected]> wrote:
> > >
> > > On Thu, Oct 06, 2022 at 04:44:58PM +0200, Knut Olav Břhmer wrote:
> > > >Hi,
> > > >
> > > >I would like to enable output without color.
> > > >I also have on the wish list to print passfile_dir with a leading slash.
> > >
> > > i'm assuming you need this for passing pass' output to another program.
> > >
> > > how about using something like the code below. 'test -t' checks whether
> > > a file descriptor is a tty. this would keep interactive output the same,
> > > while automatically making pipelines work.
> > >
> > > if [[ -t 1 ]]
> > > then
> > >         color=always
> > > else
> > >         color=never
> > > fi
> > >
> > > # ...
> > >
> > > grepresults=$(... | grep --color="$color" ...)
> > >
> > >
> > > if that's too verbose for you:
> > >
> > > color=never
> > > test -t 1 && color=always
> >
> > consider this
> >
> > pass grep .| less -R
> >
> > Sometimes want colored output even if the output is a pipe. But I
> > would still consider your idea an improvement.
>
> test -t should be used if --color=auto
>
> --
> Knut Olav Bøhmer
> 41 000 108



-- 
Knut Olav Bøhmer
41 000 108
From 11029cff498b16008d19df35003bb982a8c520fb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Knut=20Olav=20B=C3=B8hmer?= <[email protected]>
Date: Thu, 6 Oct 2022 16:30:15 +0200
Subject: [PATCH] Make cmd_grep understand --color

---
 src/password-store.sh | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/password-store.sh b/src/password-store.sh
index 22e818f..22c5695 100755
--- a/src/password-store.sh
+++ b/src/password-store.sh
@@ -419,16 +419,25 @@ cmd_find() {
 
 cmd_grep() {
 	[[ $# -lt 1 ]] && die "Usage: $PROGRAM $COMMAND [GREPOPTIONS] search-string"
-	local passfile grepresults
+	[[ "$@" =~ --color=(.*)[[:space:]] ]]
+	local passfile grepresults color=${BASH_REMATCH[1]:-always} formatstring
+
+	if [[ $color == never  || ( $color == auto && ! -t 1 ) ]]
+	then
+		formatstring="%s%s:\n"
+	else
+		formatstring="\e[94m%s\e[1m%s\e[0m:\n"
+	fi
+
 	while read -r -d "" passfile; do
-		grepresults="$($GPG -d "${GPG_OPTS[@]}" "$passfile" | grep --color=always "$@")"
+		grepresults="$($GPG -d "${GPG_OPTS[@]}" "$passfile" | grep --color=${color} "$@")"
 		[[ $? -ne 0 ]] && continue
 		passfile="${passfile%.gpg}"
 		passfile="${passfile#$PREFIX/}"
 		local passfile_dir="${passfile%/*}/"
 		[[ $passfile_dir == "${passfile}/" ]] && passfile_dir=""
 		passfile="${passfile##*/}"
-		printf "\e[94m%s\e[1m%s\e[0m:\n" "$passfile_dir" "$passfile"
+		printf $formatstring "$passfile_dir" "$passfile"
 		echo "$grepresults"
 	done < <(find -L "$PREFIX" -path '*/.git' -prune -o -path '*/.extensions' -prune -o -iname '*.gpg' -print0)
 }
-- 
2.37.3

Reply via email to