Skip to content

Instantly share code, notes, and snippets.

@adoussot
Last active August 9, 2016 22:22
Show Gist options
  • Save adoussot/0cac2e1914876ad631eca9f2da4ad92a to your computer and use it in GitHub Desktop.
Save adoussot/0cac2e1914876ad631eca9f2da4ad92a to your computer and use it in GitHub Desktop.
python script for changing the file case
#!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import
import os
import re
import sys
from os import listdir
from os.path import isdir, join
from tree_struct import TreeStructure
class FileCase:
"""
Change the files/folders Case
"""
def __init__(self, root_path):
self.root_path = root_path
# thanks to that awesome post
# http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case?answertab=active#answer-1176023
self.first_cap_re = re.compile('(.)([A-Z][a-z]+)')
self.all_cap_re = re.compile('([a-z0-9])([A-Z])')
self.tree_struct = TreeStructure(self.root_path)
self.files_pblm = []
self.folders_pblm = []
def get_indices(self, s):
"""
:param arg1:
:type arg1: str
"""
print('s : {}'.format(s))
print(type(s))
return [i for i, c in enumerate(s) if c.isupper()]
def show_errors(self):
"""
Show the files which can't be renamed
"""
if (len(self.folders_pblm) > 0):
print('Some Folders can\'t be renamed :')
for i in self.folders_pblm:
print('\n\t {} '.format(i))
if (len(self.files_pblm) > 0):
print('Some Files can\'t be renamed :')
for i in self.files_pblm:
print('\n\t {} '.format(i))
def camel_to_kebab(self, name):
"""
:param arg1: the name to convert to kebab-case
:type arg1: str
"""
s1 = self.first_cap_re.sub(r'\1-\2', name)
return self.all_cap_re.sub(r'\1-\2', s1).lower()
def camel_to_snake(self, name):
"""
:param arg1: the name to convert to snake-case
:type arg1: str
"""
s1 = self.first_cap_re.sub(r'\1_\2', name)
return self.all_cap_re.sub(r'\1_\2', s1).lower()
def display_struct(self):
"""
display the tree structure from root_path
"""
self.tree_struct.display_tree(1)
def rename_file(self, path, files):
"""
:param arg1: path to the current directory
:param arg2: array of files available at at specific path
:type arg1: str
:type arg2: str[]
"""
for file_ in files:
if (len(self.get_indices(file_)) > 0):
print('camel_to_snake(dir_) {}'.format(self.camel_to_snake(file_)))
try:
os.rename(join(path,file_), join(path, self.camel_to_snake(file_)))
except IOError:
self.files_pblm.append(join(path, file_))
print('\n\n')
def rename_folder(self, path, dirs):
"""
:param arg1: path to the current directory
:param arg2: array of folders available at at specific path
:type arg1: str
:type arg2: str[]
"""
for dir_ in dirs:
if (len(self.get_indices(dir_)) > 0):
print('camel_to_kebab(dir_) {}'.format(self.camel_to_kebab(dir_)))
try:
os.rename(join(path,dir_), join(path, self.camel_to_kebab(dir_)))
except IOError:
self.folders_pblm.append(join(path, dir_))
print('\n\n')
def rename(self, is_rename_folders, is_rename_file):
"""
scan folders recursively from bottom-up
:param arg1: flag represent wheter or not we have to rename folders
:param arg2: flag represent wheter or not we have to rename files
:type arg1: Boolean
:type arg2: Boolean
"""
for root, dirs, files in os.walk(self.root_path, topdown=False):
if (is_rename_folders):
self.rename_folder(root, dirs)
if (is_rename_file):
self.rename_file(root, dirs)
self.show_errors()
if __name__ == "__main__":
# import pdb; pdb.set_trace()
FOLDERS = True
FILES = True
file_case = FileCase(sys.argv[1])
# file_case.display_struct()
file_case.rename(FOLDERS, FILES)
#!/usr/bin/env python3
# coding: utf-8
import os
class TreeStructure:
"""
Display tree structure
"""
# thanks to that awesome post
# http://codereview.stackexchange.com/questions/62123/tree-utility-in-python#answer-112778
def __init__(self, path, print_hidden=False, max_depth=100):
self.path = path
self.FOLDER_PATTERN = ['| ', ' ']
self.FILE_PATTERN = ['|-- ', '`-- ']
self.print_hidden = print_hidden
self.max_depth = max_depth
self.parent_folders = []
def display_tree(self, depth):
"""
:param arg1: maximum depth to scan
:type arg1: int
"""
file_count, directory_count = 0, 0
files = sorted((os.path.join(self.path, filename)
for filename in os.listdir(self.path)
if self.print_hidden or not filename.startswith('.')),
key=lambda s: s.lower())
files_count = len(files)
for i, filepath in enumerate(files, start = 1):
print('{}{}{}'.format(
''.join(self.FOLDER_PATTERN[folder] for folder in self.parent_folders),
self.FILE_PATTERN[i == files_count],
os.path.basename(filepath)))
# Recurse if we find a new subdirectory
if os.path.isdir(filepath) and depth < self.max_depth:
# Append whether current directory is last in current list or not
self.parent_folders.append(i == files_count)
# Print subdirectory and get numbers
self.path = os.path.join(filepath)
subdir_file_count, subdir_directory_count = \
self.display_tree(depth+1)
# Back in current directory, remove the newly added directory
self.parent_folders.pop()
# Update counters
file_count += subdir_file_count
directory_count += subdir_directory_count + 1
elif os.path.isdir(filepath):
directory_count += 1
else:
file_count += 1
return file_count, directory_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment