-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhd
More file actions
executable file
·303 lines (273 loc) · 10.7 KB
/
hd
File metadata and controls
executable file
·303 lines (273 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/bin/sh
# Enhanced hex dump wrapper for `hd`
# This requires the `hexdump` command-line utility.
# Install in a higher priority part within your $PATH than other `hd` command(s)
# Expand folds in vim with z then R in normal mode (or use a simpler editor)
# Helper functions {{{
help() { cat <</help
Enhanced hex dump wrapper (colors and wide options)
Usage: ${0##*/} [OPTIONS] [FILE...]
OPTIONS
-1, --narrow Half-width display: only one 8-byte column (8B/line)
-2, --width=4 Double-width display: four 8-byte columns, 32B/line
-C, --canonical Display two 8-byte columns with hexdump's built-in logic
--color[=WHEN] Use colors to denote different character classes
WHEN may be: always, auto (default), map (help), or never
--exec=PATH Path to the \`hexdump\` (or \`hd\`) executable
-F, --final-count Add a final count line like canonical hd (--canonical)
--help-colors Display a mapping of what colors means what (--color=map)
-n LENGTH Interpret only only LENGTH bytes of input
-U, --no-unicode Disable inserting Unicode stand-ins for non-printing chars
-v, --no-squeezing Display all input data (do not compress with asterisks)
-w, --wide Display as many 8-byte columns as fit on the terminal
-W, --width=NUM Display NUM 8-byte columns (default=2, showing 16B/line)
/help
version
}
version() {
v="$("$hexdump" --version 2>&1)"
if [ $? != 0 ]; then
v="hexdump from $(echo "$v" |grep -m1 '[0-9]\.[0-9]' || echo "$hexdump")"
elif [ -z "$v" ]; then
v="$(man hexdump 2>/dev/null |awk '
END { sub(/ .*/, ""); if (NR) print "hexdump from", $0 }')"
fi
if [ -n "$v" ]; then
echo "$v"
fi
echo "Part of misc-scripts: https://github/adamhotep/misc-scripts"
echo "hd-wrapper 2.1.20250528.0 Copyright 2005+ by Adam Katz," \
"GPLv3+ / BSD 2-clause"
exit
}
changelog() { cat <</changelog
Change log:
1.0.3.20230102 First git commit, changes unknown (iirc, color support)
2.0.20240721.0 Better option parsing, Unicode, new color map, spacing bugfix
2.0.20250518.0 Support for mawk 1.3.4.20241212+ and busybox
2.1.20250528.0 Auto/arbitrary width (changes -w/--wide & -1/--narrow, adds -W)
Complete chagelog: https://github.com/adamhotep/misc-scripts/commits/main/hd
/changelog
exit
}
color_map() {
x= null_disclaimer= iso_8859_1=
if [ "$unicode" != 1 ]; then
null_disclaimer=" (rendered as ${red}0$off)"
else
iso_8859_1=" (rendered in UTF-8 as if ISO-8859-1)"
fi
cat <</COLORS
${0##*/} wrapper color mapping:
${red}Inverted Red$off Null character$null_disclaimer
${x# }Plain${x} ASCII letter
${yel}Yellow$off ASCII number
${cyn}Cyan$off Space, printable ASCII non-alphanumeric character
${inv}Inverted$off Other ASCII & Extended ASCII (controls, other spaces)
${blu}Blue$off Any other unicode character$iso_8859_1
/COLORS
exit
}
die() {
printf '%s\n' "$@" >&2
[ $# -lt 2 ] && echo "Try ${0##*/} --help" >&2
exit 2
}
needs_arg() { if [ -z "$OPTARG" ]; then die "No arg for --$OPT option"; fi; }
save_opt() { argv="$argv${argv:+$sep}-$long$OPT$OPTARG"; }
### end of helper functions }}}
# Color filter {{{
_colorhd() {
if [ -z "$CLICOLOR_FORCE" ] || [ -n "$unsupported" ]; then # no color/support
grep ^
return $?
fi
awk -v red="$red" -v yel="$yel" -v blu="$blu" -v prp="$prp" -v cyn="$cyn" \
-v inv="$inv" -v off="$off" -v unicode=$unicode '
BEGIN { for(i = 0; i < 256; i++) hex2int[sprintf("%02x", i)] = i }
# update blockarr[] with string str, shade ss, and at position ii
function swap(str, ss, ii) {
if (!ii) ii = i # ii uses i when unspecified
if (ss) shade = ss # SETS shade when ss *is* specified
if (!str) str = blockarr[ii] # default str to the current value
blockarr[ii] = off
if (shade != off) blockarr[ii] = blockarr[ii] shade
blockarr[ii] = blockarr[ii] str cyn
}
length($2) == 2 {
block = match($0, /\|.*\|$/)
if (block) {
count = length($1)
codes = substr($0, count + 1, block - count - 1)
# busybox awk lacks "%*s" support, so we concatenate the length inside
space = sprintf("%" 1 + length(codes) - match(codes, / +$/) "s", "")
count = substr($0, 1, count)
blocklen = split(substr($0, block), blockarr, "")
swap("", prp, blocklen) # color the last character of the block
hex = " "
i = 1
for (char = 3; $(++i) ~ /^[0-9a-fA-F][0-9a-fA-F]$/; char+=3) {
if (i > 2 && i % 8 == 2) { hex = hex " "; char++ } # space every 8
c = substr(codes, char, 2) # target value
if (c == " ") { hex = hex " "; continue } # no value
c = hex2int[substr(codes, char, 2)] / 1 # numeric (decimal) code
if (c == 0) { # null is inverted red
if (unicode) swap("\xe2\x90\x80", red)
else swap("0", red)
}
else if (c < 32 || 126 < c && c < 160) { # controls: invert
shade = inv
if (unicode) {
if (c < 32) swap(sprintf("\xe2\x90%c", c + 128)) # C0 code
else if (c == 0x7f) swap("\xe2\x90\xa1") # delete
else swap(".")
}
else swap(".")
} else if (c > 47 && c < 58) { # numbers are yellow
swap("", yel)
} else if (c > 64 && c < 91 || c > 96 && c < 123) { # white letters
swap("", off)
} else if (c == 160) { # no-break space
if (unicode) swap("\xe2\x8d\xbd", blu) # shouldered open box
else swap(" ") # regular space
} else if (c > 160) { # higher unicode is blue
shade = blu
if (unicode && c < 192) swap(sprintf("\xc2%c", c))
else if (unicode) swap(sprintf("\xc3%c", c - 64))
else swap(".")
} else {
swap("", cyn) # space/punctuation: cyan
}
if (shade) { hex = sprintf("%s %s%02x%s", hex, shade, c, off) }
else { hex = sprintf("%s %02x", hex, c) }
}
if (full == 0) full = char
block = ""
for (i = 1; i <= blocklen; i++) block = block blockarr[i]
print prp count off hex space prp block off
next
}
}
{ x=""; if (! sub(/ /, off "&")) x = off; print prp $0 x; next }
END { exit ! (full > 0) }
'
}
### end of color filter _colorhd() }}}
# Parse options {{{
# Unique separator: start of heading (\x01), <, PID, >, start of text (\x02)
# This allows us to preserve spacing from option arguments later
sep="<$$>" # THIS LINE CONTAINS ESCAPE CHARACTERS. sep="\x01<$$>\x02"
argv= canonical= final_count= help= hexdump=hexdump map= unicode=1 unsupported=
version= width=2
# Load default colors from the environment
if [ -n "$NO_COLOR" ]; then
color=never
elif [ -n "$CLICOLOR_FORCE" ]; then
color=always
else # default to auto as if $CLICOLOR is on (you're here for color, right?)
color=auto
fi
while getopts 12bcCde:f:FhLn:s:oUvVwW:x-: OPT; do
long=
if [ "$OPT" = - ]; then # --long, https://stackoverflow.com/a/28466267/519360
OPT="${OPTARG%%=*}" OPTARG="${OPTARG#"$OPT"}" OPTARG="${OPTARG#=}" long="-"
fi
case "$OPT" in
( [bcdoxX] | one-by* | two-by* ) unsupported=1; save_opt ;;
( 1 | narrow ) width=1 ;; # half-width: 8 bytes in 1 column
( 2 ) width=4 ;; # double-width: 32 bytes in 4 columns
( C | canonical ) canonical=1 width=2; save_opt ;;
( change* ) changelog ;;
( [ef] | format* ) unsupported=1; needs_arg; save_opt ;;
( exec* ) needs_arg; hexdump="$OPTARG" ;;
( F | final-count ) final_count='-e "%08.8_Ax\n"' ;;
( help*colo*r* ) map=1 ;;
( h | help* ) help=1 ;;
( L | color ) color="${OPTARG:-always}" ;;
( n | length ) needs_arg; save_opt ;;
( s | skip ) needs_arg; save_opt ;;
( U | no-unicode ) unicode=0 ;;
( V | version ) version=1 ;;
( [wW] | wid[et]* ) width="${OPTARG:-auto}" ;;
( \?* ) die ;;
( ??* ) die "Illegal option $OPT" ;;
( * ) save_opt ;; # some options are just pass-throughs
esac
done
shift $((OPTIND-1))
if [ "${hexdump##*/}" = busybox ]; then
busybox="$hexdump"
else
busybox=busybox
fi
if ! command -v "$hexdump" >/dev/null || [ "$busybox" != busybox ]; then
if [ "$hexdump" != hexdump ] && [ "$busybox" = busybox ]; then
die "Could not run hexdump executable at \`$hexdump\`"
elif command -v busybox >/dev/null && busybox --list |grep -qFx hexdump; then
busybox_hexdump() {
if [ "$1" = --version ]; then
"$busybox" |awk '{ print "hexdump from", $0; exit }'
else
"$busybox" hexdump "$@";
fi
}
hexdump=busybox_hexdump
else
die "ERROR, hexdump is not a command (try --exec=PATH as noted in --help)" \
"To install hexdump, look for a package like bsdmaintools or busybox)"
fi
fi
# these were deferred so we could say which hexdump version we're using
if [ "$help" = 1 ]; then
help
elif [ "$version" = 1 ]; then
version
fi
poe='" " 8/1 "%02x "' # pieces of eight
if [ -z "$unsupported$canonical" ]; then
# --width: wider hd, https://stackoverflow.com/a/58600201/519360
if [ "$width" = auto ]; then # yeah, this allows for NARROWER views too
if ! [ "$COLUMNS" -ge 45 ] 2>/dev/null; then
COLUMNS="$(tput cols)" || die "Couldn't detect your view's width"
if ! [ "$COLUMNS" -ge 45 ] 2>/dev/null; then
die "Your terminal must be 45+ columns wide to automatically set it." \
"Try --width=NUM instead. Learn more with --help"
fi
fi
width=$(( (COLUMNS - 12) / 33 )) # 12 = 8 @counter + 2 spaces + 2 pipes
: $width
elif ! [ "$width" -gt 0 ] 2>/dev/null; then
die "Width \`$width\` is not supported. Try \`auto\` or an integer > 0"
fi
i=0 codes=
while [ $((i+=1)) -le $width ]; do
codes="$codes${codes:+ }$poe"
done
set -- $final_count -e '"%08.8_ax" '"$codes" \
-e '" |" '$((width*8))'/1 "%_p" "|\n"' "$@"
fi
# Split $argv and compose final $@ with preseved spacing
while [ -n "$argv" ]; do
set -- "${argv##*$sep}" "$@"
if [ "$argv" = "${argv##*$sep}" ]; then break; fi
argv="${argv%$sep*}"
done
case $color in
( always | auto | never ) : "color '$color' is valid" ;;
( map | help ) color=auto map=1 ;;
( yes | 1 ) color=always ;;
( no | 0 ) color=never ;;
( tty | TTY | default ) color=auto ;;
( * ) die "Invalid color '$color'" ;;
esac
if [ "$color" = always ] || [ "$color" = auto -a -t 1 ]; then
# THE FOLLOWING 2 LINES HAVE AN ESCAPE CHARACTER (\x1b) BEFORE EACH SQ BRACKET
export CLICOLOR_FORCE=1 CLICOLOR=1 red="[47;31m" yel="[0;33m"
export blu="[0;34m" prp="[0;35m" cyn="[0;36m" inv="[7m" off="[m"
unset NO_COLOR
else
export NO_COLOR=1 CLICOLOR_FORCE= CLICOLOR=
fi
if [ -n "$map" ]; then color_map; fi
### end of option parsing }}}
"$hexdump" "$@" |_colorhd