-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmulle-path.sh
827 lines (679 loc) · 15.5 KB
/
mulle-path.sh
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# shellcheck shell=bash
# shellcheck disable=SC2236
# shellcheck disable=SC2166
# shellcheck disable=SC2006
#
# Copyright (c) 2015 Nat! - Mulle kybernetiK
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of Mulle kybernetiK nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
if ! [ ${MULLE_PATH_SH+x} ]
then
MULLE_PATH_SH='included'
[ -z "${MULLE_STRING_SH}" ] && _fatal "mulle-string.sh must be included before mulle-path.sh"
# RESET
# NOCOLOR
#
# Assortment of various string functions that deal with filepaths.
# None of these functions actually touch the filesystem.
#
# Functions prefixed "r_" return the result in the global variable RVAL.
# The return value 0 indicates success.
#
# TITLE INTRO
# COLOR
#
# r_filepath_cleaned <filepath>
#
# r_filepath_cleaned makes somewhat prettier filenames, removing
# superfluous "." and trailing '/'. It's fairly cheap though.
# DO NOT USE ON URLs
#
function r_filepath_cleaned()
{
RVAL="$1"
[ -z "${RVAL}" ] && return
local old
old=''
# remove excess //, also inside components
# remove excess /./, also inside components
while [ "${RVAL}" != "${old}" ]
do
old="${RVAL}"
RVAL="${RVAL//\/.\///}"
RVAL="${RVAL//\/\///}"
done
if [ -z "${RVAL}" ]
then
RVAL="${1:0:1}"
fi
}
#
# r_filepath_concat <component> ...
#
# r_filepath_concat concatenates filepaths components to produce a single
# filepath.
# .e.g. "foo" "bar" -> foo/bar
# "/" "/foo" "." "bar" -> /foo/bar
#
r_filepath_concat()
{
local i
local s
local sep
local fallback
s=""
fallback=""
for i in "$@"
do
sep="/"
r_filepath_cleaned "${i}"
i="${RVAL}"
case "$i" in
"")
continue
;;
"."|"./")
if [ -z "${fallback}" ]
then
fallback="./"
fi
continue
;;
esac
case "$i" in
"/"|"/.")
if [ -z "${fallback}" ]
then
fallback="/"
fi
continue
;;
esac
if [ -z "${s}" ]
then
s="${fallback}$i"
else
case "${i}" in
/*)
s="${s}${i}"
;;
*)
s="${s}/${i}"
;;
esac
fi
done
if [ ! -z "${s}" ]
then
r_filepath_cleaned "${s}"
else
RVAL="${fallback:0:1}" # / make ./ . again
fi
}
# ####################################################################
# Path handling
# ####################################################################
#
# r_basename <filename>
#
# In functionality identical to "basename", but much faster than calling
# the external commands
#
#
# /tmp/foo.sh -> foo.sh
#
function r_basename()
{
local filename="$1"
while :
do
case "${filename}" in
/)
RVAL="/"
return
;;
*/)
filename="${filename%?}"
;;
*)
RVAL="${filename##*/}"
return
;;
esac
done
}
#
# r_dirname <filename>
#
# In functionality identical to "dirname", but much faster than calling
# the external commands
#
# /tmp/foo.sh -> /tmp
#
function r_dirname()
{
local filename="$1"
local last
while :
do
case "${filename}" in
/)
RVAL="${filename}"
return
;;
*/)
filename="${filename%?}"
continue
;;
esac
break
done
# need to escape filename here as it may contain wildcards
printf -v last '%q' "${filename##*/}"
RVAL="${filename%${last}}"
while :
do
case "${RVAL}" in
/)
return
;;
*/)
RVAL="${RVAL%?}"
;;
*)
RVAL="${RVAL:-.}"
return
;;
esac
done
}
#
# r_path_depth <filepath>
#
# Computes the depth of <filepath>
# Return values are
# 0 = ""
# 1 = /
# 2 = /tmp
# 3 = /tmp/bar
# 3 = /tmp/bar/
# 4 = /tmp/bar/foo
# ...
#
function r_path_depth()
{
local name="$1"
local depth
depth=0
if [ ! -z "${name}" ]
then
depth=1
while [ "$name" != "." -a "${name}" != '/' ]
do
r_dirname "${name}"
name="${RVAL}"
depth=$((depth + 1))
done
fi
RVAL="${depth}"
}
#
# r_extensionless_basename <s>
#
# Extracts filename from <s> and cut off the last extension only
#
# /tmp/foo.sh.xxx -> foo.sh
#
function r_extensionless_basename()
{
r_basename "$@"
RVAL="${RVAL%.*}"
}
#
# r_extensionless_filename <s>
#
# Cut off the last extension from <s>
#
# /tmp/foo.sh.xx -> /tmp/foo.sh
#
function r_extensionless_filename()
{
RVAL="${1%.*}"
}
#
# r_path_extension <s>
#
# Retrieve the last extension from <s>
#
# /tmp/foo.sh.xx -> "xx"
#
function r_path_extension()
{
r_basename "$@"
case "${RVAL}" in
*.*)
RVAL="${RVAL##*.}"
return
;;
esac
RVAL=""
}
# ----
# stolen from: https://stackoverflow.com/questions/2564634/convert-absolute-path-into-relative-path-given-a-current-directory-using-bash
# because the python dependency irked me.
#
# There must be no ".." or "." in the paths.
#
__r_relative_path_between()
{
RVAL=''
[ $# -ge 1 ] && [ $# -le 2 ] || return 1
current="${2:+"$1"}"
target="${2:-"$1"}"
[ "$target" != . ] || target=/
target="/${target##/}"
[ "$current" != . ] || current=/
current="${current:="/"}"
current="/${current##/}"
appendix="${target##/}"
relative=''
while appendix="${target#"$current"/}"
[ "$current" != '/' ] && [ "$appendix" = "$target" ]; do
if [ "$current" = "$appendix" ]; then
relative="${relative:-.}"
RVAL="${relative#/}"
return 0
fi
current="${current%/*}"
relative="$relative${relative:+/}.."
done
RVAL="$relative${relative:+${appendix:+/}}${appendix#/}"
}
_r_relative_path_between()
{
local a
local b
if [ "${MULLE_TRACE_PATHS_FLIP_X:-}" = 'YES' ]
then
set +x
fi
# remove relative components and './' it upsets the code
r_simplified_path "$1"
a="${RVAL}"
r_simplified_path "$2"
b="${RVAL}"
# a="`printf "%s\n" "$1" | sed -e 's|/$||g'`"
# b="`printf "%s\n" "$2" | sed -e 's|/$||g'`"
[ -z "${a}" ] && _internal_fail "Empty path (\$1)"
[ -z "${b}" ] && _internal_fail "Empty path (\$2)"
__r_relative_path_between "${b}" "${a}" # flip args (historic)
if [ "${MULLE_TRACE_PATHS_FLIP_X:-}" = 'YES' ]
then
set -x
fi
}
#
# r_relative_path_between <to> <from>
#
# <to> is the directory/file, that we want to access relative from root
# <from> is the directory we want to access <to> from. To belabor this
# <from> can not be a file.
#
# The routine can not deal with ../ and ./, but is a bit faster than
# symlink_relpath.
#
# ex. /usr/include /usr, -> include
# ex. /usr/include / -> /usr/include
#
#
function r_relative_path_between()
{
local a="$1"
local b="$2"
# the function can't do mixed paths
case "${a}" in
"")
_internal_fail "First path is empty"
;;
../*|*/..|*/../*|..)
_internal_fail "Path \"${a}\" mustn't contain .."
;;
./*|*/.|*/./*|.)
_internal_fail "Filename \"${a}\" mustn't contain component \".\""
;;
/*)
case "${b}" in
"")
_internal_fail "Second path is empty"
;;
../*|*/..|*/../*|..)
_internal_fail "Filename \"${b}\" mustn't contain \"..\""
;;
./*|*/.|*/./*|.)
_internal_fail "Filename \"${b}\" mustn't contain \".\""
;;
/*)
;;
*)
_internal_fail "Mixing absolute filename \"${a}\" and relative filename \"${b}\""
;;
esac
;;
*)
case "${b}" in
"")
_internal_fail "Second path is empty"
;;
../*|*/..|*/../*|..)
_internal_fail "Filename \"${b}\" mustn't contain component \"..\"/"
;;
./*|*/.|*/./*|.)
_internal_fail "Filename \"${b}\" mustn't contain component \".\""
;;
/*)
_internal_fail "Mixing relative filename \"${a}\" and absolute filename \"${b}\""
;;
*)
;;
esac
;;
esac
_r_relative_path_between "${a}" "${b}"
}
#
# r_compute_relative <s>
#
# Compute number of ".." needed to return from <path> to root. Returns
# this as a string.
# e.g. cd "a/b/c" -> cd ../../..
#
function r_compute_relative()
{
local name="${1:-}"
local relative
local depth
r_path_depth "${name}"
depth="${RVAL}"
if [ "${depth}" -gt 1 ]
then
relative=".."
while [ "$depth" -gt 2 ]
do
relative="${relative}/.."
depth=$((depth - 1))
done
fi
# if [ -z "$relative" ]
# then
# relative="."
# fi
RVAL="${relative}"
}
#
# is_absolutepath <filepath>
#
# Returns 0 if <filepath> is an absolute path.
# e.g. "/foo" -> 0 "./x" -> 1
#
function is_absolutepath()
{
case "${1}" in
/*|~*)
return 0
;;
*)
return 1
;;
esac
}
#
# is_relativepath <filepath>
#
# Returns 0 if <filepath> is a relative path.
# e.g. "/foo" -> 1 "./x" -> 0
#
function is_relativepath()
{
case "${1}" in
""|/*|~*)
return 1
;;
*)
return 0
;;
esac
}
#
# r_absolutepath <filepath> [pwd]
#
# Creates an absolute filepath from <filepath> The current directory may
# be passed as [pwd]. Otherwise the contents of PWD is used. If <filepath>
# is already absolute, no changes happen.
#
# e.g. "/foo" -> 1 "./x" -> 0
#
function r_absolutepath()
{
local directory="$1"
local working="${2:-${PWD}}"
case "${directory}" in
"")
RVAL=''
;;
/*|~*)
RVAL="${directory}"
;;
*)
RVAL="${working}/${directory}"
;;
esac
}
#
# r_simplified_absolutepath <directory> [pwd]
#
# Like r_absolutepath but the resultant path is then simplified with
# r_simplified_path.
#
function r_simplified_absolutepath()
{
local directory="$1"
local working="${2:-${PWD}}"
case "${1}" in
"")
RVAL=''
;;
/*|~*)
r_simplified_path "${directory}"
;;
*)
r_simplified_path "${working}/${directory}"
;;
esac
}
#
# r_symlink_relpath <file> <directory>
#
# Imagine you are in a working <directory>
# This function gives the relative path you need to create a symlink
# that points to <file>.
#
function r_symlink_relpath()
{
local a
local b
# _relative_path_between will simplify
r_absolutepath "$1"
a="$RVAL"
r_absolutepath "$2"
b="$RVAL"
_r_relative_path_between "${a}" "${b}"
}
#
# _r_simplified_path() works on paths that may or may not exist
# it makes prettier relative or absolute paths
# you can't have | in your path though
#
_r_simplified_path()
{
local filepath="$1"
[ -z "${filepath}" ] && fail "empty path given"
local i
local last
local result
local remove_empty
result=""
last=""
remove_empty='NO' # remove trailing slashes
.foreachpathcomponent i in ${filepath}
.do
case "$i" in
\.)
remove_empty='YES'
.continue
;;
\.\.)
# remove /..
remove_empty='YES'
if [ "${last}" = "|" ]
then
.continue
fi
if [ ! -z "${last}" -a "${last}" != ".." ]
then
r_remove_last_line "${result}"
result="${RVAL}"
r_get_last_line "${result}"
last="${RVAL}"
.continue
fi
;;
~*)
fail "Can't deal with ~ filepaths"
;;
"")
if [ "${remove_empty}" = 'NO' ]
then
last='|'
result='|'
fi
.continue
;;
esac
remove_empty='YES'
last="${i}"
r_add_line "${result}" "${i}"
result="${RVAL}"
.done
if [ -z "${result}" ]
then
RVAL="."
return
fi
if [ "${result}" = '|' ]
then
RVAL="/"
return
fi
RVAL="${result//\|/}"
RVAL="${RVAL//$'\n'//}"
RVAL="${RVAL%/}"
}
#
# r_simplified_path <filepath>
#
# r_simplified_path makes prettier relative or absolute paths.
# This function works also on filepaths that do not exist.
# r_simplified_path performs better, if there are no relative components.
# Caveat: you can't have | in your <filepath>.
#
function r_simplified_path()
{
#
# quick check if there is something to simplify
# because this isn't fast at all
#
case "${1}" in
""|".")
RVAL="."
;;
*/|*\.\.*|*\./*|*/\.)
if [ "${MULLE_TRACE_PATHS_FLIP_X:-}" = 'YES' ]
then
set +x
fi
_r_simplified_path "$@"
if [ "${MULLE_TRACE_PATHS_FLIP_X:-}" = 'YES' ]
then
set -x
fi
;;
*)
RVAL="$1"
;;
esac
}
#
# r_assert_sane_path <filepath>
#
# Use to check a filepath before possible deletion. Will not accept the
# following filepaths and fail:
# . .. ~ ${HOME}
# anything starting with '$'
# anyfile path whose depth is <= 2, so /usr/local is bad but /usr/local/etc
# would be okay. /tmp is an exception though.
#
function r_assert_sane_path()
{
r_simplified_path "$1"
case "${RVAL}" in
\$*|~|"${HOME}"|..|.)
fail "refuse unsafe path \"$1\""
;;
/tmp/*)
;;
""|/*)
local filepath
filepath="${RVAL}"
r_path_depth "${filepath}"
if [ "${RVAL}" -le 2 ]
then
fail "Refuse suspicious path \"$1\""
fi
RVAL="${filepath}"
;;
*)
if [ "${RVAL}" = "${HOME}" ]
then
fail "refuse unsafe path \"$1\""
fi
;;
esac
}
fi
: