@@ -115,13 +115,82 @@ def process_swagger(spec):
115115 except PreprocessingException as e :
116116 print (e .message )
117117
118+ remove_model_prefixes (spec )
119+
118120 # TODO: Kubernetes does not set a version for OpenAPI spec yet,
119121 # remove this when that is fixed.
120122 spec ['info' ]['version' ] = SPEC_VERSION
121123
122124 return spec
123125
124126
127+ def rename_model (spec , old_name , new_name ):
128+ if new_name in spec ['definitions' ]:
129+ raise PreprocessingException (
130+ "Cannot rename model %s. new name %s exists." %
131+ (old_name , new_name ))
132+ find_rename_ref_recursive (spec ,
133+ "#/definitions/" + old_name ,
134+ "#/definitions/" + new_name )
135+ spec ['definitions' ][new_name ] = spec ['definitions' ][old_name ]
136+ del spec ['definitions' ][old_name ]
137+
138+
139+ def find_rename_ref_recursive (root , old , new ):
140+ if isinstance (root , list ):
141+ for r in root :
142+ find_rename_ref_recursive (r , old , new )
143+ if isinstance (root , dict ):
144+ if "$ref" in root :
145+ if root ["$ref" ] == old :
146+ root ["$ref" ] = new
147+ for k , v in root .iteritems ():
148+ find_rename_ref_recursive (v , old , new )
149+
150+
151+ def remove_model_prefixes (spec ):
152+ """Remove full package name from OpenAPI model names.
153+
154+ Starting kubernetes 1.6, all models has full package name. This is
155+ verbose and inconvenient in python client. This function tries to remove
156+ parts of the package name but will make sure there is no conflicting model
157+ names. This will keep most of the model names generated by previous client
158+ but will change some of them.
159+ """
160+ models = {}
161+ for k , v in spec ['definitions' ].iteritems ():
162+ if k .startswith ("io.k8s" ):
163+ models [k ] = {"split_n" : 2 }
164+
165+ conflict = True
166+ while conflict :
167+ for k , v in models .iteritems ():
168+ splits = k .rsplit ("." , v ["split_n" ])
169+ v ["removed_prefix" ] = splits .pop (0 )
170+ v ["new_name" ] = "." .join (splits )
171+
172+ conflict = False
173+ for k , v in models .iteritems ():
174+ for k2 , v2 in models .iteritems ():
175+ if k != k2 and v ["new_name" ] == v2 ["new_name" ]:
176+ v ["conflict" ] = True
177+ v2 ["conflict" ] = True
178+ conflict = True
179+
180+ if conflict :
181+ for k , v in models .iteritems ():
182+ if "conflict" in v :
183+ print ("Resolving conflict for %s" % k )
184+ v ["split_n" ] += 1
185+ del v ["conflict" ]
186+
187+ for k , v in models .iteritems ():
188+ if "new_name" not in v :
189+ raise PreprocessingException ("Cannot rename model %s" % k )
190+ print ("Removing prefix %s from %s...\n " % (v ["removed_prefix" ], k ))
191+ rename_model (spec , k , v ["new_name" ])
192+
193+
125194def main ():
126195 pool = urllib3 .PoolManager ()
127196 with pool .request ('GET' , SPEC_URL , preload_content = False ) as response :
0 commit comments