style(user/bkytpldl-generic):Cleanup script settings section
[BK-2020-03.git] / unitproc / bkt-get_path_fork_level
1 #!/bin/bash
2
3 get_path_fork_level() {
4 # Desc: Get fork level from two paths
5 # Input: arg1 str path
6 # arg2 str path
7 # Output: stdout int fork level
8 # Version: 0.0.1
9 local path1="$1";
10 local path2="$2";
11
12 # Squeeze multiple slashes and remove trailing slashes
13 path1="$(echo "$path1" | tr -s '/' | sed 's:/*$::' )";
14 path2="$(echo "$path2" | tr -s '/' | sed 's:/*$::' )";
15
16 # Check for mixed absolute/relative paths
17 if [[ "$path1" =~ ^/ ]] && [[ "$path2" =~ ^/ ]]; then
18 flag_root=true;
19 # Remove initial /
20 path1="$(echo "$path1" | sed -e 's:^/::' )";
21 path2="$(echo "$path2" | sed -e 's:^/::' )";
22 elif [[ ! "$path1" =~ ^/ ]] && [[ ! "$path2" =~ ^/ ]]; then
23 flag_root=false;
24 else
25 declare -p path1 path2 flag_root;
26 echo "FATAL:Mixed relative and absolute paths not supported." 1>&2;
27 return 1;
28 fi;
29
30 # Save path as arrays with `/` as element delimiter
31 local IFS='/';
32 read -ra parts1 <<< "$path1";
33 read -ra parts2 <<< "$path2";
34
35 # Get fork level by counting identical path elements from rootside
36 local fork_level=0;
37 for (( i=0; i<${#parts1[@]} && i<${#parts2[@]}; i++ )); do
38 if [[ "${parts1[i]}" != "${parts2[i]}" ]]; then break; fi;
39 ((fork_level++));
40 done;
41
42 echo "$fork_level";
43 #declare -p path1 path2 flag_root parts1 parts2 fork_level; # debug
44 return 0;
45 }; # Get fork level int from two paths
46
47 printf "========Test 1========\n"; # fork at 0
48 p1="foo"; p2="bee"; declare -p p1 p2;
49 get_path_fork_level "$p1" "$p2";
50 printf "========Test 2========\n"; # fork at 1
51 p1="foo"; p2="foo/bar"; declare -p p1 p2;
52 get_path_fork_level "$p1" "$p2";
53 printf "========Test 3========\n"; # fork at 1
54 p1="foo"; p2="foo/bar/"; declare -p p1 p2;
55 get_path_fork_level "$p1" "$p2";
56 printf "========Test 4========\n"; # fork at 2
57 p1="foo/bar/baz"; p2="foo/bar"; declare -p p1 p2;
58 get_path_fork_level "$p1" "$p2";
59 printf "========Test 5========\n"; # fork at 2
60 p1="/foo/bar/baz"; p2="/foo/bar"; declare -p p1 p2;
61 get_path_fork_level "$p1" "$p2";
62 printf "========Test 6========\n"; # ERROR: No mixed
63 p1="foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2;
64 get_path_fork_level "$p1" "$p2";
65 printf "========Test 7========\n"; # fork at 0
66 p1="/foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2;
67 get_path_fork_level "$p1" "$p2";
68 printf "========Test 8========\n"; # # ERROR: No mixed
69 p1="/foo/bar/baz"; p2="foo"; declare -p p1 p2;
70 get_path_fork_level "$p1" "$p2";
71 printf "========Test 9========\n"; # fork at 3
72 p1="foo///////////bar////////baz//////"; p2="foo/////////bar/////////baz///bee"; declare -p p1 p2;
73 get_path_fork_level "$p1" "$p2";
74