Method: Kubeclient::ClientMixin.parse_definition

Defined in:
lib/kubeclient/common.rb

.parse_definition(kind, name) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/kubeclient/common.rb', line 139

def self.parse_definition(kind, name)
  # Kubernetes gives us 3 inputs:
  #   kind: "ComponentStatus", "NetworkPolicy", "Endpoints"
  #   name: "componentstatuses", "networkpolicies", "endpoints"
  #   singularName: "componentstatus" etc (usually omitted, defaults to kind.downcase)
  # and want to derive singular and plural method names, with underscores:
  #   "network_policy"
  #   "network_policies"
  # kind's CamelCase word boundaries determine our placement of underscores.

  if IRREGULAR_NAMES[kind]
    # In a few cases, the given kind / singularName itself is still plural.
    # We require a distinct singular method name, so force it.
    method_names = IRREGULAR_NAMES[kind]
  else
    # TODO: respect singularName from discovery?
    # But how?  If it differs from kind.downcase, kind's word boundaries don't apply.
    singular_name = kind.downcase

    if !(/[A-Z]/ =~ kind)
      # Some custom resources have a fully lowercase kind - can't infer underscores.
      method_names = [singular_name, name]
    else
      # Some plurals are not exact suffixes, e.g. NetworkPolicy -> networkpolicies.
      # So don't expect full last word to match.
      /^(?<prefix>(.*[A-Z]))(?<singular_suffix>[^A-Z]*)$/ =~ kind  # "NetworkP", "olicy"
      if name.start_with?(prefix.downcase)
        plural_suffix = name[prefix.length..-1]                    # "olicies"
        prefix_underscores = ClientMixin.underscore_entity(prefix) # "network_p"
        method_names = [prefix_underscores + singular_suffix,      # "network_policy"
                        prefix_underscores + plural_suffix]        # "network_policies"
      else
        method_names = resolve_unconventional_method_names(name, kind, singular_name)
      end
    end
  end

  OpenStruct.new(
    entity_type:   kind,
    resource_name: name,
    method_names:  method_names
  )
end