grpc_util.bzl 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright 2021 The gRPC Authors
  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. # Follows convention set in objectivec_helpers.cc in the protobuf ObjC compiler.
  15. """
  16. Contains generic helper utilities.
  17. """
  18. _upper_segments_list = ["url", "http", "https"]
  19. def strip_extension(str):
  20. return str.rpartition(".")[0]
  21. def capitalize(word):
  22. if word in _upper_segments_list:
  23. return word.upper()
  24. else:
  25. return word.capitalize()
  26. def lower_underscore_to_upper_camel(str):
  27. """Converts from lower underscore case to upper camel case.
  28. Args:
  29. str: The snake case string to convert.
  30. Returns:
  31. The title case version of str.
  32. """
  33. str = strip_extension(str)
  34. camel_case_str = ""
  35. word = ""
  36. for c in str.elems(): # NB: assumes ASCII!
  37. if c.isalpha():
  38. word += c.lower()
  39. else:
  40. # Last word is finished.
  41. if len(word):
  42. camel_case_str += capitalize(word)
  43. word = ""
  44. if c.isdigit():
  45. camel_case_str += c
  46. # Otherwise, drop the character. See UnderscoresToCamelCase in:
  47. # third_party/protobuf/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
  48. if len(word):
  49. camel_case_str += capitalize(word)
  50. return camel_case_str
  51. def file_to_upper_camel(src):
  52. elements = src.rpartition("/")
  53. upper_camel = lower_underscore_to_upper_camel(elements[-1])
  54. return "".join(list(elements[:-1]) + [upper_camel])
  55. def file_with_extension(src, ext):
  56. elements = src.rpartition("/")
  57. return "".join(list(elements[:-1]) + [elements[-1], "." + ext])
  58. def to_upper_camel_with_extension(src, ext):
  59. src = file_to_upper_camel(src)
  60. return file_with_extension(src, ext)