dirnotes-cli is working pretty well; copy the library code from -cli to the other two

This commit is contained in:
2022-11-01 17:54:22 -04:00
parent 4523c13c0f
commit de894e57bf
5 changed files with 708 additions and 325 deletions
+77 -68
View File
@@ -4,6 +4,8 @@
# TODO: re-read date/author to xattr after an edit
# TODO: consider adding h,j,k,l movement
# TODO: change move command to 'v', change mode to 'm', drop copy-comments
# TODO: bug: enter db mode, type E to edit a comment, we get the xattr version!!
# TODO: try to clear a comment, left with ' '
# scroll
# up/down - change focus, at limit: move 1 line,
@@ -22,16 +24,13 @@ import curses, sqlite3, curses.textpad
import logging, getpass, argparse
import json
VERSION = "1.8"
VERSION = "1.9"
# these may be different on MacOS
xattr_comment = "user.xdg.comment"
xattr_author = "user.xdg.comment.author"
xattr_date = "user.xdg.comment.date"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
# convert the ~/ form to a fully qualified path
# database_name = "~/.dirnotes.db"
mode_names = {"db":"<Database mode> ","xattr":"<Xattr mode>"}
modes = ("db","xattr")
mode = "db"
@@ -191,8 +190,8 @@ class Pane:
self.file_pad.addstr(y,self.sep1,UiHelper.getShortSize(f))
self.file_pad.addstr(y,self.sep2,UiHelper.getShortDate(f.date))
comment = f.getComment() or ''
other = f.getOtherComment() or ''
comment = f.getComment(mode) or ''
other = f.getOtherComment(mode) or ''
logging.info(f"file_line, comments are <{comment}> and <{other}> differ_flag:{self.some_comments_differ}")
if comment == other:
self.file_pad.addnstr(y,self.sep3,comment,self.w-self.sep3-2)
@@ -286,20 +285,22 @@ class Files():
def sortSize(a):
if a.getDisplayName() == '../':
return 0
return -2
if a.isDir() or a.isLink() or a.isSock():
return -1
return a.getSize()
def sortComment(a):
return a.getComment()
return a.getComment(mode) or '~'
sort_mode = sortName
sortFunc = sortName
def sort(self):
self.files.sort(key = Files.sort_mode)
self.files.sort(key = Files.sortFunc)
def getCurDir(self):
return self.directory
def getMasterComment(self):
return self.directory.getComment()
return self.directory.getComment(mode)
## accessors ##
def __len__(self):
@@ -409,7 +410,7 @@ class UiHelper:
now = time.time()
diff = now - longDate
if diff > YEAR:
fmt = "%b %e %Y"
fmt = "%b %e %Y"
else:
fmt = "%b %e %H:%M"
return time.strftime(fmt, time.localtime(longDate))
@@ -438,16 +439,18 @@ class FileObj:
if not self.displayName.endswith('/'):
self.displayName += '/'
self.date = self.stat.st_mtime
self.size = self.stat.st_size
self.size = self.stat.st_size
self.db = db
def getName(self):
""" returns the absolute pathname """
return self.fileName
def getDisplayName(self):
""" returns just this basename of the file; dirs end in / """
return self.displayName
# new methods; no caching
def getDbData(self):
""" returns (comment, author, comment_date) """
if not hasattr(self,'dbCommentAuthorDate'):
cad = self.db.execute("select comment, author, comment_date from dirnotes where name=? order by comment_date desc",(self.fileName,)).fetchone()
self.dbCommentAuthorDate = cad if cad else (None, None, None)
@@ -456,6 +459,7 @@ class FileObj:
return self.getDbData()[0]
def getXattrData(self):
""" returns (comment, author, comment_date) """
if not hasattr(self,'xattrCommentAuthorDate'):
c = a = d = None
try:
@@ -507,13 +511,15 @@ class FileObj:
errorBox("is this a VFAT or EXFAT volume? these don't allow comments")
return False
def getComment(self):
def getComment(self,mode):
return self.getDbComment() if mode == "db" else self.getXattrComment()
def getOtherComment(self):
def getOtherComment(self,mode):
return self.getDbComment() if mode == "xattr" else self.getXattrComment()
def getData(self):
def getData(self,mode):
""" returns (comment, author, comment_date) """
return self.getDbData() if mode == "db" else self.getXattrData()
def getOtherData(self):
def getOtherData(self,mode):
""" returns (comment, author, comment_date) """
return self.getDbData() if mode == "xattr" else self.getXattrData()
def getDate(self):
@@ -533,18 +539,33 @@ class FileObj:
if stat.S_ISREG(self.stat.st_mode):
dest = os.path.join(destDir,self.displayName)
try:
print("try copy from",self.fileName,"to",dest)
print_v("try copy from",self.fileName,"to",dest)
shutil.copy2(self.fileName, dest)
except:
errorBox(f"file copy to <{dest}> failed; check permissions")
return
f = FileObj(dest, self.db)
print("dest object created",repr(f))
f.setDbComment(self.getDbComment())
########## dest folder picker ###############
def moveFile(self, destDir):
# NOTE: this method moves the xattr (comment + old author + old date)
# but creates new db (comment + this author + new date)
src = self.fileName
dest = os.path.join(destDir, self.displayName)
# move preserves dates & chmod/chown & xattr
print_v(f"move from {self.fileName} to {destDir}")
try:
shutil.move(src, dest)
except:
ErrorBox(f"file move to <{dest}> failed; check permissions")
return
# and copy the database record
f = FileObj(dest,files.db)
f.setDbComment(self.getDbComment())
########## dest directory picker ###############
# returns None if the user hits <esc>
# the dir_pad contents are indexed from 0,0, matching self.fs
class showFolderPicker:
class showDirectoryPicker:
def __init__(self,starting_dir,title):
self.selected = None
self.title = title
@@ -744,11 +765,11 @@ Comments detail:
def show_detail(f):
global mode
h = paint_dialog(COLOR_HELP,detail_string)
c,a,d = f.getData() # get all three, depending on the current mode
c,a,d = f.getData(mode) # get all three, depending on the current mode
h.addstr(1,20,"from xattrs" if mode=="xattr" else "from database")
h.addnstr(2,12,c,h.getmaxyx()[1]-13)
h.addstr(3,12,a if a else "<not set>")
h.addstr(4,12,d if d else "<not set>")
h.addnstr(2,12,c or "<not set>",h.getmaxyx()[1]-13)
h.addstr(3,12,a or "<not set>")
h.addstr(4,12,d or "<not set>")
h.refresh()
c = h.getch()
del h
@@ -807,13 +828,13 @@ def main(w, cwd, database_file, start_file):
elif c == CMD_SORT:
c = show_sort()
if c == ord('s') or c == ord('S'):
Files.sort_mode = Files.sortSize
Files.sortFunc = Files.sortSize
elif c == ord('n') or c == ord('N'):
Files.sort_mode = Files.sortName
Files.sortFunc = Files.sortName
elif c == ord('d') or c == ord('D'):
Files.sort_mode = Files.sortDate
Files.sortFunc = Files.sortDate
elif c == ord('c') or c == ord('C'):
Files.sort_mode = Files.sortComment
Files.sortFunc = Files.sortComment
files.sort()
mywin.refill()
mywin.refresh()
@@ -849,7 +870,7 @@ def main(w, cwd, database_file, start_file):
f = files[mywin.cursor]
if f.isDir():
cwd = f.getName()
logging.info(f"CD change to {cwd}")
print_v(f"CD change to {cwd}")
files = Files(cwd,db)
mywin = Pane(w,cwd,files)
# TODO: should this simply re-fill() the existing Pane instead of destroy?
@@ -915,43 +936,29 @@ def main(w, cwd, database_file, start_file):
mywin.refresh()
elif c == CMD_COPY:
if files[mywin.cursor].displayName == "..":
if files[mywin.cursor].getDisplayName() == "../":
continue
if os.path.isdir(files[mywin.cursor].fileName):
errorBox(f"<{files[mywin.cursor].displayName}> is a directory. Copy not allowed")
continue
dest_dir = showFolderPicker(cwd,"Select folder for copy").value()
if dest_dir:
#errorBox(f"copy cmd to {dest_dir}")
src = cwd + '/' + files[mywin.cursor].displayName
dest = dest_dir + '/' + files[mywin.cursor].displayName
# copy2 preserves dates & chmod/chown & xattr
logging.info(f"copy from {src} to {dest_dir}")
shutil.copy2(src, dest_dir)
# and copy the database record
f = FileObj(dest,files.db)
f.setDbComment(files[mywin.cursor].getDbComment())
if files[mywin.cursor].isDir():
errorBox(f"<{files[mywin.cursor].getDisplayName()}> is a directory. Copy not allowed")
else:
dest_dir = showDirectoryPicker(cwd,"Select folder for copy").value()
if dest_dir:
files[mywin.cursor].copyFile(dest_dir)
mywin.refresh()
elif c == CMD_MOVE:
if files[mywin.cursor].displayName == "..":
if files[mywin.cursor].getDisplayName() == "../":
continue
if os.path.isdir(files[mywin.cursor].fileName):
errorBox(f"<{files[mywin.cursor].displayName}> is a directory. Move not allowed")
continue
dest_dir = showFolderPicker(cwd,"Select folder for move").value()
if dest_dir:
#errorBox(f"move cmd to {dest_dir}")
src = cwd + '/' + files[mywin.cursor].displayName
dest = dest_dir + '/' + files[mywin.cursor].displayName
# move preserves dates & chmod/chown & xattr
logging.info(f"move from {src} to {dest_dir}")
shutil.move(src, dest_dir)
# and copy the database record
f = FileObj(dest,files.db)
f.setDbComment(files[mywin.cursor].getDbComment())
files = Files(cwd,db)
mywin = Pane(w,cwd,files) # is this the way to refresh the main pane? TODO
if files[mywin.cursor].isDir():
errorBox(f"<{files[mywin.cursor].getDisplayName()}> is a directory. Move not allowed")
else:
dest_dir = showDirectoryPicker(cwd,"Select folder for move").value()
if dest_dir:
files[mywin.cursor].moveFile(dest_dir)
files = Files(cwd,db)
mywin = Pane(w,cwd,files) # is this the way to refresh the main pane? TODO
mywin.refresh() # to clean up the errorBox or FolderPicker
elif c == curses.KEY_RESIZE:
mywin.resize()
@@ -965,12 +972,17 @@ def pre_main():
parser = argparse.ArgumentParser(description="Add comments to files")
parser.add_argument('-c','--config', dest='config_file', help="config file (json format)")
parser.add_argument('-v','--version', action='version', version=f"dirnotes ver:{VERSION}")
parser.add_argument('-d','--db', action='store_true',help="start up in database mode")
parser.add_argument('-x','--xattr', action='store_true',help="start up in xattr mode")
parser.add_argument('directory', type=str, default='.', nargs='?', help="directory or file to start")
args = parser.parse_args()
logging.info(args)
config = ConfigLoader(args.config_file or DEFAULT_CONFIG_FILE)
if args.db:
config.mode = "db"
if args.xattr:
config.mode = "xattr"
# print(repr(config))
# print("start_mode",config["start_mode"])
@@ -992,7 +1004,4 @@ else:
curses_running = True
curses.wrapper(main, cwd or '.', database_name, start_file)
# dirnotes database is name, date, size, comment, comment_date, author
# symlinks: follow_symlinks should always be True, because symlinks in Linux
# can't have xattr....it appears to be the same in darwin