Skip to content

Instantly share code, notes, and snippets.

@QinMing
Last active December 14, 2020 04:06
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 QinMing/145d8ae792f92d57f523f0d9a3a7a2d1 to your computer and use it in GitHub Desktop.
Save QinMing/145d8ae792f92d57f523f0d9a3a7a2d1 to your computer and use it in GitHub Desktop.
Set the correct line ending, either CRLF or LF, for a directory tree
#!/usr/bin/env python3
#
# Sample Usage:
# <command> '.*\.html'
import logging
import os
import re
from argparse import ArgumentParser
logging.basicConfig(format='%(asctime)-15s %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__file__)
def discover_and_process(pattern: str):
for current_dir, dirs, files in os.walk('.'):
for name in files:
if re.match(pattern, name):
path = os.path.join(current_dir, name)
process_file(path)
logger.info("finished")
def process_file(path: str):
with open(path, 'r') as f:
text = f.read()
# Python `open` will set the end-of-line characters correctly
with open(path, 'w') as f:
f.write(text)
logger.info('Changed %s', path)
def main():
parser = ArgumentParser()
parser.add_argument('pattern', type=str, help='Regex pattern for file names')
args = parser.parse_args()
logger.info('Arguments = %s', args)
pattern = args.pattern
discover_and_process(pattern)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment