[hackers] [farbfeld] Refactor 2ff(1) || Laslo Hunhold

From: <git_AT_suckless.org>
Date: Fri, 14 Apr 2017 17:36:53 +0200 (CEST)

commit 42678350147b13345174f1e4c637a89c442ffd3c
Author: Laslo Hunhold <dev_AT_frign.de>
AuthorDate: Fri Apr 14 17:32:12 2017 +0200
Commit: Laslo Hunhold <dev_AT_frign.de>
CommitDate: Fri Apr 14 17:36:49 2017 +0200

    Refactor 2ff(1)
    
    The Unix philosophy teaches us that tools should strive to output only
    necessary diagnostic information and also reflect errors properly with
    the return value.
    There were three subtle problems with 2ff:
    
       1) If the farbfeld-passthrough failed, it would return 1 instead
          of 1.
       2) If the first 8 bytes contained a NUL byte, bash would print
          an ugly warning message. Passing it through tr -d '\0' fixes
          that.
       3) Lack of comments. I added some to make the structure even
          clearer, also including using an if-else-structure.
    
    I removed the 2ff error message; the tools themselves print proper
    messages already.

diff --git a/2ff b/2ff
index bf58e5b..ef6f02d 100755
--- a/2ff
+++ b/2ff
_AT_@ -1,36 +1,38 @@
 #!/bin/sh
+
+# arguments
 if [ "$#" -ne 0 ]; then
         echo "usage: $0" >&2
         exit 1
 fi
 
+# write input into temporary file
 TMP=$(mktemp)
 trap 'rm "$TMP"' EXIT
-
 cat > "$TMP"
 
-if [ "$(dd if="$TMP" bs=1 count=8 2>/dev/null)" = "farbfeld" ]; then
+# determine the mime-type
+if [ "$(dd if="$TMP" bs=1 count=8 2>/dev/null | tr -d '\0')" = "farbfeld" ]; then
         cat "$TMP"
- exit 0
-fi
+else
+ MIME=$(file -ib "$TMP" | cut -d ";" -f 1)
 
-FORMAT=$(file -ib "$TMP" | cut -d ";" -f 1)
-
-case "$FORMAT" in
-image/png)
- png2ff < "$TMP"
- ;;
-image/jpeg)
- jpg2ff < "$TMP"
- ;;
-*)
- convert "$TMP" png:- 2>/dev/null | png2ff 2>/dev/null
- ;;
-esac
+ case "$MIME" in
+ image/png)
+ png2ff < "$TMP"
+ ;;
+ image/jpeg)
+ jpg2ff < "$TMP"
+ ;;
+ *)
+ convert "$TMP" png:- 2>/dev/null | png2ff 2>/dev/null
+ ;;
+ esac
+fi
 
+# errors
 if [ $? -ne 0 ]; then
- printf "%s: failed to convert from %s\n" "$0" "$FORMAT" >&2
         exit 1
+else
+ exit 0
 fi
-
-exit 0
Received on Fri Apr 14 2017 - 17:36:53 CEST

This archive was generated by hypermail 2.3.0 : Fri Apr 14 2017 - 17:48:20 CEST