summaryrefslogtreecommitdiffstats
path: root/build/relpath.awk
blob: 10651d0a07e0ab7d994805836e2dd00998014490 (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
# The path from one directory to one file, relative to the directory; used by
# `make install' for the hook symlink.  A relative link survives a staged install,
# an unpacked prefix, or an image built somewhere else; an absolute one points at
# whatever lives at that path on the machine reading it.
#
# POSIX awk: busybox awk, mawk and gawk all agree on it.


function split_path(p, out,    n, parts, i, depth) {
    n = split(p, parts, "/")
    depth = 0
    for (i = 1; i <= n; i++) {
        if (parts[i] == "" || parts[i] == ".")
            continue                       # empty runs, and "." changes nothing
        if (parts[i] == "..") {
            if (depth > 0)
                depth--                    # already inside a component we know
            else
                out[++depth] = ".."        # above the root we cannot see into
            continue
        }
        out[++depth] = parts[i]
    }
    return depth
}

BEGIN {
    if (from == "" || to == "") {
        print "relpath: needs -v from=DIR -v to=FILE" > "/dev/stderr"
        exit 64
    }

    nf = split_path(from, f)
    nt = split_path(to, t)

    common = 0
    while (common < nf && common < nt && f[common + 1] == t[common + 1])
        common++

    # No relative route into a directory we cannot name.

    if ((nf > common && f[common + 1] == "..") ||
        (nt > common && t[common + 1] == "..")) {
        print to
        exit 0
    }

    res = ""
    for (i = common + 1; i <= nf; i++)
        res = res ".." "/"
    for (i = common + 1; i <= nt; i++)
        res = res t[i] "/"
    sub(/\/$/, "", res)
    if (res == "")
        res = "."                          # the file is the directory's own name
    print res
}