|
78 | 78 | import ./macvtap.nix {
|
79 | 79 | inherit microvmConfig hypervisorConfig lib;
|
80 | 80 | };
|
| 81 | + |
| 82 | + /* |
| 83 | + extractOptValues - Extract and remove all occurrences of a command-line option and its values from a list of arguments. |
| 84 | +
|
| 85 | + Description: |
| 86 | + This function searches for a specified option flag in a list of command-line arguments, |
| 87 | + extracts ALL associated values, and returns both the values and a filtered list with |
| 88 | + all occurrences of the option flag and its values removed. The order of all other |
| 89 | + arguments is preserved. Uses tail recursion to process the argument list. |
| 90 | +
|
| 91 | + Parameters: |
| 92 | + optFlag :: String | [String] - The option flag(s) to search for. Can be: |
| 93 | + - A single string (e.g., "-platform") |
| 94 | + - A list of strings (e.g., ["-p" "-platform"]) |
| 95 | + All matching flags and their values are extracted |
| 96 | + extraArgs :: [String] - A list of command-line arguments |
| 97 | +
|
| 98 | + Returns: |
| 99 | + { |
| 100 | + values :: [String] - List of all values associated with matching flags (empty list if none found) |
| 101 | + args :: [String] - The input list with all matched flags and their values removed |
| 102 | + } |
| 103 | +
|
| 104 | + Examples: |
| 105 | + # Extract single occurrence: |
| 106 | + extractOptValues "-platform" ["-vnc" ":0" "-platform" "linux" "-usb"] |
| 107 | + => { values = ["linux"]; args = ["-vnc" ":0" "-usb"]; } |
| 108 | +
|
| 109 | + # Extract multiple occurrences: |
| 110 | + extractOptValues "-platform" ["-a" "a" "-b" "b" "-c" "c" "-b" "b2"] |
| 111 | + => { values = ["b" "b2"]; args = ["-b" "b" "-c" "c"]; } |
| 112 | +
|
| 113 | + # Extract with multiple flag aliases: |
| 114 | + extractOptValues ["-p" "-platform"] ["-p" "short" "-vnc" ":0" "-platform" "long" "-usb"] |
| 115 | + => { values = ["short" "long"]; args = ["-vnc" ":0" "-usb"]; } |
| 116 | +
|
| 117 | + # Degenerate case with no matches: |
| 118 | + extractOptValues ["-p" "-platform"] ["-vnc" ":0" "-usb"] |
| 119 | + => { values = []; args = ["-vnc" ":0" "-usb"]; } |
| 120 | + */ |
| 121 | + extractOptValues = optFlag: extraArgs: |
| 122 | + let |
| 123 | + flags = if builtins.isList optFlag then optFlag else [optFlag]; |
| 124 | + |
| 125 | + processArgs = args: values: acc: |
| 126 | + if args == [] then |
| 127 | + { values = values; args = acc; } |
| 128 | + else if (builtins.elem (builtins.head args) flags) && (builtins.length args) > 1 then |
| 129 | + # Found one of the option flags, skip it and its value |
| 130 | + processArgs (builtins.tail (builtins.tail args)) (values ++ [(builtins.elemAt args 1)]) acc |
| 131 | + else |
| 132 | + # Not the option we're looking for, keep this element |
| 133 | + processArgs (builtins.tail args) values (acc ++ [(builtins.head args)]); |
| 134 | + in |
| 135 | + processArgs extraArgs [] []; |
81 | 136 | }
|
0 commit comments