Files
dirnotes/cleanup.py
T

83 lines
2.7 KiB
Python
Raw Normal View History

2022-08-30 16:29:44 -04:00
#!/usr/bin/python3
""" Maintenance up the database used by dirnotes and c_dirnotes
- view the history of file comments
- delete the history of file comments
"""
import sqlite3, os, sys
import logging
VERSION = "0.1"
dbname = "~/.dirnotes.db"
dbname = os.path.expanduser(dbname)
def main(summary, view, delete):
try:
d = sqlite3.connect(dbname)
except sqlite3.OperationalError:
print("database not found, or permission-locked; cleanup aborted")
return
c = d.cursor()
if summary:
c = d.cursor()
total,distinct = c.execute("select count(name),count(distinct name) from dirnotes;").fetchone()
print(f"this database has entries for {distinct} files, and {total-distinct} history entries")
if view or delete:
c.execute("select distinct name from dirnotes;")
for f in c:
# note, f is a tuple of (name,)
c1 = d.cursor()
if view:
history = c1.execute("select comment_date,author,comment from dirnotes where name=? order by comment_date desc",f).fetchall()
if len(history)>1:
print(f"filename: {f[0]} has a history of comments:")
first = True
for lin in history:
print(f"{'->' if first else ' '} date: {lin[0]} author: {lin[1]}\n comment: {lin[2]}")
first = False
if delete:
most_recent = c1.execute("select comment_date from dirnotes where name=? order by comment_date desc",f).fetchone()[0]
logging.info(f"working on file: {f} with most-recent-date of {most_recent}")
c1.execute("delete from dirnotes where name=? and comment_date <> ?",(f[0],most_recent))
if delete:
total,distinct = c.execute("select count(name),count(distinct name) from dirnotes;").fetchone()
print(f"this database has been cleaned to {distinct} files, and {total-distinct} history entries")
d.commit()
d.close()
view = False
delete = False
summary = True # default
if __name__ == "__main__":
logging.basicConfig(filename="/tmp/dirnotes_clear.log", level=logging.DEBUG)
logging.info("starting the db mainenance tool")
if len(sys.argv)>1:
if "-h" in sys.argv or "--help" in sys.argv:
print(f"Usage: {sys.argv[0]} maintenance for the database used by dirnotes & c_dirnotes")
print(" -d delete comment history")
print(" -s view comment summary")
print(" -v view comment history")
sys.exit(1)
if "-v" in sys.argv:
view = True
if "-s" in sys.argv:
summary = True
if "-d" in sys.argv:
delete = True
if delete:
print("Cleanup of the dirnotes database located at ~/.dirnotes.db")
c = input("Proceed? (Y/N)")
if c in ("yY"):
main(summary, view, delete)
else:
print("nothing done")
else:
main(summary, view, delete)