Skip to content

Instantly share code, notes, and snippets.

@polym
Created February 28, 2019 10:17
Show Gist options
  • Save polym/fa7f93a70b9a278a25a8cc309e553bd0 to your computer and use it in GitHub Desktop.
Save polym/fa7f93a70b9a278a25a8cc309e553bd0 to your computer and use it in GitHub Desktop.
Swagger.yaml 化整为零
import os
import yaml
from collections import OrderedDict
class PerfectDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(PerfectDumper, self).increase_indent(flow, False)
class UnsortableList(list):
def sort(self, *args, **kwargs):
pass
class UnsortableOrderedDict(OrderedDict):
def items(self, *args, **kwargs):
return UnsortableList(OrderedDict.items(self, *args, **kwargs))
yaml.add_representer(UnsortableOrderedDict, yaml.representer.SafeRepresenter.represent_dict)
def decode_yaml(filename):
return yaml.load(file(filename, 'r'))
def encode_yaml(data, filename = ''):
if filename == '':
print yaml.dump(data, Dumper=PerfectDumper, default_flow_style=False, allow_unicode=True)
else:
yaml.dump(data, file(filename, 'w'), Dumper=PerfectDumper, default_flow_style=False, allow_unicode=True)
def merge_map(a, b):
total = {}
for k, v in a.iteritems():
total[k] = v
for k, v in b.iteritems():
if k in total:
if isinstance(v, dict) and isinstance(total[k], dict):
total[k] = merge_map(total[k], v)
else:
raise Exception('merge_map need two map value')
else:
total[k] = v
return total
def merge_objects(dirpath):
total = {}
for obj in os.listdir(dirpath):
abspath = os.path.join(dirpath, obj)
if os.path.isdir(abspath):
total[obj] = merge_objects(abspath)
if os.path.isfile(abspath) and abspath.endswith('.yaml'):
total = merge_map(total, decode_yaml(abspath))
return total
encode_yaml(merge_objects('.'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment