| 1 |
# https://github.com/MorganPeterson/args/blob/main/args.janet |
| 2 |
|
| 3 |
# https://github.com/AlDanial/cloc/issues/802 |
| 4 |
(defn- to-byte |
| 5 |
"convert chars to byte and only return first result" |
| 6 |
[x] |
| 7 |
(get (string/bytes x) 0)) |
| 8 |
|
| 9 |
(defn- parse |
| 10 |
"parse command line arguments" |
| 11 |
[args] |
| 12 |
(def f |
| 13 |
(fiber/new |
| 14 |
(fn [] |
| 15 |
(loop [x :in args] |
| 16 |
(yield x))))) |
| 17 |
(def dash (to-byte "-")) |
| 18 |
(def spce (to-byte " ")) |
| 19 |
|
| 20 |
(var results @[]) |
| 21 |
(var kpwh false) # keep flag whole if no dash |
| 22 |
|
| 23 |
(while (fiber/can-resume? f) |
| 24 |
(var args0 (resume f)) |
| 25 |
|
| 26 |
(cond |
| 27 |
(= args0 dash) (set args0 (resume f)) |
| 28 |
(set kpwh true)) |
| 29 |
|
| 30 |
(if (and (= args0 dash) (not (fiber/can-resume? f))) (break)) |
| 31 |
|
| 32 |
(cond |
| 33 |
(= args0 dash) |
| 34 |
(do |
| 35 |
(var a @[]) |
| 36 |
(loop [x :in f :until (or (= x spce) (not (fiber/can-resume? f)))] |
| 37 |
(array/push a (string/from-bytes x))) |
| 38 |
(array/push results (string/join a))) |
| 39 |
(do |
| 40 |
(var b @[]) |
| 41 |
(when (not (nil? args0)) |
| 42 |
(array/push b (string/from-bytes args0)) |
| 43 |
(loop [x :in f :until (or (= x spce) (not (fiber/can-resume? f)))] |
| 44 |
(array/push b (string/from-bytes x))) |
| 45 |
(cond |
| 46 |
(true? kpwh) (array/push results (string/join b)) |
| 47 |
(do |
| 48 |
(array/concat results b) |
| 49 |
(set kpwh false))))))) |
| 50 |
results) |
| 51 |
|
| 52 |
(defn flags |
| 53 |
"take in raw commandline string" |
| 54 |
[args] |
| 55 |
(parse (string/join (tuple/slice args 1) " "))) |