|
| 1 | +module Giraffe.Python.FormatExpressions |
| 2 | + |
| 3 | +open System |
| 4 | +open System.Text.RegularExpressions |
| 5 | +open Microsoft.FSharp.Reflection |
| 6 | +open FSharp.Core |
| 7 | + |
| 8 | +// --------------------------- |
| 9 | +// String matching functions |
| 10 | +// --------------------------- |
| 11 | + |
| 12 | +let private formatStringMap = |
| 13 | + let decodeSlashes (str: string) = |
| 14 | + // Kestrel has made the weird decision to |
| 15 | + // partially decode a route argument, which |
| 16 | + // means that a given route argument would get |
| 17 | + // entirely URL decoded except for '%2F' (/). |
| 18 | + // Hence decoding %2F must happen separately as |
| 19 | + // part of the string parsing function. |
| 20 | + // |
| 21 | + // For more information please check: |
| 22 | + // https://github.com/aspnet/Mvc/issues/4599 |
| 23 | + str.Replace("%2F", "/").Replace("%2f", "/") |
| 24 | + |
| 25 | + let parseGuid (str: string) = |
| 26 | + match str.Length with |
| 27 | + | 22 -> ShortGuid.toGuid str |
| 28 | + | _ -> Guid str |
| 29 | + |
| 30 | + let guidPattern = |
| 31 | + "([0-9A-Fa-f]{8}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{12}|[0-9A-Fa-f]{32}|[-_0-9A-Za-z]{22})" |
| 32 | + |
| 33 | + let shortIdPattern = "([-_0-9A-Za-z]{10}[048AEIMQUYcgkosw])" |
| 34 | + |
| 35 | + dict |
| 36 | + [ |
| 37 | + // Char Regex Parser |
| 38 | + // ------------------------------------------------------------- |
| 39 | + 'b', ("(?i:(true|false)){1}", (fun (s: string) -> bool.Parse s) >> box) // bool |
| 40 | + 'c', ("([^/]{1})", char >> box) // char |
| 41 | + 's', ("([^/]+)", decodeSlashes >> box) // string |
| 42 | + 'i', ("(-?\d+)", int32 >> box) // int |
| 43 | + 'd', ("(-?\d+)", int64 >> box) // int64 |
| 44 | + 'f', ("(-?\d+\.{1}\d+)", float >> box) // float |
| 45 | + 'O', (guidPattern, parseGuid >> box) // Guid |
| 46 | + 'u', (shortIdPattern, ShortId.toUInt64 >> box) ] // uint64 |
| 47 | + |
| 48 | +type MatchMode = |
| 49 | + | Exact // Will try to match entire string from start to end. |
| 50 | + | StartsWith // Will try to match a substring. Subject string should start with test case. |
| 51 | + | EndsWith // Will try to match a substring. Subject string should end with test case. |
| 52 | + | Contains // Will try to match a substring. Subject string should contain test case. |
| 53 | + |
| 54 | +type MatchOptions = |
| 55 | + { IgnoreCase: bool |
| 56 | + MatchMode: MatchMode } |
| 57 | + |
| 58 | + static member Exact = |
| 59 | + { IgnoreCase = false |
| 60 | + MatchMode = Exact } |
| 61 | + |
| 62 | + static member IgnoreCaseExact = { IgnoreCase = true; MatchMode = Exact } |
| 63 | + |
| 64 | +let private convertToRegexPatternAndFormatChars (mode: MatchMode) (formatString: string) = |
| 65 | + let rec convert (chars: char list) = |
| 66 | + match chars with |
| 67 | + | '%' :: '%' :: tail -> |
| 68 | + let pattern, formatChars = convert tail |
| 69 | + "%" + pattern, formatChars |
| 70 | + | '%' :: c :: tail -> |
| 71 | + let pattern, formatChars = convert tail |
| 72 | + let regex, _ = formatStringMap.[c] |
| 73 | + regex + pattern, c :: formatChars |
| 74 | + | c :: tail -> |
| 75 | + let pattern, formatChars = convert tail |
| 76 | + c.ToString() + pattern, formatChars |
| 77 | + | [] -> "", [] |
| 78 | + |
| 79 | + let inline formatRegex mode pattern = |
| 80 | + match mode with |
| 81 | + | Exact -> "^" + pattern + "$" |
| 82 | + | StartsWith -> "^" + pattern |
| 83 | + | EndsWith -> pattern + "$" |
| 84 | + | Contains -> pattern |
| 85 | + |
| 86 | + formatString |
| 87 | + |> List.ofSeq |
| 88 | + |> convert |
| 89 | + |> (fun (pattern, formatChars) -> formatRegex mode pattern, formatChars) |
| 90 | + |
| 91 | +/// <summary> |
| 92 | +/// Tries to parse an input string based on a given format string and return a tuple of all parsed arguments. |
| 93 | +/// </summary> |
| 94 | +/// <param name="format">The format string which shall be used for parsing.</param> |
| 95 | +/// <param name="options">The options record with specifications on how the matching should behave.</param> |
| 96 | +/// <param name="input">The input string from which the parsed arguments shall be extracted.</param> |
| 97 | +/// <returns>Matched value as an option of 'T</returns> |
| 98 | +let tryMatchInput (format: PrintfFormat<_, _, _, _, 'T>) (options: MatchOptions) (input: string) = |
| 99 | + try |
| 100 | + let pattern, formatChars = |
| 101 | + format.Value |
| 102 | + |> Regex.Escape |
| 103 | + |> convertToRegexPatternAndFormatChars options.MatchMode |
| 104 | + |
| 105 | + let options = |
| 106 | + match options.IgnoreCase with |
| 107 | + | true -> RegexOptions.IgnoreCase |
| 108 | + | false -> RegexOptions.None |
| 109 | + |
| 110 | + let result = Regex.Match(input, pattern, options) |
| 111 | + |
| 112 | + if result.Groups.Count <= 1 then |
| 113 | + None |
| 114 | + else |
| 115 | + let groups = result.Groups |> Seq.cast<Group> |> Seq.skip 1 |
| 116 | + |
| 117 | + let values = |
| 118 | + (groups, formatChars) |
| 119 | + ||> Seq.map2 (fun g c -> |
| 120 | + let _, parser = formatStringMap.[c] |
| 121 | + let value = parser g.Value |
| 122 | + value) |
| 123 | + |> Seq.toArray |
| 124 | + |
| 125 | + let result = |
| 126 | + match values.Length with |
| 127 | + | 1 -> values.[0] |
| 128 | + | _ -> |
| 129 | + let types = values |> Array.map (fun v -> v.GetType()) |
| 130 | + let tupleType = FSharpType.MakeTupleType types |
| 131 | + FSharpValue.MakeTuple(values, tupleType) |
| 132 | + |
| 133 | + result :?> 'T |> Some |
| 134 | + with _ -> |
| 135 | + None |
| 136 | + |
| 137 | +/// <summary> |
| 138 | +/// Tries to parse an input string based on a given format string and return a tuple of all parsed arguments. |
| 139 | +/// </summary> |
| 140 | +/// <param name="format">The format string which shall be used for parsing.</param> |
| 141 | +/// <param name="ignoreCase">The flag to make matching case insensitive.</param> |
| 142 | +/// <param name="input">The input string from which the parsed arguments shall be extracted.</param> |
| 143 | +/// <returns>Matched value as an option of 'T</returns> |
| 144 | +let tryMatchInputExact (format: PrintfFormat<_, _, _, _, 'T>) (ignoreCase: bool) (input: string) = |
| 145 | + let options = |
| 146 | + match ignoreCase with |
| 147 | + | true -> MatchOptions.IgnoreCaseExact |
| 148 | + | false -> MatchOptions.Exact |
| 149 | + |
| 150 | + tryMatchInput format options input |
| 151 | + |
| 152 | + |
| 153 | +// --------------------------- |
| 154 | +// Validation helper functions |
| 155 | +// --------------------------- |
| 156 | + |
| 157 | +/// **Description** |
| 158 | +/// |
| 159 | +/// Validates if a given format string can be matched with a given tuple. |
| 160 | +/// |
| 161 | +/// **Parameters** |
| 162 | +/// |
| 163 | +/// `format`: The format string which shall be used for parsing. |
| 164 | +/// |
| 165 | +/// **Output** |
| 166 | +/// |
| 167 | +/// Returns `unit` if validation was successful otherwise will throw an `Exception`. |
| 168 | +/// Returns `unit` if validation was successful otherwise will throw an `Exception`. |
0 commit comments