Skip to content

Instantly share code, notes, and snippets.

@filipgorczynski
Created July 11, 2020 05:46
Show Gist options
  • Save filipgorczynski/d99b9391539636e777071cf7ee6e502d to your computer and use it in GitHub Desktop.
Save filipgorczynski/d99b9391539636e777071cf7ee6e502d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from datetime import datetime
import mmap
import os
from stat import *
from colorama import Fore, Style
WHITE = Fore.WHITE
BLACK = Fore.BLACK
GREEN = Fore.GREEN
RED = Fore.RED
LBLUE = Fore.LIGHTBLUE_EX
LCYAN = Fore.LIGHTCYAN_EX
RESET = Style.RESET_ALL
NOTES_DIR = "/home/Notes/"
SCAN_EXT = [".md"]
def run_fast_scandir(dir, ext):
subfolders, files = [], []
for f in os.scandir(dir):
if f.is_dir():
subfolders.append(f.path)
if f.is_file():
if os.path.splitext(f.name)[1].lower() in ext:
files.append(f.path)
for dir in list(subfolders):
sf, f = run_fast_scandir(dir, ext)
subfolders.extend(sf)
files.extend(f)
return subfolders, files
def get_create_stat(md_file):
create_dt = os.path.getctime(md_file)
return datetime.fromtimestamp(int(create_dt)).strftime("%Y%m%d%H%M%S")
def fix_linking(file_name, new_file_name):
_, files = run_fast_scandir(NOTES_DIR, SCAN_EXT)
for md_file in files:
if os.path.getsize(md_file):
with open(md_file, 'rb', 0) as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find(file_name.encode('utf-8')) != -1:
print(WHITE + "Replace {} with {} in file {}".format(file_name, new_file_name, md_file) + RESET)
os.system("sed -i 's/{}/{}/g' {}".format(file_name, new_file_name, md_file))
def change_file_name(md_file):
create_dt = get_create_stat(md_file)
location = md_file.split(os.path.sep)
file_name = location[-1]
path = os.path.sep.join(location[0:-1])
new_file_name = create_dt + '.md'
fix_linking(file_name, new_file_name)
print(
'Rename {} to {}'.format(
RED + os.path.sep.join([path, file_name]),
GREEN + os.path.sep.join([path, new_file_name]) + RESET,
)
)
os.rename(os.path.sep.join([path, file_name]), os.path.sep.join([path, new_file_name]))
def main():
_, files = run_fast_scandir(NOTES_DIR, SCAN_EXT)
for md_file in files:
change_file_name(md_file)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment