summaryrefslogtreecommitdiffstats
path: root/tldr
blob: 3cd229d0c05a1369f4619c4c055d0f9539cd114b (plain)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/bin/sh
# tldr client by Ray Lee, http://github.com/raylee/tldr
# tldr-sh-client version: 2021-12-18  spec: v1.5

# The following is written in a mildly functional style. It makes the code
# marginally slower, but more easily traceable, debuggable, and composable.
# And for me, at least, easier to reason about.

# In scripts "$@" often means 'all the arguments'. Below, it's also used
# for function indirection, executing the first parameter ($1) of $@ as a
# command, $2 onward as parameters, and wrapping it with other behaviors.

# Q: Why implement tldr in a plain POSIX shell script at all? It's nice to have
# a low-dependency way to see the pages, independent of local architecture. For
# some of us, POSIX sh is everywhere.

# silent executes its arguments as a command with args, silently.
silent() {
	>/dev/null 2>&1 "$@"
}

set -uf
# Some shells don't support setting pipefail, so try it silently and
# ignore any errors.
# silent set -o pipefail || true


main() {
	check_requirements

	# Set up the local platform as the default for pages.
	preferred_platform "$(local_platform)"

	# Some people like running this without saving any state.
	cache true
	if [ "${TLDR_CACHE:-}" = no ]; then
		cache false
		debug log Disabling cache
	fi

	Cmd=''
	bool listing
	while [ $# -gt 0 ]; do
		case $1 in
			-h|--help)
				usage > /dev/stderr
				exit 0
				;;
			-l|--list)
				listing true
				;;
			-L|--language)
				preferred_language "$2"
				shift
				;;
			-n|--no-cache)
				cache false
				;;
			-p|--platform)
				preferred_platform "$2"
				shift
				;;
			-u|--update)
				update_tldr_cache
				exit 0
				;;
			-v|--version)
				version_info
				exit 0
				;;
			-*)
				panic "Unrecognized option '$1'"
				;;
			*)
				# By the tldr client spec, the first argument
				# that does not start with a dash signals the
				# start of the command name. Spaces are
				# converted to dashes, and uppercase to lower.
				Cmd=$(printf %s "$*" | tr 'A-Z ' 'a-z-')
				break
				;;
		esac
		shift
	done

	# Download a copy of the pages locally if we don't have them already.
	if ! exists "$(page_cache)/index.json"; then
		update_tldr_cache
	fi

	if listing; then
		list_pages
		exit 0
	fi

	# # as an extension, this script can also parse arbitary md files.
	# if exists "$*"; then
	# 	display_tldr < "$*"
	# 	exit 0
	# fi

	if [ -z "$Cmd" ]; then
		# If stdin is a pipeline or a file, display it as a page.
		if ! interactive; then
			display_tldr "$(cat)"
		else
			usage > /dev/stderr
		fi
		exit 0
	fi

	tldr=$(get_page_md "$Cmd" 2>/dev/null)
	if [ -z "$tldr" ]; then
		panic "tldr page for command $Cmd not found"
	fi
	display_tldr "$tldr"
	echo

	# Freshen our local copy of the pages if they're out of date.
	if ! recent "$(page_cache)/index.json"; then
		update_tldr_cache
	fi
}


# panic exits the script with a final message to stderr.
panic() {
	>/dev/stderr printf "%s\n" "$@"
	exit 1
}

# installed tests the availability of command $1
installed() {
	silent command -v "$1"
}

# Check to see if we have the required external tools.
check_requirements() {
	# if sed is available we assume the smaller utils such as tr, cut,
	# sort, uniq, grep... are as well.
	installed sed    || panic 'tldr requires sed installed and available'
	installed unzip  || panic 'tldr requires unzip installed and available'
	installed curl   || installed wget || panic "tldr requires curl or wget installed and available"
}


# constants and read-only values

base_url() {
	echo https://raw.githubusercontent.com/tldr-pages/tldr/main/pages
}

upstream_pages() {
	echo https://raw.githubusercontent.com/tldr-pages/tldr-pages.github.io/main/assets/tldr.zip
}

# cache_dir returns the base path for caching tldr data files.
cache_dir() {
	if [ -n "${XDG_CACHE_HOME:-}" ]; then
		echo "${XDG_CACHE_HOME}/tldr"
		return
	fi

	if [ -n "${HOME:-}" ]; then
		if [ -d "$HOME/.cache" ]; then
			echo "$HOME/.cache/tldr"
		else
			echo "$HOME/.tldr"
		fi
		return
	fi

	echo "/tmp"
}


