| 1 |
# Copyright (c) 2017 Ansible Project |
| 2 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 3 |
|
| 4 |
# used by Convert-DictToSnakeCase to convert a string in camelCase |
| 5 |
# format to snake_case |
| 6 |
Function Convert-StringToSnakeCase($string) { |
| 7 |
# cope with pluralized abbreviations such as TargetGroupARNs |
| 8 |
if ($string -cmatch "[A-Z]{3,}s") { |
| 9 |
$replacement_string = $string -creplace $matches[0], "_$($matches[0].ToLower())" |
| 10 |
|
| 11 |
# handle when there was nothing before the plural pattern |
| 12 |
if ($replacement_string.StartsWith("_") -and -not $string.StartsWith("_")) { |
| 13 |
$replacement_string = $replacement_string.Substring(1) |
| 14 |
} |
| 15 |
$string = $replacement_string |
| 16 |
} |
| 17 |
$string = $string -creplace "(.)([A-Z][a-z]+)", '$1_$2' |
| 18 |
$string = $string -creplace "([a-z0-9])([A-Z])", '$1_$2' |
| 19 |
$string = $string.ToLower() |
| 20 |
|
| 21 |
return $string |
| 22 |
} |
| 23 |
|
| 24 |
# used by Convert-DictToSnakeCase to convert list entries from camelCase |
| 25 |
# to snake_case |
| 26 |
Function Convert-ListToSnakeCase($list) { |
| 27 |
$snake_list = [System.Collections.ArrayList]@() |
| 28 |
foreach ($value in $list) { |
| 29 |
if ($value -is [Hashtable]) { |
| 30 |
$new_value = Convert-DictToSnakeCase -dict $value |
| 31 |
} |
| 32 |
elseif ($value -is [Array] -or $value -is [System.Collections.ArrayList]) { |
| 33 |
$new_value = Convert-ListToSnakeCase -list $value |
| 34 |
} |
| 35 |
else { |
| 36 |
$new_value = $value |
| 37 |
} |
| 38 |
[void]$snake_list.Add($new_value) |
| 39 |
} |
| 40 |
|
| 41 |
return , $snake_list |
| 42 |
} |
| 43 |
|
| 44 |
# converts a dict/hashtable keys from camelCase to snake_case |
| 45 |
# this is to keep the return values consistent with the Ansible |
| 46 |
# way of working. |
| 47 |
Function Convert-DictToSnakeCase($dict) { |
| 48 |
$snake_dict = @{} |
| 49 |
foreach ($dict_entry in $dict.GetEnumerator()) { |
| 50 |
$key = $dict_entry.Key |
| 51 |
$snake_key = Convert-StringToSnakeCase -string $key |
| 52 |
|
| 53 |
$value = $dict_entry.Value |
| 54 |
if ($value -is [Hashtable]) { |
| 55 |
$snake_dict.$snake_key = Convert-DictToSnakeCase -dict $value |
| 56 |
} |
| 57 |
elseif ($value -is [Array] -or $value -is [System.Collections.ArrayList]) { |
| 58 |
$snake_dict.$snake_key = Convert-ListToSnakeCase -list $value |
| 59 |
} |
| 60 |
else { |
| 61 |
$snake_dict.$snake_key = $value |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
return , $snake_dict |
| 66 |
} |
| 67 |
|
| 68 |
# this line must stay at the bottom to ensure all defined module parts are exported |
| 69 |
Export-ModuleMember -Alias * -Function * -Cmdlet * |