forked from googleapis/gapic-generator-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcase.py
More file actions
61 lines (48 loc) · 2.08 KB
/
case.py
File metadata and controls
61 lines (48 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
def to_snake_case(s: str) -> str:
"""Convert any string to snake case.
This is provided to templates as the ``snake_case`` filter.
Args:
s (str): The input string, provided in any sane case system.
Returns:
str: The string in snake case (and all lower-cased).
"""
# Replace all capital letters that are preceded by a lower-case letter.
s = re.sub(r'(?<=[a-z])([A-Z])', r'_\1', str(s))
# Find all capital letters that are followed by a lower-case letter,
# and are preceded by any character other than underscore.
# (Note: This also excludes beginning-of-string.)
s = re.sub(r'(?<=[^_])([A-Z])(?=[a-z])', r'_\1', s)
# Numbers are a weird case; the goal is to spot when they _start_
# some kind of name or acronym (e.g. 2FA, 3M).
#
# Find cases of a number preceded by a lower-case letter _and_
# followed by at least two capital letters or a single capital and
# end of string.
s = re.sub(r'(?<=[a-z])(\d)(?=[A-Z]{2})', r'_\1', s)
s = re.sub(r'(?<=[a-z])(\d)(?=[A-Z]$)', r'_\1', s)
# Done; return the camel-cased string.
return s.lower()
def to_camel_case(s: str) -> str:
'''Convert any string to camel case.
This is provided to templates as the ``camel_case`` filter.
Args:
s (str): The input string, provided in snake case.
Returns:
str: The string in camel case with the first letter unchanged.
'''
items = s.split('_')
return items[0] + "".join([x.capitalize() for x in items[1:]])