All three apps updated with newest library.

Database is now at ~/.local/share/dirnotes/dirnotes.db
and the config is at ~/.config/dirnotes/dirnotes.conf
Fixed double-write in dirnotes (gui) (it was re-entering .change())
This commit is contained in:
2022-11-02 00:01:38 -04:00
parent de894e57bf
commit 62027a2729
4 changed files with 157 additions and 129 deletions
+47 -40
View File
@@ -79,7 +79,7 @@ now = time.time()
YEAR = 3600*24*365
verbose = None
def print_v(*a):
def print_d(*a):
if verbose:
print(*a)
@@ -324,17 +324,19 @@ def errorBox(string):
print(string)
time.sleep(3)
############# the dnDataBase, UiHelper and FileObj code is shared with other dirnotes programs
# >>> snip here <<<
#============ the DnDataBase, UiHelper and FileObj code is shared with other dirnotes programs
import getpass, time, stat, shutil
DEFAULT_CONFIG_FILE = "~/.dirnotes.conf"
DEFAULT_CONFIG_FILE = "~/.config/dirnotes/dirnotes.conf" # or /etc/dirnotes.conf
# config
# we could store the config in the database, in a second table
# or in a .json file
DEFAULT_CONFIG = {"xattr_tag":"user.xdg.comment",
"database":"~/.dirnotes.db",
"database":"~/.local/share/dirnotes/dirnotes.db",
"start_mode":"xattr",
"options for database":("~/.dirnotes.db","/etc/dirnotes.db"),
"options for database":("~/.local/share/dirnotes/dirnotes.db","~/.dirnotes.db","/etc/dirnotes.db"),
"options for start_mode":("db","xattr")
}
@@ -351,6 +353,7 @@ class ConfigLoader: # singleton
errorBox(f"config file {configFile} not found; using the default settings")
config = DEFAULT_CONFIG
try:
os.makedirs(os.path.dirname(configFile),exist_ok = True)
with open(configFile,"w") as f:
json.dump(config,f,indent=4)
except:
@@ -371,7 +374,7 @@ class DnDataBase:
this object: 1) finds or creates the database
2) determine if it's readonly
TODO: the database is usually associated with a user, in $XDG_DATA_HOME (~/.local/share/)
TODO: the database is usually associated with a user, in $XDG_DATA_HOME (~/.local/share/)
TODO: if the database is not found, create it in $XDG_DATA_DIRS (/usr/local/share/)
make it 0666 permissions (rw-rw-rw-)
'''
@@ -380,16 +383,21 @@ class DnDataBase:
try:
self.db = sqlite3.connect(dbFile)
except sqlite3.OperationalError:
logging.error(f"Database {dbFile} not found")
raise
# create new database if it doesn't exist
print_d(f"Database {dbFile} not found")
try:
os.makedirs(os.path.dirname(dbFile), exist_ok = True)
self.db = sqlite3.connect(dbFile)
except (sqlite3.OperationalError, PermissionError):
printd(f"Failed to create {dbFile}, aborting")
raise
# create new table if it doesn't exist
try:
self.db.execute("select * from dirnotes")
except sqlite3.OperationalError:
print_v(f"Table dirnotes created")
self.db.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME, author TEXT)")
self.db.execute("create index dirnotes_i on dirnotes(name)")
print_d(f"Table dirnotes created")
# at this point, if a shared database is required, somebody needs to set perms to 0o666
self.writable = True
@@ -398,6 +406,7 @@ class DnDataBase:
except sqlite3.OperationalError:
self.writable = False
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
class UiHelper:
@staticmethod
def epochToDb(epoch):
@@ -446,7 +455,7 @@ class FileObj:
""" returns the absolute pathname """
return self.fileName
def getDisplayName(self):
""" returns just this basename of the file; dirs end in / """
""" returns just the basename of the file; dirs end in / """
return self.displayName
def getDbData(self):
@@ -480,18 +489,18 @@ class FileObj:
# return
s = os.lstat(self.fileName)
try:
print_v(f"setDbComment db {self.db}, file: {self.fileName}")
print_d(f"setDbComment db {self.db}, file: {self.fileName}")
self.db.execute("insert into dirnotes (name,date,size,comment,comment_date,author) values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'),?)",
(self.fileName, s.st_mtime, s.st_size,
str(newComment), time.time(), getpass.getuser()))
self.db.commit()
self.dbCommentAuthorDate = newComment, getpass.getuser(), UiHelper.epochToDb(time.time())
except sqlite3.OperationalError:
print_v("database is locked or unwritable")
print_d("database is locked or unwritable")
errorBox("the database that stores comments is locked or unwritable")
def setXattrComment(self,newComment):
print_v(f"set comment {newComment} on file {self.fileName}")
print_d(f"set comment {newComment} on file {self.fileName}")
try:
os.setxattr(self.fileName,xattr_comment,bytes(newComment,'utf8'),follow_symlinks=False)
os.setxattr(self.fileName,xattr_author,bytes(getpass.getuser(),'utf8'),follow_symlinks=False)
@@ -505,21 +514,22 @@ class FileObj:
elif self.isSock():
errorBox("Linux does not allow comments on sockets; comment is stored in database")
elif os.access(self.fileName, os.W_OK)!=True:
errorBox("you don't appear to have write permissions on this file")
errorBox(f"you don't appear to have write permissions on this file: {self.fileName}")
# change the listbox background to yellow
elif "Errno 95" in str(e):
errorBox("is this a VFAT or EXFAT volume? these don't allow comments")
return False
def getComment(self,mode):
""" returns the comment for the given mode """
return self.getDbComment() if mode == "db" else self.getXattrComment()
def getOtherComment(self,mode):
return self.getDbComment() if mode == "xattr" else self.getXattrComment()
def getData(self,mode):
""" returns (comment, author, comment_date) """
""" returns (comment, author, comment_date) for the given mode """
return self.getDbData() if mode == "db" else self.getXattrData()
def getOtherData(self,mode):
""" returns (comment, author, comment_date) """
""" returns (comment, author, comment_date) for the 'other' mode """
return self.getDbData() if mode == "xattr" else self.getXattrData()
def getDate(self):
@@ -533,34 +543,31 @@ class FileObj:
def isSock(self):
return stat.S_ISSOCK(self.stat.st_mode)
def copyFile(self, destDir):
def copyFile(self, dest, doMove = False):
""" dest is either a FQ filename or a FQ directory, to be expanded with same basename """
# NOTE: this method copies the xattr (comment + old author + old date)
# but creates new db (comment + this author + new date)
if stat.S_ISREG(self.stat.st_mode):
if os.path.isdir(dest):
dest = os.path.join(destDir,self.displayName)
try:
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)
f.setDbComment(self.getDbComment())
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)
print_d("try copy from",self.fileName,"to",dest)
# shutil methods preserve dates & chmod/chown & xattr
if doMove:
shutil.move(self.fileName, dest)
else:
shutil.copy2(self.fileName, dest)
# can raise FileNotFoundError, Permission Error, shutil.SameFileError, IsADirectoryError
except:
ErrorBox(f"file move to <{dest}> failed; check permissions")
errorBox(f"file copy/move to <{dest}> failed; check permissions")
return
# and copy the database record
f = FileObj(dest,files.db)
f.setDbComment(self.getDbComment())
f = FileObj(dest, self.db)
f.setDbComment(self.getDbComment())
def moveFile(self, dest):
""" dest is either a FQ filename or a FQ directory, to be expanded with same basename """
self.copyFile(dest, doMove = True)
# >>> snip here <<<
########## dest directory picker ###############
# returns None if the user hits <esc>
@@ -870,7 +877,7 @@ def main(w, cwd, database_file, start_file):
f = files[mywin.cursor]
if f.isDir():
cwd = f.getName()
print_v(f"CD change to {cwd}")
print_d(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?