Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save migliori/afc9ac58c995f7a24134a6a599ddd3f9 to your computer and use it in GitHub Desktop.
Save migliori/afc9ac58c995f7a24134a6a599ddd3f9 to your computer and use it in GitHub Desktop.
untitled #python #snake_case #smallCamelCase
###
# This script converts $my_variable (snake_case) to $myVariable (smallCamelCase) in the given file or in the given folder and all its subfolders recursively.
import os
import re
def snake_to_camel(snake_str):
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])
def convert_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
pattern = re.compile(r'(\$[a-zA-Z]+(?:_[a-zA-Z]+)+|\->[a-zA-Z]+(?:_[a-zA-Z]+)+)')
matches = pattern.findall(content)
if matches:
print(f"Converting variables and properties in: {file_path}")
unique_matches = set(matches)
for match in unique_matches:
if match.startswith('$row->'):
continue
if match.startswith('->'):
camel_case = '->' + snake_to_camel(match[2:])
else:
camel_case = '$' + snake_to_camel(match[1:])
content = content.replace(match, camel_case)
with open(file_path, 'w', encoding='utf-8', newline='\n') as file:
file.write(content)
except Exception as e:
print(f"Error processing {file_path}: {e}")
def convert_folder(folder_path):
skip_folders = ['vendor', 'registration', 'plugins']
for root, dirs, files in os.walk(folder_path):
if any(skip_folder in root.split(os.sep) for skip_folder in skip_folders):
continue
print(f"Entering folder: {root}")
for file in files:
if file.endswith('.php'):
file_path = os.path.join(root, file)
print(f"Processing file: {file_path}")
convert_file(file_path)
def convert(path):
if os.path.isdir(path):
convert_folder(path)
elif os.path.isfile(path):
convert_file(path)
else:
print(f"The path {path} is not a valid file or directory.")
# Example usage
path = 'C:\\path\to\file.php'
# or path = 'C:\\path\to\folder'
convert(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment