...
1# Copyright 2022 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""This file provides utility functions for working with strings."""
16
17import re
18
19from functools import cache
20
21SERVICE_REPLACEMENTS = {
22 'bigquery': 'BigQuery',
23 'billingbudgets': 'BillingBudgets',
24 'cloudbuild': 'CloudBuild',
25 'cloudfunctions': 'CloudFunctions',
26 'cloudresourcemanager':
27 '', #TODO(kcc-eng): Handle ResourceManagerLien, etc.
28 'dependencyservice': 'DependencyService',
29 'dlp': 'DLP',
30 'dns': 'DNS',
31 'gcp': 'GCP',
32 'http': 'HTTP',
33 'https': 'HTTPS',
34 'iam': 'IAM',
35 'identitytoolkit': 'IdentityPlatform',
36 'kms': 'KMS',
37 'osconfig': 'OSConfig',
38 'ospolicyassignment': 'OSPolicyAssignment',
39 'pubsub': 'PubSub',
40 'sql': 'SQL',
41 'tcp': 'TCP',
42 'testservice': 'TestService',
43 'url': 'URL',
44 'vpcaccess': 'VPCAccess',
45 'vpn': 'VPN',
46} # Replacement map for KCC Kinds. Keys are case insensitive.
47
48
49class colors:
50 HEADER = '\033[95m'
51 OKBLUE = '\033[94m'
52 OKCYAN = '\033[96m'
53 OKGREEN = '\033[92m'
54 WARNING = '\033[93m'
55 FAIL = '\033[91m'
56 ENDC = '\033[0m'
57 BOLD = '\033[1m'
58 UNDERLINE = '\033[4m'
59
60
61class patterns:
62 SNAKE_FIRST_LETTERS = re.compile('(^|_)([a-z])')
63
64
65def snake_to_title(string):
66 return replace_map(
67 SERVICE_REPLACEMENTS,
68 re.sub(patterns.SNAKE_FIRST_LETTERS, lambda m: m.group(2).upper(),
69 string), True)
70
71
72@cache
73def replace_map_regex(keys, ignore_case):
74 """Return a regex which matches any of the keys in the given set."""
75 if ignore_case:
76 return re.compile(r'(' + keys + r')', re.IGNORECASE)
77 return re.compile(r'(' + keys + r')')
78
79
80def replace_map(replacements, string, ignore_case=False):
81 """Return the given string with all instances of keys in the given map replaced with their values."""
82 if not replacements:
83 return string
84 return re.sub(
85 replace_map_regex(
86 r'|'.join([re.escape(key) for key in replacements.keys()]),
87 ignore_case),
88 lambda match: replacements[match.group().lower()
89 if ignore_case else match.group()], string)
View as plain text