File: relpath.awk

package info (click to toggle)
brltty 5.6-10~bpo9+1
  • links: PTS, VCS
  • area: main
  • in suites: stretch-backports
  • size: 25,116 kB
  • sloc: ansic: 117,871; sh: 6,590; java: 4,785; xml: 3,451; makefile: 1,973; tcl: 1,499; awk: 611; ml: 293; python: 250; lisp: 52
file content (36 lines) | stat: -rw-r--r-- 1,009 bytes parent folder | download | duplicates (14)
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
function normalizePath(path) {
  if (length(path) == 0) path = "."
  path = path pathDelimiter
  gsub((pathDelimiter "+"), pathDelimiter, path)
  return path
}

BEGIN {
  pathDelimiter = "/"

  pathLength = length(path = normalizePath(path))
  referenceLength = length(reference = normalizePath(reference))

  minimumLength = pathLength
  if (referenceLength < minimumLength) minimumLength = referenceLength

  prefixLength = 0
  for (i=1; i<=minimumLength; ++i) {
    character = substr(reference, i, 1)
    if (substr(path, i, 1) != character) break
    if (character == pathDelimiter) prefixLength = i
  }

  if ((prefixLength > 0) || ((substr(path, 1, 1) == pathDelimiter) == (substr(reference, 1, 1) == pathDelimiter))) {
    suffix = substr(path, prefixLength+1)
    prefix = substr(reference, prefixLength+1)
    gsub(("[^" pathDelimiter "]+"), "..", prefix)
    path = normalizePath(prefix suffix)
  }

  path = normalizePath(path)
  sub((pathDelimiter "$"), "", path)

  printf "%s", path
  exit 0
}