File: getopts.awk

package info (click to toggle)
zplug 2.4.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,068 kB
  • sloc: sh: 1,504; awk: 235; makefile: 26
file content (74 lines) | stat: -rw-r--r-- 1,370 bytes parent folder | download | duplicates (4)
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
function out(k,v) {
    print(k "" (v == "" ? "" : " "v))
}

function pop() {
    return len <= 0 ? "_" : opt[len--]
}

{
    if (done) {
        out("_" , $0)
        next
    }

    if (match($0, "^-[A-Za-z]+")) {
        $0 = "- " substr($0, 2, RLENGTH - 1) " " substr($0, RLENGTH + 1)

    } else if (match($0, "^--[A-Za-z0-9_-]+")) {
        $0 = "-- " substr($0, 3, RLENGTH - 2) " " substr($0, RLENGTH + 2)
    }

    if ($1 == "--" && $2 == "") {
        done = 1

    } else if ($2 == "" || $1 !~ /^-|^--/ ) {
        out(pop(), $0)

    } else {
        while (len) {
            out(pop())
        }

        if ($3 != "") {
            if (match($0, $2)) {
                $3 = substr($0, RSTART + RLENGTH + 1)
            }
        }

        if ($1 == "--") {
            if ($3 == "") {
                opt[++len] = $2
            } else {
                out($2, $3)
            }
        }

        if ($1 == "-") {
            if ($2 == "") {
                print($1)
                next

            } else {
                n = split($2, keys, "")
            }

            if ($3 == "") {
                opt[++len] = keys[n]

            } else {
                out(keys[n], $3)
            }

            for (i = 1; i < n; i++) {
                out(keys[i])
            }
        }
    }
}

END {
    while (len) {
        out(pop())
    }
}