Created
August 23, 2022 09:57
-
-
Save dpjanes/592ae09553b9b4a4fed8f0554b6d20bb to your computer and use it in GitHub Desktop.
Rename documents with a datestamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import click | |
import re | |
import time | |
import logging | |
logger = logging.getLogger(__name__) | |
def process_dir(f, depth=0, **av): | |
files = os.listdir(f) | |
for file in files: | |
process(os.path.join(f, file), depth=depth+1, **av) | |
def process_file(f, depth=0, force=False, **av): | |
dirname, basename = os.path.split(f) | |
if basename.startswith("."): | |
logger.debug(f"ignoring dotfile: {f}") | |
return | |
if re.match("^[0-9]{4}-[0-9]{2} ", basename): | |
logger.debug(f"already done: {f}") | |
return | |
try: | |
stbuf = os.stat(f) | |
except IOError: | |
logger.info(f"cannot stat - ignoring: {f}") | |
return | |
yyyy_dd = time.strftime("%Y-%m", time.localtime(stbuf.st_mtime)) | |
dst = os.path.join(dirname, f"{yyyy_dd} {basename}") | |
if not force: | |
logger.info(f"would do: rename {f} to {dst} if --force") | |
return | |
os.rename(f, dst) | |
logger.info(f"{f} → {dst}") | |
once = False | |
def process(f, **av): | |
global once | |
recursive = av["recursive"] | |
depth = av["depth"] | |
dirname, basename = os.path.split(f) | |
if os.path.isdir(f): | |
if not depth: | |
process_dir(f, **av) | |
elif recursive: | |
process_dir(f, **av) | |
elif not once: | |
logger.warning(f"ignoring folder={f} - use --recursive to change") | |
once = True | |
elif os.path.isfile(f): | |
process_file(f, **av) | |
else: | |
logger.warning(f"{f} is not a file or directory") | |
@click.command() | |
@click.argument("inputs", nargs=-1) | |
@click.option("--recursive", is_flag=True) | |
@click.option("--debug", is_flag=True) | |
@click.option("--force", is_flag=True, default=False) | |
def cli(inputs, recursive, debug, force): | |
if debug: | |
logging.basicConfig(level=logging.DEBUG) | |
else: | |
logging.basicConfig(level=logging.INFO) | |
for f in inputs: | |
process(f, recursive=recursive, depth=0, force=force) | |
if __name__ == '__main__': | |
cli(prog_name="DateDocuments") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment