def main(output_file: Text): coloredlogs.install(level=logging.DEBUG) db.SetupDatabase(db_file=':memory:') logging.debug('Generating enums...') lines = ['import enum', ''] enum_lines = {} for cls in db.db.Entity.__subclasses__(): enum_name = None enum_field = None secondary_enum_field = None for attr in cls._attrs_: if attr.py_type in (common.SingleEnumString, common.MultiEnumString): enum_name = 'E' + cls.__name__ enum_field = attr.name elif attr.py_type in (common.MultiEnumSecondaryString, ): secondary_enum_field = attr.name if not enum_name or not enum_field: continue if secondary_enum_field: logging.info( f'Processing {cls.__name__} (enum fields "{enum_field}", "{secondary_enum_field}")' ) else: logging.info( f'Processing {cls.__name__} (enum field "{enum_field}")') SPECIAL_CHARS = string.punctuation.replace('%', '').replace('_', '') enums = {} with orm.db_session: for r in cls.select(): name = ''.join(c for c in getattr(r, enum_field) if c not in SPECIAL_CHARS) name = name.replace('%', '_percent') if secondary_enum_field and getattr(r, secondary_enum_field): name += '_' + getattr(r, secondary_enum_field) name = stringcase.constcase(name) if name[0].isnumeric(): name = '_' + name name = re.sub('_+', '_', name) if cls.__name__ == 'ItemSubClass': enums[name] = r.sub_class else: enums[name] = r.id enum_lines[enum_name] = [f'class {enum_name}(enum.IntEnum):'] for k, v in sorted(enums.items()): enum_lines[enum_name].append(f' {k} = {v}') enum_lines[enum_name].append('') for _, el in sorted(enum_lines.items()): lines.extend(el) with open(output_file, 'w') as f: f.write('\n'.join(lines))
def convertCase(self, data): txt = self.txtInput.text() result = txt if data == 'Alpha Num Case': result = stringcase.alphanumcase(txt) if data == 'Camel Case': result = stringcase.camelcase(txt) if data == 'Capital Case': result = stringcase.capitalcase(txt) if data == 'Const Case': result = stringcase.constcase(txt) if data == 'Lower Case': result = stringcase.lowercase(txt) if data == 'Pascal Case': result = stringcase.pascalcase(txt) if data == 'Path Case': result = stringcase.pathcase(txt) if data == 'Sentence Case': result = stringcase.sentencecase(txt) if data == 'Snake Case': result = stringcase.snakecase(txt) if data == 'Spinal Case': result = stringcase.spinalcase(txt) if data == 'Title Case': result = stringcase.titlecase(txt) if data == 'Trim Case': result = stringcase.trimcase(txt) if data == 'Upper Case': result = stringcase.uppercase(txt) self.lblResult.setText(result) pyperclip.copy(result)
def write_edge(self, edge, extra): if edge.prop is not None: type_ = stringcase.constcase(edge.prop.name) row = [type_, edge.source_id, edge.target_id, edge.weight] self.links_writer.writerow(row) if edge.proxy is not None: proxy = edge.proxy type_ = stringcase.constcase(proxy.schema.name) # That potentially may lead to multiple edges with same id cells = [proxy.id, type_, edge.source_id, edge.target_id] cells.extend(extra or []) for prop, values in self.exportable_fields(edge.proxy): cells.append(prop.type.join(values)) writer = self._get_writer(proxy.schema) writer.writerow(cells)
def legacy_enum() -> str: out = ["class LegacyTranslationEnum:"] for module in modules: for translation in module["translations"]: key = stringcase.constcase(translation["key"]) value = f'({module["index"]}, {translation["index"]})' out.append(f" {key} = {value}") return "\n".join(out) + "\n"
def _make_edge(self, source, target, attributes, type_): cypher = 'MATCH (s { %(source)s }), (t { %(target)s }) ' \ 'MERGE (s)-[:%(type)s { %(map)s }]->(t);\n' self.fh.write( cypher % { 'source': self._to_map({'id': source}), 'target': self._to_map({'id': target}), 'type': stringcase.constcase(type_), 'map': self._to_map(attributes), })
def legacy_enum() -> str: out = ["export enum LegacyEnum {"] for module in modules: for translation in module["translations"]: key = stringcase.constcase(translation["key"]) value = module["index"] * 1000 + translation["index"] out.append(f" {key} = {value},") out.append("}") return "\n".join(out) + "\n"
def test_constcase(self): from stringcase import constcase eq = self.assertEqual eq('FOO_BAR', constcase('fooBar')) eq('FOO_BAR', constcase('foo_bar')) eq('FOO_BAR', constcase('foo-bar')) eq('FOO_BAR', constcase('foo.bar')) eq('_BAR_BAZ', constcase('_bar_baz')) eq('_BAR_BAZ', constcase('.bar_baz')) eq('', constcase('')) eq('NONE', constcase(None))
def _make_edge(self, source, target, attributes, label): cypher = 'MATCH (s { %(source)s }), (t { %(target)s }) ' \ 'MERGE (s)-[:%(label)s { %(map)s }]->(t);\n' label = [stringcase.constcase(l) for l in ensure_list(label)] self.fh.write( cypher % { 'source': self._to_map({'id': source}), 'target': self._to_map({'id': target}), 'label': ':'.join(label), 'map': self._to_map(attributes), })
def __init__(self, project_name, path_input, exe_suffix): if not path_input: print("No Path input - default to current working directory", os.getcwd()) path_input = os.getcwd() elif os.path.exists(path_input): print("Path exists !!") else: print("Path DOES NOT exists !!", "Creating folder", path_input) os.mkdir(path_input) self.cwd = os.getcwd() self.path = path_input self.base_const = stringcase.constcase(os.path.basename(self.path)) self.base_snake = stringcase.snakecase(os.path.basename(self.path)) print("Current working directory %s" % self.path) self.snake = stringcase.snakecase(project_name) self.const = stringcase.constcase(project_name) self.pascal = stringcase.pascalcase(project_name) self.create_base() self.create_project() if exe_suffix: exe_project_name = "_".join([stringcase.snakecase(project_name), exe_suffix]) self.exe_snake = stringcase.snakecase(exe_project_name) self.exe_const = stringcase.constcase(exe_project_name) self.exe_pascal = stringcase.pascalcase(exe_project_name) self.create_executable() # print current projects print("Current source projects: ") for d in next(os.walk(os.path.join(self.path, src)))[1]: print("\t", d) # print current projects print("Current source projects - tests: ") for d in next(os.walk(os.path.join(self.path, tests)))[1]: print("\t", d)
def write_link(self, proxy, prop, value): if prop.type.name not in self.edge_types: return weight = prop.specificity(value) if weight == 0: return other_id = self.get_id(prop.type, value) if prop.type != registry.entity and other_id not in self.nodes_seen: row = [other_id, prop.type.name, value] self.nodes_writer.writerow(row) self.nodes_seen.add(other_id) type_ = stringcase.constcase(prop.name) row = [type_, proxy.id, other_id, weight] self.links_writer.writerow(row)
def write_graph(self) -> None: """Export queries for each graph element.""" for node in self.graph.iternodes(): if node.value in self.proxy_nodes: continue if node.id is None: continue if node.proxy is not None: self.proxy_nodes.add(node.value) attributes = self.get_attributes(node) attributes["id"] = node.id if node.caption is not None: attributes["caption"] = node.caption if node.schema: labels = list(node.schema.names) else: labels = [node.type.name] cypher = "MERGE (p { %(id)s }) " "SET p += { %(map)s } SET p :%(label)s;\n" self.fh.write( cypher % { "id": self._to_map({"id": node.id}), "map": self._to_map(attributes), "label": ":".join(labels), }) for edge in self.graph.iteredges(): attributes = self.get_attributes(edge) attributes["id"] = edge.id attributes["weight"] = str(edge.weight) cypher = ("MATCH (s { %(source)s }), (t { %(target)s }) " "MERGE (s)-[:%(type)s { %(map)s }]->(t);\n") self.fh.write( cypher % { "source": self._to_map({"id": edge.source_id}), "target": self._to_map({"id": edge.target_id}), "type": stringcase.constcase(edge.type_name), "map": self._to_map(attributes), }) self.graph.flush()
def init(**params): for key, default in (("debug", False), ("multiplierType", Multiplier)): for o in (CommonUIComponents, Global): setattr(o, constcase(snakecase(key)), params.get(key, default)) SmartWidget._STYLE_INSTANCE = Style() # pylint: disable = import-outside-toplevel from tkinter import Canvas from tkinter.ttk import Button, Label, Radiobutton from .containers import \ Container \ , LabeledContainer \ , LabeledRadioButtonGroup \ , LabeledWidgetContainer \ , LabeledWidgetLabeledContainer \ , LabeledWidgetsContainer \ , TimePicker from .widgets import \ Checkbutton \ , Combobox \ , CommonCombobox \ , Entry \ , LabeledScale \ , Listbox \ , NumberEntry \ , Scrollbar \ , Spinbox \ , StatefulButton for tkinterBase in (Button, Canvas, Label, Radiobutton): CommonUIComponents.wrapClass(tkinterBase) for smartWidget in (Checkbutton, Combobox, CommonCombobox, Container, Entry, LabeledContainer, LabeledRadioButtonGroup, LabeledWidgetContainer, LabeledWidgetsContainer, LabeledWidgetLabeledContainer, LabeledScale, Listbox, NumberEntry, Scrollbar, Spinbox, StatefulButton, TimePicker): CommonUIComponents.registerClass(smartWidget)
def case_conversion(source, style: StringStyle) -> str: """Case conversion of the input (usually fully qualified vss node inlcuding the path) into a supported string style representation. Args: source: Source string to apply conversion to. style: Target string style to convert source to. Returns: Converted source string according to provided string style. """ if style == StringStyle.ALPHANUM_CASE: return stringcase.alphanumcase(source) elif style == StringStyle.CAMEL_CASE: return camel_case(source) elif style == StringStyle.CAMEL_BACK: return camel_back(source) elif style == StringStyle.CAPITAL_CASE: return stringcase.capitalcase(source) elif style == StringStyle.CONST_CASE: return stringcase.constcase(source) elif style == StringStyle.LOWER_CASE: return stringcase.lowercase(source) elif style == StringStyle.PASCAL_CASE: return stringcase.pascalcase(source) elif style == StringStyle.SENTENCE_CASE: return stringcase.sentencecase(source) elif style == StringStyle.SNAKE_CASE: return stringcase.snakecase(source) elif style == StringStyle.SPINAL_CASE: return stringcase.spinalcase(source) elif style == StringStyle.TITLE_CASE: return stringcase.titlecase(source) elif style == StringStyle.TRIM_CASE: return stringcase.trimcase(source) elif style == StringStyle.UPPER_CASE: return stringcase.uppercase(source) else: return source
def generate( self, resource, single_endpoint, single_parameters, filter_for_single, list_endpoint, list_parameters, ): list_templ = self.get_template("redux/actions.js.j2") resource_const = stringcase.constcase(resource) rendered = list_templ.render( resource=resource, resource_const=resource_const, single_endpoint=single_endpoint, single_parameters=single_parameters, filter_for_single=filter_for_single, list_endpoint=list_endpoint, list_parameters=list_parameters, ) return rendered
def write_graph(self): """Export queries for each graph element.""" for node in self.graph.iternodes(): if node.value in self.proxy_nodes: continue if node.proxy is not None: self.proxy_nodes.add(node.value) attributes = self.get_attributes(node) attributes['id'] = node.id if node.caption is not None: attributes['caption'] = node.caption if node.schema: labels = node.schema.names else: labels = [node.type.name] cypher = 'MERGE (p { %(id)s }) ' \ 'SET p += { %(map)s } SET p :%(label)s;\n' self.fh.write( cypher % { 'id': self._to_map({'id': node.id}), 'map': self._to_map(attributes), 'label': ':'.join(labels) }) for edge in self.graph.iteredges(): attributes = self.get_attributes(edge) attributes['id'] = edge.id attributes['weight'] = edge.weight cypher = 'MATCH (s { %(source)s }), (t { %(target)s }) ' \ 'MERGE (s)-[:%(type)s { %(map)s }]->(t);\n' self.fh.write( cypher % { 'source': self._to_map({'id': edge.source_id}), 'target': self._to_map({'id': edge.target_id}), 'type': stringcase.constcase(edge.type_name), 'map': self._to_map(attributes), }) self.graph.flush()
def GetJinjaEnvironment(self): def IsOfType(obj, theType): return theType in str(type(obj)) def AddLeadingUnderscore(s: str): return "_%s" % (s) def Privatize(s: str): return AddLeadingUnderscore(stringcase.camelcase(s)) def QuoteIfString(s: str, condition): if condition == 'string' or isinstance(condition, str): return '"%s"' % (s) return s def Enumify(s: str): if s[0].isnumeric(): return "_" + stringcase.constcase(s) return stringcase.constcase(s) if self.jinjaEnvironment is None: env = jinja2.Environment( loader=jinja2.PackageLoader(self.templatePkg, '')) env.filters['UpperCamelCase'] = stringcase.pascalcase env.filters['PascalCase'] = lambda s: stringcase.pascalcase( stringcase.snakecase(s)) env.filters['CONST_CASE'] = lambda s: stringcase.constcase(str(s)) env.filters['snake_case'] = stringcase.snakecase env.filters['camelCase'] = stringcase.camelcase env.filters['type'] = type # For debugging env.filters['quotestring'] = QuoteIfString env.filters['dir'] = dir # For debug env.filters['privatize'] = Privatize env.filters['enumify'] = Enumify env.tests['oftype'] = IsOfType self.jinjaEnvironment = env return self.jinjaEnvironment
def _get_jinja2_environment(self, force=False): def _is_of_type(obj, theType): return theType in str(type(obj)) if force or self._jinja2_environment is None: loader = jinja2.ChoiceLoader(self.loaders) env = jinja2.Environment(loader=loader, extensions=['jinja2.ext.do']) env.filters['UpperCamelCase'] = stringmanip.upper_camel_case env.filters['PascalCase'] = stringmanip.upper_camel_case env.filters['CONST_CASE'] = lambda s: stringcase.constcase(str(s)) env.filters['snake_case'] = stringcase.snakecase env.filters['camelCase'] = stringcase.camelcase env.filters['type'] = type # For debug env.filters['underscore'] = self._add_leading_underscore env.filters['quotestring'] = self._quote_if_string env.filters['dir'] = dir # For debug env.filters['strip'] = self._strip for filter_name, filter_def in self.filters.items(): env.filters[filter_name] = filter_def env.tests['oftype'] = _is_of_type self._jinja2_environment = env return self._jinja2_environment
def GetJinjaEnvironment(self): def IsOfType(obj, theType): return theType in str(type(obj)) def ReferencePointsToObject(ref): val = False if hasattr(ref, 'ref') and hasattr(ref, 'Resolve'): resolved = ref.Resolve() if hasattr(resolved, 'type'): return resolved.type == 'object' return val def Bold(s: str): if s and s is not None and s != 'None' and len(s) > 0: return "**%s**" % (s) else: return '' def Italics(s: str): if s and s is not None and s != 'None' and len(s) > 0: return "_%s_" % (s) else: return '' def CppLineEnd(s: str): s = str(s) if s and s is not None and s != 'None' and len(s) > 0: return "%s;" % (s) else: return '' def BlockQuote(s: str, level=1): lines = str.split("\n") return "\n".join([">" + l for l in lines]) def AddLeadingUnderscore(s: str): return "_%s" % (s) def Privatize(s: str): return AddLeadingUnderscore(stringcase.camelcase(s)) def QuoteIfString(s: str, condition): if condition == 'string' or condition is True or isinstance( condition, str): return '"%s"' % (s) return s def Enumify(s: str): if s[0].isnumeric(): s = '_' + s return stringcase.constcase(s) def Strip(s: str, chars): return s.strip(chars) if self.jinjaEnvironment is None: #env = jinja2.Environment(loader=jinja2.PackageLoader(self.templatePkg, '')) loader = jinja2.ChoiceLoader([ jinja2.PackageLoader(self.templatePkg, ''), jinja2.FileSystemLoader(searchpath="./templates/cpp"), jinja2.PackageLoader('asyncapicodegen.templates.cpp', ''), jinja2.PackageLoader('jsonschemacodegen.templates.cpp', ''), jinja2.PackageLoader('jsonschemacodegen.templates.markdown', ''), ]) env = jinja2.Environment(loader=loader) env.filters['UpperCamelCase'] = stringcase.pascalcase env.filters['PascalCase'] = stringcase.pascalcase env.filters['CONST_CASE'] = lambda s: stringcase.constcase(str(s)) env.filters['snake_case'] = stringcase.snakecase env.filters['camelCase'] = stringcase.camelcase env.filters['bold'] = Bold env.filters['italics'] = Italics env.filters['blockquote'] = BlockQuote env.filters['semicolon'] = CppLineEnd env.filters['type'] = type env.filters['underscore'] = AddLeadingUnderscore env.filters['quotestring'] = QuoteIfString env.filters['dir'] = dir # For debug env.filters['enumify'] = Enumify env.filters['privatize'] = Privatize env.filters['strip'] = Strip env.tests['oftype'] = IsOfType env.tests['refToObj'] = ReferencePointsToObject self.jinjaEnvironment = env return self.jinjaEnvironment
def Enumify(s: str): if s[0].isnumeric(): return "_" + stringcase.constcase(s) return stringcase.constcase(s)
def format_case(enum_case: str) -> str: return stringcase.constcase(enum_case.lower())
if not comment and not line.startswith("%") and "=" in line: m = re.match(r"[ \t]*?([^ \t]*)[ \t]*=[ \t]*([^ \t]*)", line) if m: if reverse: name = m.group(1) value = int(m.group(2), 16) else: name = m.group(2) value = int(m.group(1), 16) if value < 0: str_value = f"{value}" else: str_value = "0x" + f"{value:08x}".upper() if name.upper() != name: name = constcase(name) items.append((name, str_value)) name_max_len = max(len(name), name_max_len) elif "/%" in line: comment = True elif "%/" in line: comment = False # Write a section to the header file for this enum h.write(f"typedef UNK_TYPE {namespace};\n") for (name, value) in items: h.write(f"#define {namespace}_{name.ljust(name_max_len)} {value}\n") h.write("\n") h.write("#endif\n")
def init(self, context: Context) -> None: """ Set Context property and perform validation of the record's data, then initialize any fields or properties that depend on that data. This method may be called multiple times for the same instance, possibly with a different context parameter for each subsequent call. IMPORTANT - Every override of this method must call base.Init() first, and only then execute the rest of the override method's code. """ # Initialize base before executing the rest of the code in this method super().init(context) if self.env_type in [ EnvType.Prod, EnvType.Uat, EnvType.Dev, EnvType.User, EnvType.Test ]: # For all env types except Custom, database name consists of env type in uppercase, # and env group, env name converted from snake_case to PascalCase, with all three # then concatenated with semicolon delimiter env_type_pascal_case: str = stringcase.constcase( self.env_type.name) env_group_pascal_case: str = stringcase.pascalcase(self.env_group) env_name_pascal_case: str = stringcase.pascalcase(self.env_name) self.__db_name: str = ';'.join([ env_type_pascal_case, env_group_pascal_case, env_name_pascal_case ]) elif self.env_type == EnvType.Custom: # For Custom env type, env group must be empty and env name # is database name if self.env_group is not None and self.env_group != '': raise Exception( f'Data source has env_group={self.env_group}, however it' f'must be empty for env_type=Custom.') self.__db_name = self.env_name elif self.env_type == EnvType.Empty: raise Exception('Data source has empty env_type.') else: raise Exception( f'Data source has unknown value of env_type={self.env_type.name}.' ) # Check that database name length does not exceed Mongo limit # to prevent an obscure message from PyMongo about namespace # being not valid db_name_length_in_bytes: int = len(self.__db_name.encode('utf-8')) if db_name_length_in_bytes > MongoDataSource.__max_db_name_length: raise Exception( f'Database name {self.__db_name} has {db_name_length_in_bytes} bytes ' f'which exceeds MongoDB limit of {MongoDataSource.__max_db_name_length} bytes. ' f'Note that the number of bytes may exceed the number of characters for ' f'Unicode strings.') # Check for prohibited symbols if any(x in self.__db_name for x in MongoDataSource.__prohibited_symbols): raise Exception( f'MongoDB database name {self.__db_name} contains a space or another ' f'prohibited character from the following list: /\\.\"$*<>:|?') # Create PyMongo client and database objects. If server is missing use default if self.mongo_server is None: self.__client = MongoClient() else: self.__client = MongoClient(self.mongo_server.split('=', 1)[1]) self.__db = self.__client.get_database(self.__db_name)
def Enumify(s: str): if s[0].isnumeric(): s = '_' + s return stringcase.constcase(s)