Skip to content

Instantly share code, notes, and snippets.

@muthugit
Created October 13, 2020 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muthugit/c8f34e7b2831a1f758ffbcf89bd5d59c to your computer and use it in GitHub Desktop.
Save muthugit/c8f34e7b2831a1f758ffbcf89bd5d59c to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python
# coding: utf-8
__author__ = 'muthugit'
# Importing system libraries
import sys
import ast
import re
variables = []
class Camel_to_Snake:
"""Convert all camelCase variables & arguments to snake_case
:param file_path: A valid file path of the python file
:type file_path: String
:returns: Formatted code
:rtype: String
"""
def __init__(self, file_path):
self.file_path = file_path
self.vars = []
with open(file_path, 'r') as file:
self.content = file.read()
self.convert()
def __case_converter(self, str):
"""Converting any uppercase in a string to snakecase format"""
return ''.join(['_'+i.lower() if i.isupper()
else i for i in str]).lstrip('_')
def convert(self):
"""Main function"""
p = ast.parse(self.content)
print("===== ORIGINAL CODE =====")
print(self.content)
code = p.body
self.fetch_vars(code)
print(set(self.vars))
return self.apply_to_code()
def apply_to_code(self):
"""Apply the converted variables to the existing code"""
for var in self.vars:
new_case = self.__case_converter(var)
self.content = re.sub(r"\b{}\b".format(var),
new_case, self.content)
self.new_code = self.content
return self.content
def fetch_vars(self, code):
"""Fetching variables & args from the code string
:param code: The CODE string
:type code: String
:returns: List of variables
:rtype: list
"""
for cc in code:
if 'targets' in cc.__dict__:
# Targets -> Variables
for target in cc.__dict__['targets']:
self.vars.append(target.__dict__['id'])
elif 'name' in cc.__dict__:
# Name -> Name of Class or function
self.vars.append(cc.__dict__['name'])
if 'args' in cc.__dict__:
# If function contains any arguments consider as variables
print("{} function with args: {}".format(
cc.__dict__['name'],
cc.__dict__['args'].__dict__))
for arg in cc.__dict__['args'].__dict__['args']:
self.vars.append(arg.__dict__['arg'])
if 'body' in cc.__dict__:
# Recursive the fetch_vars
self.fetch_vars(cc.__dict__['body'])
else:
# Not a function/variable/class
print(cc.__dict__) # Skip this for conversion
return self.vars
if __name__ == "__main__":
obj = Camel_to_Snake('testfn.py')
print(obj.new_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment