update(user/bkots):Remove unnecessary must()
[BK-2020-03.git] / unitproc / bkt-get_path_fork_level
CommitLineData
670c5ae4
SBS
1#!/bin/bash
2
3get_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
47printf "========Test 1========\n"; # fork at 0
48p1="foo"; p2="bee"; declare -p p1 p2;
49get_path_fork_level "$p1" "$p2";
50printf "========Test 2========\n"; # fork at 1
51p1="foo"; p2="foo/bar"; declare -p p1 p2;
52get_path_fork_level "$p1" "$p2";
53printf "========Test 3========\n"; # fork at 1
54p1="foo"; p2="foo/bar/"; declare -p p1 p2;
55get_path_fork_level "$p1" "$p2";
56printf "========Test 4========\n"; # fork at 2
57p1="foo/bar/baz"; p2="foo/bar"; declare -p p1 p2;
58get_path_fork_level "$p1" "$p2";
59printf "========Test 5========\n"; # fork at 2
60p1="/foo/bar/baz"; p2="/foo/bar"; declare -p p1 p2;
61get_path_fork_level "$p1" "$p2";
62printf "========Test 6========\n"; # ERROR: No mixed
63p1="foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2;
64get_path_fork_level "$p1" "$p2";
65printf "========Test 7========\n"; # fork at 0
66p1="/foo/bar/baz"; p2="/bee/boo/tax"; declare -p p1 p2;
67get_path_fork_level "$p1" "$p2";
68printf "========Test 8========\n"; # # ERROR: No mixed
69p1="/foo/bar/baz"; p2="foo"; declare -p p1 p2;
70get_path_fork_level "$p1" "$p2";
71printf "========Test 9========\n"; # fork at 3
72p1="foo///////////bar////////baz//////"; p2="foo/////////bar/////////baz///bee"; declare -p p1 p2;
73get_path_fork_level "$p1" "$p2";
74