# page_cache returns the base path for tldr markdown pages.
page_cache() {
	# if [ -z "${page_cache_path:-}" ]; then
	# 	page_cache_path="$(cache_dir)/page-source"
	# fi
	# echo "$page_cache_path"
	echo "$(cache_dir)/page-source"
}

# cache_days is how long to wait before refreshing our local copy.
cache_days() {
	echo 14
}

version_info() {
	grep '^# tldr-sh-client version: ' "$0" | cut -c3-
	echo "Check https://github.com/raylee/tldr-sh-client for updates."
}

# exists tests whether a file exists.
exists() {
	silent test -e "$1"
}

# recent tests whether "$1" exists and is more recent than $(cache_days) old.
recent() {
	exists "$(find "$1" -mtime "-$(cache_days)" 2>/dev/null)"
}

# basename acts like the command of the same name.
basename() {
	fn=${1##*/}
	if [ $# -eq 2 ]; then
		fn=${fn%"$2"}
	fi
	printf "%s\n" "$fn"
}

# extension returns the portion of the filename after the last ., if any.
extension() {
	echo "${1##*.}"
}

# lang_cc returns the ${language}_${country_code} portion of a locale.
# example: lang_cc en_DK.utf8 => en_DK
lang_cc() {
	for arg; do
		echo "${arg%.*}"
	done
}

Get() {
	if installed curl; then
		curl -sfL "$1"
	else
		wget -O - "$1"
	fi
}


# Calling `cache true` enables the cache, any other parameter disables it.
# Calling `cache` with no parameters changes the success code to true or false.
cache() {
	case $# in
		0) [ "${cache_bool:-}" = true ] ;;
		1) cache_bool=$1 ;;
	esac
}

get_page_md() {
	if cache; then
		cat "$(page_path "$1")"
	else
		Get "$(base_url)/{$(local_platform),common}/$1.md"
	fi
}

# Update the local cached copy of the tldr source pages.
update_tldr_cache() {
	if cache; then
		mkdir -p "$(page_cache)"
		Get "$(upstream_pages)" > "$(cache_dir)/tldr.zip"
		silent unzip -o -d "$(page_cache)" -u "$(cache_dir)/tldr.zip"
	fi
}

# # list the languages used in the current tldr zip archive.
# tldr_languages() {
# 	for path in "$(page_cache)"/pages.*; do
# 		extension "$path"
# 	done
# }

# Call preferred_platform with no arguments to get the current value, or pass
# values to set.
preferred_platform() {
	case $# in
		0) echo "$preferred_platform_name" ;;
		*) preferred_platform_name="$*" ;;
	esac
}

# platform_order returns a list of search paths, with one (harmless) duplicate.
platform_order() {
	echo "$(preferred_platform)" common linux osx windows sunos android
}

# Call preferred_language with no arguments to get the current value, or pass
# values to set.
preferred_language() {
	case $# in
		0) echo "${preferred_language_code:-}" ;;
		*) preferred_language_code="$*" ;;
	esac
}

# i18n_paths returns the prioritized list of language page paths to search.
i18n_paths() {
	if [ -n "$(preferred_language)" ]; then
		echo pages."$(preferred_language)"
		# by the spec, if a preferred language is set, English is no
		# longer a fallback.
		return
	fi

	# if $LANG is unset or empty, English is the fallback.
	if [ -z "${LANG:-}" ]; then
		debug log i18n: LANGless
		echo pages
		return
	fi

	# else the languages are ordered by $LANGUAGE, then $LANG, then English.
	for i in $(split : "${LANGUAGE:-}") $LANG; do
		case $i in
			C|POSIX) continue ;;
		esac
		i=$(lang_cc "$i")
		echo "pages.$i"
		debug log i18n: pages."$i"
	done
	echo pages
}

# split separates the arguments based on a single split character in $1.
split() {
	IFS="$1"
	shift
	# shellcheck disable=2048
	for x in $*; do
		echo "$x"
	done
}

# page_path takes a (normalized) page name in $1, and localizes it for language
# and platform. Platform pages are given preference over languages per the tldr
# client spec. The path to the first page found in that order is returned.
page_path() {
	for p in $(platform_order); do
		for l in $(i18n_paths); do
			if exists "$(page_cache)/$l/$p/$1.md"; then
				echo "$(page_cache)/$l/$p/$1.md"
				return
			fi
		done
	done
}

# term emits termcodes for style names passed as arguments.
term() {
	for arg; do
		# shellcheck disable=2086
		case $arg in
			reset)        tput sgr0 || tput me ;;
			bold)         tput bold || tput md ;;
			underline)<