Skip to content

Instantly share code, notes, and snippets.

@bohdon
Created July 3, 2021 00:11
Show Gist options
  • Select an option

  • Save bohdon/3dbbcb5c7b9f46498fe52cd439432e5c to your computer and use it in GitHub Desktop.

Select an option

Save bohdon/3dbbcb5c7b9f46498fe52cd439432e5c to your computer and use it in GitHub Desktop.
A util for verifying and applying case consistency for local files and folders in a perforce workspace
#! python
"""
Util for verifying that the case of local files and folders
matches the case of files synced from perforce.
"""
import click
import yaml
import os
import P4
@click.command()
@click.argument('root_path')
@click.argument('target_paths')
@click.option('-y', is_flag=True)
def main(root_path=None, target_paths=None, y=False):
print('Connecting to p4...')
p4 = P4.P4()
p4.connect()
print(f'Connection established: {p4}')
with open(target_paths, 'rb') as fp:
target_paths_dict = yaml.safe_load(fp)
abs_root_path = os.path.abspath(root_path)
apply_case_consistency(abs_root_path, target_paths_dict, dry_run=not y)
def normpath(path):
return path.replace('\\', '/')
def apply_case_consistency(root_path, target_paths, dry_run=True):
"""
Update local file and folder names to match the case
of the given set of paths.
Args:
root_path (str): Local root path of files and folders to rename
target_paths (list of str): List of paths with the target cases to apply
"""
target_paths_dict = {path.lower(): path for path in target_paths}
for dirpath, dirnames, filenames in os.walk(root_path):
for base_name in dirnames + filenames:
full_path = normpath(os.path.join(dirpath, base_name))
rel_path = normpath(os.path.relpath(full_path, root_path))
lower_path = rel_path.lower()
if lower_path in target_paths_dict:
new_rel_path = target_paths_dict[lower_path]
new_base_name = os.path.basename(new_rel_path)
if base_name != new_base_name:
# base name case is different
new_full_path = normpath(os.path.join(root_path, new_rel_path))
print(f'{full_path} -> {new_full_path}')
if not dry_run:
try:
os.rename(full_path, new_full_path)
except PermissionError as e:
print('Failed to rename: %s' % e)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment