46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
# auto remove unuse img
|
|
from pathlib import Path
|
|
import argparse
|
|
import chardet
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# get opt
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("file", help="specifi the markdown file", type=str)
|
|
parser.add_argument("-a", "--assets", help="specifi the img dir", type=str)
|
|
args = parser.parse_args()
|
|
|
|
if args.assets:
|
|
img_dir = Path(args.assets)
|
|
else:
|
|
img_dir = Path(args.file).with_suffix('.assets')
|
|
|
|
with open(args.file, 'rb') as file:
|
|
result = chardet.detect(file.read())
|
|
print("{} encoding is {}, confidence: {}".format(args.file, result['encoding'], result['confidence']))
|
|
with open(args.file, 'r', encoding=result['encoding']) as file:
|
|
content = file.read()
|
|
|
|
img_list = list(img_dir.glob('**/*'))
|
|
unuse_img_list = []
|
|
for file_name in img_list:
|
|
img_name = Path(file_name).name
|
|
if img_name not in content:
|
|
print("img:{}".format(img_name))
|
|
unuse_img_list.append(file_name)
|
|
|
|
if len(unuse_img_list) == 0:
|
|
print("not find unuse img file")
|
|
else:
|
|
print("find {} unuse img files:".format(len(unuse_img_list)))
|
|
for file_name in unuse_img_list:
|
|
print("{}".format(file_name))
|
|
usr_input = input("would you want to delete them?(y or n):")
|
|
if usr_input == "y":
|
|
for file_name in unuse_img_list:
|
|
print("delete {}".format(file_name))
|
|
Path(file_name).unlink()
|
|
else:
|
|
print("unused img will not remove!")
|