Skip to content

Instantly share code, notes, and snippets.

@alpsayin
Last active April 3, 2021 13:21
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 alpsayin/00f476307b2e44562d5e632cd3fe5302 to your computer and use it in GitHub Desktop.
Save alpsayin/00f476307b2e44562d5e632cd3fe5302 to your computer and use it in GitHub Desktop.
from pathlib import Path
from argparse import ArgumentParser
from typing import Tuple, List
from datetime import datetime
g_max_depth_traversed = 0
g_last_mtime = 0
def format_mtime(mtime: int) -> str:
return datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')
def safe_stat_mtime(path: Path) -> float:
try:
return path.stat().st_mtime
except Exception as ex:
print(ex)
return 0
def safe_is_file(path: Path) -> bool:
try:
return path.is_file()
except Exception as ex:
print(ex)
return False
def safe_is_dir(path: Path) -> bool:
try:
return path.is_dir()
except Exception as ex:
print(ex)
return False
def safe_iterdir(path: Path) -> List[Path]:
try:
return list(path.iterdir())
except Exception as ex:
print(ex)
return []
def recursive_scan(path: Path, max_depth: int) -> Tuple[Path, int]:
global g_max_depth_traversed, g_last_mtime
last_mtime_path = path
last_mtime = safe_stat_mtime(path)
if safe_is_file(path) or max_depth < 0:
return (last_mtime_path, last_mtime)
if max_depth < g_max_depth_traversed:
g_max_depth_traversed = max_depth
for child in safe_iterdir(path):
child_mtime = 0
if safe_is_file(child):
lm_child = child
child_mtime = safe_stat_mtime(path)
if safe_is_dir(child):
lm_child, child_mtime = recursive_scan(path=child, max_depth=max_depth - 1)
if child_mtime > last_mtime:
last_mtime = child_mtime
last_mtime_path = lm_child
if last_mtime > g_last_mtime:
print(f'Found later mtime {format_mtime(last_mtime)} in "{child}"')
g_last_mtime = last_mtime
return (last_mtime_path, last_mtime)
def main():
global g_max_depth_traversed, g_last_mtime
parser = ArgumentParser(description='Recursively scans a directory to find the real last modified date')
parser.add_argument('-t', '--target', type=Path, default=Path('.'), help='Target directory to recursively scan')
parser.add_argument('-d', '--max-depth', type=int, default=16, help='Maximum recursion depth to scan')
args = parser.parse_args()
kwargs = vars(args)
print(f'Target directory is {kwargs["target"].absolute()}')
print(f'Max recursion depth is {kwargs["max_depth"]}')
g_max_depth_traversed = kwargs['max_depth']
g_last_mtime = safe_stat_mtime(kwargs["target"])
print(f'Parent mtime is {format_mtime(g_last_mtime)}')
last_mtime_path, last_mtime = recursive_scan(path=kwargs['target'], max_depth=kwargs['max_depth'])
print(f'Latest mtime is {format_mtime(last_mtime)} in "{last_mtime_path}"')
print(f'Max depth traversed is {kwargs["max_depth"]-g_max_depth_traversed}')
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment