diff --git a/README.md b/README.md
index e8851b5..e6d6e63 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,8 @@ _s_ for sort, _M_ to change between xattr/database priority.
The **dirnotes-cli** has options for _-l_ list and _-c_ create a comment.
+All three apps in the **dirnotes** family have the ability to copy files from the current directory.
+
## INSTALLATION
Each of the 3 apps in the family is self contained.
@@ -55,6 +57,7 @@ This is a JSON file, with three attributes that are important:
> * database (default: ~/.dirnotes.db)
> * start_mode (_xattr_ or _db_ priority)
+The _config_file_ should be auto-generated the first time one of the **dirnotes** apps is run.
[_not fully implemented_]
## LIMITATIONS
@@ -62,12 +65,13 @@ This is a JSON file, with three attributes that are important:
The file comments are located in two locations: a database, and in the
xattr properties of the file. Each of these storage locations has its
-own benefits and limitations:
+own benefits and limitations. These can be summed up: **_xattr_** comments
+follow the iNode, **_database_** comments follow the file name.
### xattr
Comments stored in the xattr properties can be copied/moved with the file, if you
-use the correct options for **cp**. The **mv** utility
+use the correct options: **cp -p**. The **mv** utility
automatically preserves _xattr_. Other programs can also be coerced into
perserving _xattr_ properties:
@@ -136,7 +140,7 @@ The comments are stored in an Sqlite3 database, usually located at "~/.dirnotes.
|author | the system name of the user who created the comment | patb |
-The 'date' and 'size' fields reflect the file's modification date and size at the time of the last edit of the file comment, which is also 'comment_date'.
+The _date_ and _size_ fields reflect the file's modification date and size at the time of the last edit of the file comment, which is stored in _comment_date_.
As comments are editted or appended, new records are added to the database. Older records are are not purged. This gives you a history of the comments, but it means that fetching the most recent comment involves something like
@@ -146,6 +150,14 @@ As comments are editted or appended, new records are added to the database. Olde
and just fetch the first record.
+The database is created the first time one of the **dirnotes** apps is run.
+
+ * misc
+
+The **dirnotes** gui app has a desktop icon built into the code. There is not need for an external .icon file.
+
+There was _no_ consideration given for language translation. Email [me](mail:patb@pbeirne.com) if you want this, or can help.
+
### MacOS {#macos}
The **MacOS** inherently supports file comments. The Finder app manages most of the user activity. It handles file comments in a similar manner to **Dirnotes**. Comments are stored in two places:
@@ -164,12 +176,17 @@ If the Finder is used to copy/move files, the comments are moved properly to bot
## DEVELOPMENT STATUS{#status}
-Each app is a standalone file. That means there is a lot of redundancy between the tthree apps. And there _may_ be some inconsistency.
+Each app is a standalone file. That means there is a lot of redundancy between
+the three apps. And there _may_ be some inconsistency.
2022-10-04
: All three apps are functioning and usable.
- The _config_file_ is fully implemented.
- Themes are not implemented.
- Comments are intended to be _utf-8_, but are _strings_ in some places.
- MacOS code is not written yet.
- The _help_ dialogs in **dirnotes-tui** are meagre.
+ The _config_file_ is fully implemented.
+ Themes are not implemented.
+ Comments are intended to be _utf-8_, but are _strings_ in some places.
+ MacOS code is not written yet.
+ The _help_ dialogs in **dirnotes-tui** are meagre.
+ The _qt-gui_ app is working pretty well.
+
+
+
diff --git a/dirnotes b/dirnotes
index 689ed0b..7993a7f 100755
--- a/dirnotes
+++ b/dirnotes
@@ -1,227 +1,307 @@
#!/usr/bin/python3
-# TODO: add author to access
-# TODO: convert dates to strings
+# TODO: pick up comment for cwd and display at the top somewhere, or maybe status line
""" a simple gui or command line app
to view and create/edit file comments
comments are stored in an SQLite3 database
- default ~/.dirnotes.db
+ default ~/.dirnotes.db
where possible, comments are duplicated in
- xattr user.xdg.comment
+ xattr user.xdg.comment
- some file systems don't allow xattr, and even linux
- doesn't allow xattr on symlinks, so the database is
- considered primary
+ some file systems don't allow xattr, and even linux
+ doesn't allow xattr on symlinks, so the database is
+ considered primary
- these comments stick to the symlink, not the deref
+ these comments stick to the symlink, not the deref
-nav tools are enabled, so you can double-click to go into a dir, and
- there's an UP arrow to navigate back
+nav tools are enabled, so you can double-click to go into a dir
"""
+VERSION = "0.4"
-helpMsg = """
Dirnotes
Overview
+helpMsg = f"""Dirnotes |
+ | Version: {VERSION} |
+
+Overview
This app allows you to add comments to files. The comments are stored in
-a database, and where possible, saved in the xattr (hidden attributes)
+a database, and where possible, saved in the xattr (hidden attributes)
field of the file system.
-
-You can sort the directory listing by clicking on the column heading.
-
-Double click on directory names to navigate the file system. Hover over
+
+
Double click on a comment to create or edit.
+
+
You can sort the directory listing by clicking on the column heading.
+
+
Double click on directory names to navigate the file system. Hover over
fields for more information.
-
+
xattr extended attributes
-The xattr property is handy, but suffers from a few problems:
+The xattr comment suffers from a few problems:
-- is not implemented on FAT/VFAT/EXFAT file systems (like USB sticks)
-
- xattrs are not (by default) copied with the file when it's duplicated
-or backedup
-
- xattrs are not available for symlinks
-
- many programs which edit files do not preserve the xattrs during file-save
+
- is not implemented on FAT/VFAT/EXFAT file systems (some USB sticks)
+
- xattrs are not (by default) copied with the file when it's duplicated
+or backedup (mv, rsync and tar work, ssh and scp don't)
+
- xattrs are not available for symlinks
+
- some programs which edit files do not preserve the xattrs during file-save (vim)
-When the database version of a comment differs from the xattr version, the
-comment box gets a light yellow background.
+
+On the other hand, xattr comments can be bound directly to files on removable
+media (as long as the disk format allows it).
+
+When the database version of a comment differs from the xattr version,
+the comment box gets a light yellow background.
"""
-import sys,os,argparse,stat
+import sys,os,argparse,stat,getpass
#~ from dirWidget import DirWidget
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, pyqtSignal
-import sqlite3, time
+import sqlite3, json, time
-VERSION = "0.3"
-COMMENT_KEY = "user.xdg.comment"
-DATABASE_NAME = "~/.dirnotes.db"
-# convert the ~/ form to a fully qualified path
-DATABASE_NAME = os.path.expanduser(DATABASE_NAME)
+VERSION = "0.4"
+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"
+YEAR = 3600*25*365
+
+## globals
+mode_names = {"db":" ","xattr":""}
+modes = ("db","xattr")
+mode = "db"
+
+global mainWindow, dbName
+
+DEFAULT_CONFIG_FILE = "~/.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",
+ "start_mode":"xattr",
+ "options for database":("~/.dirnotes.db","/etc/dirnotes.db"),
+ "options for start_mode":("db","xattr")
+}
+
+verbose = None
+def print_v(*a):
+ if verbose:
+ print(*a)
class dnDataBase:
- ''' the database is flat
- fileName: fully qualified name
- st_mtime: a float
- size: a long
- comment: a string
- comment_time: a float, the time of the comment save
- this is effectively a log file, as well as a resource for a restore
- (in case a file-move is done without comment)
- the database is associated with a user, in the $HOME dir
- '''
- def __init__(self):
- '''try to open the database; if not found, create it'''
- try:
- self.db = sqlite3.connect(DATABASE_NAME)
- except sqlite3.OperationalError:
- print("Database %s not found" % DATABASE_NAME)
- raise OperationalError
- c = self.db.cursor()
- try:
- c.execute("select * from dirnotes")
- except sqlite3.OperationalError:
- print("Table %s created" % ("dirnotes"))
- c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME)")
-
- def getData(self, fileName):
- c = self.db.cursor()
- c.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
- return c.fetchone()
- def setData(self, fileName, comment):
- ''' TODO: convert filename to canonical '''
- c = self.db.cursor()
- s = os.lstat(fileName)
- print ("params: %s %s %d %s %s" % ((os.path.abspath(fileName),
- dnDataBase.epochToDb(s.st_mtime), s.st_size, comment,
- dnDataBase.epochToDb(time.time()))))
- try:
- c.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'))",
- (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time()))
- self.db.commit()
- except sqlite3.OperationalError:
- print("database is locked or unwriteable")
- #TODO: put up a message box for locked database
+ ''' the database is flat
+ fileName: fully qualified name
+ st_mtime: a float
+ size: a long
+ comment: a string
+ comment_time: a float, the time of the comment save
+ author: the username that created the comment
+
+ the database is associated with a user, in the $HOME dir
+ '''
+ def __init__(self,dbFile):
+ '''try to open the database; if not found, create it'''
+ try:
+ self.db = sqlite3.connect(dbFile)
+ except sqlite3.OperationalError:
+ print(f"Database {dbFile} not found")
+ raise
+ self.db_cursor = self.db.cursor()
+ try:
+ self.db_cursor.execute("select * from dirnotes")
+ except sqlite3.OperationalError:
+ print_v("Table %s created" % ("dirnotes"))
+ self.db_cursor.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME, author TEXT)")
+
+ def getData(self, fileName):
+ self.db_cursor.execute("select * from dirnotes where name=? and comment<>'' order by comment_date desc",(os.path.abspath(fileName),))
+ return self.db_cursor.fetchone()
+ def setData(self, fileName, comment):
+ s = os.lstat(fileName)
+ print_v ("params: %s %s %d %s %s" % ((os.path.abspath(fileName),
+ dnDataBase.epochToDb(s.st_mtime), s.st_size, comment,
+ dnDataBase.epochToDb(time.time()))))
+ try:
+ self.db_cursor.execute("insert into dirnotes values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'),?)",
+ (os.path.abspath(fileName), s.st_mtime, s.st_size, str(comment), time.time(), getpass.getuser()))
+ self.db.commit()
+ except sqlite3.OperationalError:
+ print("database is locked or unwriteable")
+ errorBox("database is locked or unwriteable")
+ #TODO: put up a message box for locked database
- @staticmethod
- def epochToDb(epoch):
- return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(epoch))
- @staticmethod
- def DbToEpoch(dbTime):
- return time.mktime(time.strptime(dbTime,"%Y-%m-%d %H:%M:%S"))
- @staticmethod
- def getShortDate(longDate):
- e = dnDataBase.DbToEpoch(longDate)
- sd = time.strptime(longDate,"%Y-%m-%d %H:%M:%S")
- # check for this year, or today
- ty = time.mktime((time.localtime()[0],1,1,0,0,0,0,1,-1))
- today = time.mktime((time.localtime()[0:3]+(0,0,0,0,1,-1)))
- if e < ty:
- return time.strftime("%b %d %Y",sd)
- elif e < today:
- return time.strftime("%b %d",sd)
- else:
- return time.strftime("%X",sd)
- #~ test code for this routine
- #~ for i in range(int(time.time() - 370*24*3600),
- #~ int(time.time() + 48*3600),
- #~ 3599):
- #~ ds = dnDataBase.epochToDb(i)
- #~ print("%d\t%s\t%s" % (i,ds,dnDataBase.getShortDate(ds)))
-
+ @staticmethod
+ def epochToDb(epoch):
+ return time.strftime(DATE_FORMAT,time.localtime(epoch))
+ @staticmethod
+ def DbToEpoch(dbTime):
+ return time.mktime(time.strptime(dbTime,DATE_FORMAT))
+ @staticmethod
+ def getShortDate(longDate):
+ now = time.time()
+ diff = now - longDate
+ if diff > YEAR:
+ fmt = "%b %e %Y"
+ else:
+ fmt = "%b %d %H:%M"
+ return time.strftime(fmt, time.localtime(longDate))
+
-
-def parse():
- parser = argparse.ArgumentParser(description='dirnotes application')
- parser.add_argument('dirname',metavar='dirname',type=str,
- help='directory [default=current dir]',default=".",nargs='?')
- parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
- parser.add_argument('-n','--nogui',action="store_const",const="1",
- help='use text base interface')
- parser.add_argument('-v','--version',action='version',version='%(prog)s '+VERSION)
- group = parser.add_mutually_exclusive_group()
- group.add_argument('-s','--sort-by-name',metavar='sort',action="store_const",const='n')
- group.add_argument('-m','--sort-by-date',metavar='sort',action='store_const',const='d')
- return parser.parse_args()
-
-
-#~ class FileObj(QtCore.QObject):
+## one for each file
+## and a special one for ".." parent directory
class FileObj():
- FILE_IS_DIR = -1
- FILE_IS_LINK = -2
- def __init__(self, fileName):
- self.fileName = fileName
- s = os.lstat(fileName)
- self.date = dnDataBase.epochToDb(s.st_mtime)
- if stat.S_ISDIR(s.st_mode):
- self.size = FileObj.FILE_IS_DIR
- elif stat.S_ISLNK(s.st_mode):
- self.size = FileObj.FILE_IS_LINK
- else:
- self.size = s.st_size
- self.xattrComment = ''
- try:
- self.xattrComment = os.getxattr(fileName,COMMENT_KEY,follow_symlinks=False).decode()
- except Exception as e:
- #print("comment read on %s failed, execption %s" % (self.fileName,e))
- pass
+ FILE_IS_DIR = -1
+ FILE_IS_LINK = -2
+ FILE_IS_SOCKET = -3
+ def __init__(self, fileName):
+ self.fileName = os.path.abspath(fileName)
+ self.displayName = os.path.split(fileName)[1]
+ s = os.lstat(self.fileName)
+ self.date = s.st_mtime
+ if stat.S_ISDIR(s.st_mode):
+ self.size = FileObj.FILE_IS_DIR
+ self.displayName += '/'
+ elif stat.S_ISLNK(s.st_mode):
+ self.size = FileObj.FILE_IS_LINK
+ elif stat.S_ISSOCK(s.st_mode):
+ self.size = FileObj.FILE_IS_SOCKET
+ else:
+ self.size = s.st_size
+ self.xattrComment = ''
+ self.xattrAuthor = None
+ self.xattrDate = None
+ self.dbComment = ''
+ self.dbAuthor = None
+ self.dbDate = None
+ self.commentsDiffer = False
+ try:
+ self.xattrComment = os.getxattr(fileName, xattr_comment, follow_symlinks=False).decode()
+ self.xattrAuthor = os.getxattr(fileName, xattr_author, follow_symlinks=False).decode()
+ self.xattrDate = os.getxattr(fileName, xattr_date, follow_symlinks=False).decode()
+ self.commentsDiffer = True if self.xattrComment == self.dbComment else False
+ except: # no xattr comment
+ pass
- def getName(self):
- return self.fileName
- def getFileName(self):
- return os.path.split(self.fileName)[1]
+ def getName(self):
+ return self.fileName
+ def getFileName(self):
+ return self.displayName
- def getXattrComment(self):
- return self.xattrComment
- def setXattrComment(self,newComment):
- self.xattrComment = newComment
- try:
- os.setxattr(self.fileName,COMMENT_KEY,bytes(self.xattrComment,'utf8'),follow_symlinks=False)
- return True
- # we need to move these cases out to a handler
- except Exception as e:
- print("problem setting the comment on file %s" % (self.fileName,))
- print("error "+repr(e))
- ## todo: elif file.is_sym() the kernel won't allow comments on symlinks....stored in database
- if self.size == FileObj.FILE_IS_LINK:
- print("Linux does not allow comments on symlinks; comment is stored in database")
- elif os.access(self.fileName, os.W_OK)!=True:
- print("you don't appear to have write permissions on this file")
- # change the listbox background to yellow
- self.displayBox.notifyUnchanged()
- elif "Errno 95" in str(e):
- print("is this a VFAT or EXFAT volume? these don't allow comments")
- return False
+ # with an already open database cursor
+ def loadDbComment(self,cursor):
+ cursor.execute("select comment,author,comment_date from dirnotes where name=? and comment<>'' order by comment_date desc",(self.fileName,))
+ a = cursor.fetchone()
+ if a:
+ self.dbComment, self.dbAuthor, self.dbDate = a
+ self.commentsDiffer = True if self.xattrComment == self.dbComment else False
- def getDbComment(self,db):
- self.dbComment = ""
- row = db.getData(self.fileName)
- if row and len(row)>1:
- self.dbComment = row[3]
- def setDbComment(self,db,comment):
- db.setData(self.fileName,comment)
+ def getDbComment(self):
+ return self.dbComment
+ def getDbAuthor(self):
+ return self.dbAuthor
+ def getDbDate(self):
+ return self.dbDate
+ def setDbComment(self,newComment):
+ try:
+ self.db = sqlite3.connect(dbName)
+ except sqlite3.OperationalError:
+ print_v(f"database {dbName} not found")
+ raise
+ c = self.db.cursor()
+ s = os.lstat(self.fileName)
+ try:
+ c.execute("insert into dirnotes (name,date,size,comment,comment_date,author) values (?,datetime(?,'unixepoch','localtime'),?,?,datetime(?,'unixepoch','localtime'),?)",
+ (os.path.abspath(self.fileName), s.st_mtime, s.st_size,
+ str(newComment), time.time(), getpass.getuser()))
+ self.db.commit()
+ print_v(f"database write for {self.fileName}")
+ self.dbComment = newComment
+ except sqlite3.OperationalError:
+ print_v("database is locked or unwritable")
+ errorBox("the database that stores comments is locked or unwritable")
+ self.commentsDiffer = True if self.xattrComment == self.dbComment else False
- def getDate(self):
- return self.date
- def getSize(self):
- return self.size
+ def getXattrComment(self):
+ return self.xattrComment
+ def getXattrAuthor(self):
+ return self.xattrAuthor
+ def getXattrDate(self):
+ print_v(f"someone accessed date on {self.fileName} {self.xattrDate}")
+ return self.xattrDate
+ def setXattrComment(self,newComment):
+ print_v(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)
+ os.setxattr(self.fileName,xattr_date,bytes(time.strftime(DATE_FORMAT),'utf8'),follow_symlinks=False)
+ self.xattrAuthor = getpass.getuser()
+ self.xattrDate = time.strftime(DATE_FORMAT) # alternatively, re-instantiate this FileObj
+ self.xattrComment = newComment
+ self.commentsDiffer = True if self.xattrComment == self.dbComment else False
+ return True
+ # we need to move these cases out to a handler
+ except Exception as e:
+ if self.size == FileObj.FILE_IS_LINK:
+ errorBox("Linux does not allow xattr comments on symlinks; comment is stored in database")
+ elif self.size == FileObj.FILE_IS_SOCKET:
+ 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")
+ # change the listbox background to yellow
+ self.displayBox.notifyUnchanged()
+ elif "Errno 95" in str(e):
+ errorBox("is this a VFAT or EXFAT volume? these don't allow comments")
+ self.commentsDiffer = True
+ return False
+ self.commentsDiffer = True if self.xattrComment == self.dbComment else False
+
+ def getComment(self):
+ return self.getDbComment() if mode == "db" else self.getXattrComment()
+ def getOtherComment(self):
+ return self.getDbComment() if mode == "xattr" else self.getXattrComment()
+ def getDate(self):
+ return self.date
+ def getSize(self):
+ return self.size
+ def isDir(self):
+ return self.size == self.FILE_IS_DIR
+ def isLink(self):
+ return self.size == self.FILE_IS_LINK
class HelpWidget(QDialog):
- def __init__(self, parent):
- super(QDialog, self).__init__(parent)
- self.layout = QVBoxLayout(self)
- self.tb = QLabel(self)
- self.tb.setWordWrap(True)
- self.tb.setText(helpMsg)
- self.tb.setFixedWidth(500)
- self.pb = QPushButton('OK',self)
- self.pb.setFixedWidth(200)
- self.layout.addWidget(self.tb)
- self.layout.addWidget(self.pb)
- self.pb.pressed.connect(self.close)
- self.show()
+ def __init__(self, parent):
+ super(QDialog, self).__init__(parent)
+ self.layout = QVBoxLayout(self)
+ self.tb = QLabel(self)
+ self.tb.setWordWrap(True)
+ self.tb.setText(helpMsg)
+ self.tb.setFixedWidth(500)
+ self.pb = QPushButton('OK',self)
+ self.pb.setFixedWidth(200)
+ self.layout.addWidget(self.tb)
+ self.layout.addWidget(self.pb)
+ self.pb.clicked.connect(self.close)
+ self.show()
-def loadWindowIcon(): # TODO: change border/folder to dark grey, no shadow, smaller
- icon = ["32 32 6 1",
+class errorBox(QDialog):
+ def __init__(self, text):
+ print_v(f"errorBox: {text}")
+ super(QDialog, self).__init__(mainWindow)
+ self.layout = QVBoxLayout(self)
+ self.tb = QLabel(self)
+ self.tb.setWordWrap(True)
+ self.tb.setFixedWidth(500)
+ self.tb.setText(text)
+ self.pb = QPushButton("OK",self)
+ self.layout.addWidget(self.tb)
+ self.layout.addWidget(self.pb)
+ self.pb.clicked.connect(self.close)
+ self.show()
+
+icon = ["32 32 6 1", # the QPixmap constructor allows for str[]
" c None",
". c #666666",
"+ c #FFFFFF",
@@ -260,308 +340,369 @@ def loadWindowIcon(): # TODO: change border/folder to dark grey, no shadow, sma
" .+++++++++++++++++++++++++++. ",
" ........................... ",
" "]
- return QPixmap(icon)
''' a widget that shows only a dir listing
'''
-#import sys,os,argparse
-#from PyQt4.QtGui import *
-#from PyQt4 import QtGui, QtCore
-
class DirWidget(QListWidget):
- ''' a simple widget that shows a list of directories, staring
- at the directory passed into the constructor
+ ''' a simple widget that shows a list of directories, staring
+ at the directory passed into the constructor
- a mouse click or 'enter' key will send a 'selected' signal to
- anyone who connects to this.
+ a mouse click or 'enter' key will send a 'selected' signal to
+ anyone who connects to this.
- the .. parent directory is shown for all dirs except /
+ the .. parent directory is shown for all dirs except /
- the most interesting parts of the interface are:
- constructor - send in the directory to view
- method - currentPath() returns text of current path
- signal - selected calls a slot with a single arg: new path
- '''
+ the most interesting parts of the interface are:
+ constructor - send in the directory to view
+ method - currentPath() returns text of current path
+ signal - selected calls a slot with a single arg: new path
+ '''
- selected = pyqtSignal(str)
- def __init__(self, directory='.', parent=None):
- super(DirWidget,self).__init__(parent)
- self.directory = directory
- self.refill()
- self.itemActivated.connect(self.selectionByLWI)
- # it would be nice to pick up single-mouse-click for selection as well
- # but that seems to be a system-preferences global
- def selectionByLWI(self, li):
- self.directory = os.path.abspath(self.directory + '/' + str(li.text()))
- self.refill()
- self.selected.emit(self.directory)
- def refill(self):
- current,dirs,files = os.walk(self.directory,followlinks=True).next()
- dirs.sort()
- if '/' not in dirs:
- dirs = ['..'] + dirs
- self.clear()
- for d in dirs:
- li = QListWidgetItem(d,self)
- def currentPath(self):
- return self.directory
-
+ selected = pyqtSignal(str)
+ def __init__(self, directory='.', parent=None):
+ super(DirWidget,self).__init__(parent)
+ self.directory = directory
+ self.refill()
+ self.itemActivated.connect(self.selectionByLWI)
+ # it would be nice to pick up single-mouse-click for selection as well
+ # but that seems to be a system-preferences global
+ def selectionByLWI(self, li):
+ self.directory = os.path.abspath(self.directory + '/' + str(li.text()))
+ self.refill()
+ self.selected.emit(self.directory)
+ def refill(self):
+ current,dirs,files = next(os.walk(self.directory,followlinks=True))
+ dirs.sort()
+ if '/' not in dirs:
+ dirs = ['..'] + dirs
+ self.clear()
+ for d in dirs:
+ li = QListWidgetItem(d,self)
+ def currentPath(self):
+ return self.directory
+
# sortable TableWidgetItem, based on idea by Aledsandar
# http://stackoverflow.com/questions/12673598/python-numerical-sorting-in-qtablewidget
# NOTE: the QTableWidgetItem has setData() and data() which may allow data bonding
# in Qt5, data() binding is more awkward, so do it here
class SortableTableWidgetItem(QTableWidgetItem):
- def __init__(self, text, sortValue, file_object):
- QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
- self.sortValue = sortValue
- self.file_object = file_object
- def __lt__(self, other):
- return self.sortValue < other.sortValue
-
-
+ def __init__(self, text, sortValue, file_object):
+ QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
+ self.sortValue = sortValue
+ self.file_object = file_object
+ def __lt__(self, other):
+ return self.sortValue < other.sortValue
+
+
class DirNotes(QMainWindow):
- ''' the main window of the app
- has 3 list boxes: dir_left, dir_right (may be invisible) and files
-
- '''
- def __init__(self, argFilename, db, parent=None):
- super(DirNotes,self).__init__(parent)
- self.db = db
- self.refilling = False
+ ''' the main window of the app
+ '''
+ def __init__(self, argFilename, db, start_mode, parent=None):
+ super(DirNotes,self).__init__(parent)
+ self.db = db
+ self.refilling = False
+ self.parent = parent
- win = QWidget()
- self.setCentralWidget(win)
+ win = QWidget()
+ self.setCentralWidget(win)
- lb = QTableWidget()
- self.lb = lb
- lb.setColumnCount(4)
- lb.horizontalHeader().setSectionResizeMode( 3, QHeaderView.Stretch );
- lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
- lb.verticalHeader().setVisible(False)
-
- # resize the comments column
- # and resize the parent window to match the directory size
+ lb = QTableWidget()
+ self.lb = lb
+ lb.setColumnCount(4)
+ lb.horizontalHeader().setSectionResizeMode( 3, QHeaderView.Stretch );
+ lb.verticalHeader().setDefaultSectionSize(20); # thinner rows
+ lb.verticalHeader().setVisible(False)
- # allow multiple entries on the line at this point
- #d = os.listdir(p.filename[0])
- #d.sort()
- longPathName = os.path.abspath(argFilename)
- print("longpathname is {}".format(longPathName))
- if os.path.isdir(longPathName):
- self.curPath = longPathName
- filename = ''
- else:
- self.curPath, filename = os.path.split(longPathName)
- print("working on <"+self.curPath+"> and <"+filename+">")
-
- lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
- lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
- lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
- lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
- lb.setSortingEnabled(True)
+ longPathName = os.path.abspath(argFilename)
+ print_v("longpathname is {}".format(longPathName))
+ if os.path.isdir(longPathName):
+ self.curPath = longPathName
+ filename = ''
+ else:
+ self.curPath, filename = os.path.split(longPathName)
+ print_v("working on <"+self.curPath+"> and <"+filename+">")
+
+ layout = QVBoxLayout()
- self.refill()
- lb.resizeColumnsToContents()
-
- if len(filename)>0:
- for i in range(lb.rowCount()):
- if filename == lb.item(i,0).data(32).toPyObject().getFileName():
- lb.setCurrentCell(i,3)
- break
-
- layout = QVBoxLayout()
+ copyIcon = QIcon.fromTheme('drive-harddisk-symbolic')
+ changeIcon = QIcon.fromTheme('emblem-synchronizing-symbolic')
- e = QLabel("View and edit file comments stored in extended attributes user.xdg.comment",win)
- layout.addWidget(e)
+ topLayout = QHBoxLayout()
+ self.modeShow = QLabel(win)
+ topLayout.addWidget(self.modeShow)
+ bmode = QPushButton(changeIcon, "change mode",win)
+ topLayout.addWidget(bmode)
+ cf = QPushButton(copyIcon, "copy file",win)
+ topLayout.addWidget(cf)
+ layout.addLayout(topLayout)
- bup = QPushButton("up",win)
- bup.setIcon(QIcon.fromTheme('go-up')) # or go-previous
- bup.setFixedWidth(100)
- b1 = QPushButton("restore from database",win)
+ layout.addWidget(lb)
+ win.setLayout(layout)
+
+ lb.itemChanged.connect(self.change)
+ lb.cellDoubleClicked.connect(self.double)
+ bmode.clicked.connect(self.switchMode)
+ cf.clicked.connect(self.copyFile)
- upperLayout = QHBoxLayout()
- upperLayout.addWidget(bup)
- upperLayout.addWidget(b1)
- layout.addLayout(upperLayout)
- layout.addWidget(lb)
- win.setLayout(layout)
-
- lb.itemChanged.connect(self.change)
- lb.cellDoubleClicked.connect(self.double)
- b1.pressed.connect(self.restore_from_database)
- bup.pressed.connect(self.upOneLevel)
+ lb.setHorizontalHeaderItem(0,QTableWidgetItem("File"))
+ lb.setHorizontalHeaderItem(1,QTableWidgetItem("Date/Time"))
+ lb.setHorizontalHeaderItem(2,QTableWidgetItem("Size"))
+ lb.setHorizontalHeaderItem(3,QTableWidgetItem("Comment"))
+ lb.setSortingEnabled(True)
- mb = self.menuBar()
- mf = mb.addMenu('&File')
- mf.addAction("Sort by name", self.sbn, "Ctrl+N")
- mf.addAction("Sort by date", self.sbd, "Ctrl+D")
- mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
- mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
- mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
- mf.addSeparator()
- mf.addAction("Quit", self.close, "Ctrl+Q")
- mf.addAction("About", self.about, "Ctrl+H")
+ self.refill()
+ lb.resizeColumnsToContents()
+
+ if len(filename)>0:
+ for i in range(lb.rowCount()):
+ if filename == lb.item(i,0).data(32).getFileName():
+ lb.setCurrentCell(i,3)
+ break
+
+ mb = self.menuBar()
+ mf = mb.addMenu('&File')
+ mf.addAction("Sort by name", self.sbn, "Ctrl+N")
+ mf.addAction("Sort by date", self.sbd, "Ctrl+D")
+ mf.addAction("Sort by size", self.sbs, "Ctrl+Z")
+ mf.addAction("Sort by comment", self.sbc, "Ctrl+.")
+ mf.addAction("Restore comment from database", self.restore_from_database, "Ctrl+R")
+ mf.addSeparator()
+ mf.addAction("Quit", self.close, QKeySequence.Quit)
+ mf.addAction("About", self.about, QKeySequence.HelpContents)
- #~ QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
- self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
- self.setMinimumSize(600,700)
- wi = loadWindowIcon()
- self.setWindowIcon(QIcon(wi))
- lb.setFocus()
- def closeEvent(self,e):
- print("closing")
- def sbd(self):
- print("sort by date")
- self.lb.sortItems(1,Qt.DescendingOrder)
- def sbs(self):
- print("sort by size")
- self.lb.sortItems(2)
- def sbn(self):
- print("sort by name")
- self.lb.sortItems(0)
- def about(self):
- HelpWidget(self)
- def sbc(self):
- print("sort by comment")
- self.lb.sortItems(3,Qt.DescendingOrder)
- def newDir(self):
- print("change dir to "+self.dirLeft.currentPath())
- def double(self,row,col):
- print("double click {} {}".format(row, col))
- fo = self.lb.item(row,0).file_object
- if col==0 and fo.getSize() == FileObj.FILE_IS_DIR:
- print("double click on {}".format(fo.getName()))
- self.curPath = fo.getName()
- self.refill()
- def upOneLevel(self):
- self.curPath = os.path.abspath(self.curPath + "/..")
- self.refill()
-
- def refill(self):
- self.refilling = True
- self.lb.sortingEnabled = False
- self.lb.clearContents()
- small_font = QFont("",8)
- dirIcon = QIcon.fromTheme('folder')
- fileIcon = QIcon.fromTheme('text-x-generic')
- linkIcon = QIcon.fromTheme('emblem-symbolic-link')
- current, dirs, files = next(os.walk(self.curPath,followlinks=True))
- dirs = list(map(lambda x:x+'/', dirs))
- dirs.sort()
- files.sort()
-
- d = dirs + files
- self.lb.setRowCount(len(d))
+ self.setWindowTitle("DirNotes Alt-F for menu Dir: "+self.curPath)
+ self.setMinimumSize(600,700)
+ self.setWindowIcon(QIcon(QPixmap(icon)))
+ lb.setFocus()
- #~ self.files = {}
- self.files = []
- # this is a list of all the file
- #~ print("insert {} items into cleared table {}".format(len(d),current))
- for i in range(len(d)):
- this_file = FileObj(current+'/'+d[i])
- this_file.getDbComment(self.db)
- print("FileObj created as {} and the db-comment is <{}>".format(this_file.fileName, this_file.dbComment))
- #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
- #~ self.files.update({this_file.getName(),this_file})
- self.files = self.files + [this_file]
- if this_file.getSize() == FileObj.FILE_IS_DIR:
- item = SortableTableWidgetItem(d[i],' '+d[i], this_file) # directories sort first
- else:
- item = SortableTableWidgetItem(d[i],d[i], this_file)
- item.setFlags(Qt.ItemIsEnabled)
- #item.setData(32,this_file) # keep a hidden copy of the file object
- item.setToolTip(this_file.getName())
- self.lb.setItem(i,0,item)
- #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
+ def closeEvent(self,e):
+ print("closing")
+ def sbd(self):
+ print("sort by date")
+ self.lb.sortItems(1,Qt.DescendingOrder)
+ def sbs(self):
+ print("sort by size")
+ self.lb.sortItems(2)
+ def sbn(self):
+ print("sort by name")
+ self.lb.sortItems(0)
+ def about(self):
+ HelpWidget(self)
+ def sbc(self):
+ print("sort by comment")
+ self.lb.sortItems(3,Qt.DescendingOrder)
+ def newDir(self):
+ print("change dir to "+self.dirLeft.currentPath())
+ def double(self,row,col):
+ print_v("double click {} {}".format(row, col))
+ fo = self.lb.item(row,0).file_object
+ if col==0 and fo.isDir():
+ print_v("double click on {}".format(fo.getName()))
+ self.curPath = fo.getName()
+ self.refill()
+ def copyFile(self):
+ # get current selection
+ r, c = self.lb.currentRow(), self.lb.currentColumn()
+ fo = self.lb.item(r,c).file_object
+ if not fo.isDir() and not fo.isLink(): # TODO: add check for socket
+ print_v(f"copy file {fo.getName()}")
+ # open the dir.picker
+ # TODO: move all this out to a function
+ qd = QDialog(self.parent)
+ dw = DirWidget('.',qd)
+ d_ok = QPushButton('select')
+ d_ok.setDefault(True)
+ d_ok.clicked.connect(QDialog.accept)
+ d_nope = QPushButton('cancel')
+ d_nope.clicked.connect(QDialog.reject)
+ # if returns from , copy the file and comments
+ r = qd.exec()
+ print_v(f"copy to {r}")
+ pass
+
+ def refill(self):
+ self.refilling = True
+ self.lb.sortingEnabled = False
+
+ (self.modeShow.setText("View and edit file comments stored in extended attributes\n(xattr: user.xdg.comment)")
+ if mode=="xattr" else
+ self.modeShow.setText("View and edit file comments stored in the database \n(~/.dirnotes.db)"))
+ self.lb.clearContents()
+ small_font = QFont("",8)
+ dirIcon = QIcon.fromTheme('folder')
+ fileIcon = QIcon.fromTheme('text-x-generic')
+ linkIcon = QIcon.fromTheme('emblem-symbolic-link')
+ current, dirs, files = next(os.walk(self.curPath,followlinks=True))
+ dirs.sort()
+ files.sort()
+
+ if current != '/':
+ dirs.insert(0,"..")
+ d = dirs + files
+ self.lb.setRowCount(len(d))
- # get the comment from database & xattrs, either can fail
- comment = ""
- row = self.db.getData(this_file.getName())
- if row and len(row)>0:
- comment = row[3]
- xattrComment = this_file.getXattrComment()
- self.lb.setItem(i,3,QTableWidgetItem(comment))
- if xattrComment != comment:
- self.lb.item(i,3).setBackground(QBrush(Qt.yellow))
- print("got two comments <{}> and <{}>".format(comment, xattrComment))
+ #~ self.files = {}
+ self.files = []
+ # this is a list of all the file
+ #~ print("insert {} items into cleared table {}".format(len(d),current))
+ for i,name in enumerate(d):
+ this_file = FileObj(current+'/'+name)
+ this_file.loadDbComment(self.db.db_cursor)
+ print_v("FileObj created as {} and the db-comment is <{}>".format(this_file.displayName, this_file.dbComment))
+ #~ print("insert order check: {} {} {} {}".format(d[i],i,this_file.getName(),this_file.getDate()))
+ #~ self.files.update({this_file.getName(),this_file})
+ self.files = self.files + [this_file]
+ display_name = this_file.getFileName()
+ if this_file.getSize() == FileObj.FILE_IS_DIR:
+ item = SortableTableWidgetItem(display_name,' '+display_name, this_file) # directories sort first
+ else:
+ item = SortableTableWidgetItem(display_name,display_name, this_file)
+ item.setData(32,this_file) # keep a hidden copy of the file object
+ item.setToolTip(this_file.getName())
+ self.lb.setItem(i,0,item)
+ #lb.itemAt(i,0).setFlags(Qt.ItemIsEnabled) #NoItemFlags)
- dt = this_file.getDate()
- da = SortableTableWidgetItem(dnDataBase.getShortDate(dt),dt,this_file)
- #da.setFont(small_font)
- da.setToolTip(dt)
- da.setFlags(Qt.ItemIsEnabled)
- self.lb.setItem(i,1,da)
- si = this_file.getSize()
- if si==FileObj.FILE_IS_DIR:
- sa = SortableTableWidgetItem('',0,this_file)
- item.setIcon(dirIcon)
- elif si==FileObj.FILE_IS_LINK:
- sa = SortableTableWidgetItem('symlink',-1,this_file)
- item.setIcon(linkIcon)
- dst = os.path.realpath(this_file.getName())
- sa.setToolTip("symlink: " + dst)
- else:
- sa = SortableTableWidgetItem(str(si),si,this_file)
- item.setIcon(fileIcon)
- sa.setTextAlignment(Qt.AlignRight)
- sa.setFlags(Qt.ItemIsEnabled)
- self.lb.setItem(i,2,sa)
- self.refilling = False
- self.lb.sortingEnabled = True
- self.lb.resizeColumnToContents(1)
-
- def change(self,x):
- if self.refilling:
- return
- print("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
- print(" selected file: "+self.lb.item(x.row(),0).file_object.getName())
- the_file = self.lb.item(x.row(),0).file_object
- print(" and the row file is "+the_file.getName())
- r = the_file.setXattrComment(str(x.text())) # TODO: change priority
- if r:
- self.db.setData(the_file.getName(),x.text())
+ # get the comment from database & xattrs, either can fail
+ comment = this_file.getComment()
+ other_comment = this_file.getOtherComment()
+ ci = QTableWidgetItem(comment)
+ ci.setToolTip(f"comment: {comment}\ncomment date: {this_file.getDbDate()}\nauthor: {this_file.getDbAuthor()}")
+ if other_comment != comment:
+ ci.setBackground(QBrush(QColor(255,255,160)))
+ print_v("got differing comments <{}> and <{}>".format(comment, other_comment))
+ self.lb.setItem(i,3,ci)
+
+ dt = this_file.getDate()
+ da = SortableTableWidgetItem(dnDataBase.getShortDate(dt),dt,this_file)
+ da.setToolTip(time.strftime(DATE_FORMAT,time.localtime(dt)))
+ self.lb.setItem(i,1,da)
+
+ si = this_file.getSize()
+ if this_file.isDir():
+ sa = SortableTableWidgetItem('',0,this_file)
+ item.setIcon(dirIcon)
+ elif this_file.isLink():
+ sa = SortableTableWidgetItem('symlink',-1,this_file)
+ item.setIcon(linkIcon)
+ dst = os.path.realpath(this_file.getName())
+ sa.setToolTip(f"symlink: {dst}")
+ else:
+ sa = SortableTableWidgetItem(str(si),si,this_file)
+ item.setIcon(fileIcon)
+ sa.setTextAlignment(Qt.AlignRight)
+ self.lb.setItem(i,2,sa)
+
+ self.refilling = False
+ self.lb.sortingEnabled = True
+ self.lb.resizeColumnToContents(1)
+
+ def change(self,x):
+ if self.refilling:
+ return
+ print_v("debugging " + x.text() + " r:" + str(x.row()) + " c:" + str(x.column()))
+ print_v(" selected file: "+self.lb.item(x.row(),0).file_object.getName())
+ the_file = self.lb.item(x.row(),0).file_object
+ print_v(" and the row file is "+the_file.getName())
+ the_file.setDbComment(str(x.text()))
+ r = the_file.setXattrComment(str(x.text()))
+ # TODO: change this to FileObj.setDbComment()
+ if r:
+ self.db.setData(the_file.getName(),x.text())
+
+ def switchMode(self):
+ global mode
+ mode = "xattr" if mode == "db" else "db"
+ self.refill()
+
+ # TODO: this may not be needed
+ def restore_from_database(self):
+ print("restore from database")
+ # retrieve the full path name
+ fileName = str(self.lb.item(self.lb.currentRow(),0).file_object.getName())
+ print("using filename: "+fileName)
+ existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
+ print("restore....existing="+existing_comment+"=")
+ if len(existing_comment) > 0:
+ m = QMessageBox()
+ m.setText("This file already has a comment. Overwrite?")
+ m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
+ if m.exec_() != QMessageBox.Ok:
+ return
+ fo_row = self.db.getData(fileName)
+ if fo_row and len(fo_row)>1:
+ comment = fo_row[3]
+ print(fileName,fo_row[0],comment)
+ the_file = dn.files[self.lb.currentRow()]
+ the_file.setComment(comment)
+ self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
+
+def parse():
+ parser = argparse.ArgumentParser(description='dirnotes application')
+ parser.add_argument('dirname',metavar='dirname',type=str,
+ help='directory or file [default=current dir]',default=".",nargs='?')
+ #parser.add_argument('dirname2',help='comparison directory, shows two-dirs side-by-side',nargs='?')
+ parser.add_argument('-V','--version',action='version',version='%(prog)s '+VERSION)
+ parser.add_argument('-v','--verbose',action='count',help="verbose, almost debugging")
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument( '-s','--sort-by-size',action='store_true')
+ group.add_argument( '-m','--sort-by-date',action='store_true')
+ parser.add_argument('-c','--config', dest='config_file',help="config file (json format; default ~/.dirnotes.json)")
+ parser.add_argument('-x','--xattr', action='store_true',help="start up in xattr mode")
+ parser.add_argument('-d','--db', action='store_true',help="start up in database mode (default)")
+ return parser.parse_args()
- def restore_from_database(self):
- print("restore from database")
- # retrieve the full path name
- fileName = str(self.lb.item(self.lb.currentRow(),0).file_object.getName())
- print("using filename: "+fileName)
- existing_comment = str(self.lb.item(self.lb.currentRow(),3).text())
- print("restore....existing="+existing_comment+"=")
- if len(existing_comment) > 0:
- m = QMessageBox()
- m.setText("This file already has a comment. Overwrite?")
- m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel);
- if m.exec_() != QMessageBox.Ok:
- return
- fo_row = self.db.getData(fileName)
- if fo_row and len(fo_row)>1:
- comment = fo_row[3]
- print(fileName,fo_row[0],comment)
- the_file = dn.files[self.lb.currentRow()]
- the_file.setComment(comment)
- self.lb.setItem(self.lb.currentRow(),3,QTableWidgetItem(comment))
-
if __name__=="__main__":
- p = parse()
- if len(p.dirname)>1 and p.dirname[-1]=='/':
- p.dirname = p.dirname[:-1]
- if os.path.isdir(p.dirname):
- p.dirname = p.dirname + '/'
- print(p.dirname)
-
- db = dnDataBase()
+ # TODO: delete this after debugging
+ #from PyQt5.QtCore import pyqtRemoveInputHook
+ #pyqtRemoveInputHook()
- # TODO: if there's a file specified, jump to it
- a = QApplication([])
- dn = DirNotes(p.dirname,db)
- dn.show()
-
- a.exec_()
-
- #xattr.setxattr(filename,COMMENT_KEY,commentText)
+ p = parse()
+ if len(p.dirname)>1 and p.dirname[-1]=='/':
+ p.dirname = p.dirname[:-1]
+ if os.path.isdir(p.dirname):
+ p.dirname = p.dirname + '/'
+ print_v(f"using {p.dirname}")
+ verbose = p.verbose
+
+ config_file = p.config_file if p.config_file else DEFAULT_CONFIG_FILE
+ config_file = os.path.expanduser(config_file)
+ config = DEFAULT_CONFIG
+ try:
+ with open(config_file,"r") as f:
+ config = json.load(f)
+ except json.JSONDecodeError:
+ print(f"problem reading config file {config_file}; check the .json syntax")
+ except FileNotFoundError:
+ print(f"config file {config_file} not found, using the default settings and writing a default")
+ try:
+ with open(config_file,"w") as f:
+ json.dump(config,f,indent=4)
+ except:
+ print(f"problem creating the file {config_file}")
+
+ print_v(f"here is the .json {repr(config)}")
+ dbName = os.path.expanduser(config["database"])
+ db = dnDataBase(dbName)
+ xattr_comment = config["xattr_tag"]
+ xattr_author = xattr_comment + ".author"
+ xattr_date = xattr_comment + ".date"
+
+ mode = "xattr" if p.xattr else "db"
+
+ a = QApplication([])
+ mainWindow = DirNotes(p.dirname,db,config["start_mode"])
+ mainWindow.show()
+
+ if p.sort_by_date:
+ mainWindow.sbd()
+ if p.sort_by_size:
+ mainWindow.sbs()
+
+ a.exec_()
+
+ #xattr.setxattr(filename,COMMENT_KEY,commentText)
''' files from directories
use os.isfile()
@@ -596,7 +737,7 @@ user.xdg.publisher
''' TODO: create 'show comment history' popup '''
''' TODO: add dual-pane for file-move, file-copy '''
-
+
''' commandline xattr
getfattr -h (don't follow symlink) -d (dump all properties)
'''
diff --git a/dirnotes-cli b/dirnotes-cli
index 2d43a2f..0a06122 100755
--- a/dirnotes-cli
+++ b/dirnotes-cli
@@ -9,197 +9,197 @@ answer_json = []
verbose = 0
db = None
xattr_comment = "user.xdg.comment"
-xattr_author = "user.xdg.comment.author"
-xattr_date = "user.xdg.comment.date"
+xattr_author = "user.xdg.comment.author"
+xattr_date = "user.xdg.comment.date"
#======= debugging/verbose ===========
def print_d(*a):
- if verbose > 1:
- print('>>',*a)
+ if verbose > 1:
+ print('>>',*a)
def print_v(*a):
- if verbose:
- print('>',*a)
+ if verbose:
+ print('>',*a)
#============= the functions that are called from the main.loop ===============
def file_copy(f,target,target_is_dir,force):
- print_d(f"call file_copy with args={target},{target_is_dir} and {force}")
- dest = target if not target_is_dir else target+'/'+os.path.basename(f)
- if os.path.exists(dest) and not force:
- go = input("The copy target <<" + dest + ">> exists. Overwrite? (y or n) ")
- if go != 'y' and go != 'Y':
- return
- print_d(f"copy from {f} to {dest}")
+ print_d(f"call file_copy with args={target},{target_is_dir} and {force}")
+ dest = target if not target_is_dir else target+'/'+os.path.basename(f)
+ if os.path.exists(dest) and not force:
+ go = input("The copy target <<" + dest + ">> exists. Overwrite? (y or n) ")
+ if go != 'y' and go != 'Y':
+ return
+ print_d(f"copy from {f} to {dest}")
def file_zap(f,all_flag):
- print_d(f"zapping the comment history of {f}")
- if all_flag:
- print_d("zapping the entire database")
+ print_d(f"zapping the comment history of {f}")
+ if all_flag:
+ print_d("zapping the entire database")
def file_modify_comment(f, create, append, erase):
- print_d(f"modify the comment on file {f} with extra={(create,append,erase)}")
- if not os.path.exists(f):
- print(f"the target file does not exist; please check the spelling of the file: {f}")
- # sys.exit() here?
+ print_d(f"modify the comment on file {f} with extra={(create,append,erase)}")
+ if not os.path.exists(f):
+ print(f"the target file does not exist; please check the spelling of the file: {f}")
+ # sys.exit() here?
def file_display(f, listall, history, json, minimal):
- print_d(f"list file details {f}")
- x_comment = None
- try:
- x_comment = xattr.getxattr(f,xattr_comment).decode()
- x_author = xattr.getxattr(f,xattr_author).decode()
- x_date = xattr.getxattr(f,xattr_date).decode()
- except:
- pass
- full_f = os.path.realpath(f)
+ print_d(f"list file details {f}")
+ x_comment = None
+ try:
+ x_comment = xattr.getxattr(f,xattr_comment).decode()
+ x_author = xattr.getxattr(f,xattr_author).decode()
+ x_date = xattr.getxattr(f,xattr_date).decode()
+ except:
+ pass
+ full_f = os.path.realpath(f)
- d_comment = getDbComment(full_f)
- if d_comment:
- d_comment, d_author, d_date = d_comment
- print_d(f"for file {f}, database comment is <{d_comment}>, xattr comment is <{x_comment}>")
+ d_comment = getDbComment(full_f)
+ if d_comment:
+ d_comment, d_author, d_date = d_comment
+ print_d(f"for file {f}, database comment is <{d_comment}>, xattr comment is <{x_comment}>")
- if os.path.isdir(f):
- f = f+'/'
- if x_comment or listall:
- if x_comment and (d_comment != x_comment):
- x_comment += '*'
- if not json:
- if minimal:
- print(f"{x_comment}")
- else:
- print(f"{f}: {x_comment}")
- else:
- if verbose:
- answer_json.append( {"file":f,"comment":x_comment,"author":x_author,"date":x_date } )
- else:
- answer_json.append( {"file":f,"comment":x_comment} )
+ if os.path.isdir(f):
+ f = f+'/'
+ if x_comment or listall:
+ if x_comment and (d_comment != x_comment):
+ x_comment += '*'
+ if not json:
+ if minimal:
+ print(f"{x_comment}")
+ else:
+ print(f"{f}: {x_comment}")
+ else:
+ if verbose:
+ answer_json.append( {"file":f,"comment":x_comment,"author":x_author,"date":x_date } )
+ else:
+ answer_json.append( {"file":f,"comment":x_comment} )
def getDbComment(full_filename):
- global db
- print_d(f"db access for {full_filename}")
- c = db.cursor()
- c.execute("select comment,author,comment_date from dirnotes where name=? and comment<>'' order by comment_date desc",(full_filename,))
- a = c.fetchone()
- if a:
- return a[0:3]
+ global db
+ print_d(f"db access for {full_filename}")
+ c = db.cursor()
+ c.execute("select comment,author,comment_date from dirnotes where name=? and comment<>'' order by comment_date desc",(full_filename,))
+ a = c.fetchone()
+ if a:
+ return a[0:3]
def openDb():
- global db
- dbName = "~/.dirnotes.db"
- dbName = os.path.expanduser(dbName)
- db = sqlite3.connect(dbName)
- try:
- c = db.cursor()
- c.execute("select * from dirnotes")
- except sqlite3.OperationalError:
- c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME, author TEXT)")
- return db
+ global db
+ dbName = "~/.dirnotes.db"
+ dbName = os.path.expanduser(dbName)
+ db = sqlite3.connect(dbName)
+ try:
+ c = db.cursor()
+ c.execute("select * from dirnotes")
+ except sqlite3.OperationalError:
+ c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME, author TEXT)")
+ return db
def main(args):
- parser = argparse.ArgumentParser(description="Display or add comments to files",
- epilog="Some options conflict. Use only one of: -l -c -a -H -e -z -Z and one of -d -x")
- parser.add_argument('-V',"--version", action="version", version=f"dncli ver:{VERSION}")
- parser.add_argument('-v',"--verbose", action='count', help="verbose, almost debugging; do not use in scripts",default=0)
- parser.add_argument('-j',"--json", action="store_true",help="output in JSON format")
- pars_m = parser.add_mutually_exclusive_group()
- pars_m.add_argument('-l',"--listall", action="store_true",help="list all files, including those without comments")
- parser.add_argument('-d',"--db", action="store_true",help="list comments from database")
- parser.add_argument('-x',"--xattr", action="store_true",help="list comments from xattr")
- parser.add_argument('-n',"--minimal", action="store_true",help="output only comments; useful in scripting")
- parser.add_argument('-H',"--history", action="store_true",help="output the history of comments for a file")
- pars_m.add_argument('-c',"--create", metavar="comment", help="add a comment to a file")
- pars_m.add_argument('-a',"--append", metavar="comment", help="append to a comment on a file, separator=';'")
- pars_m.add_argument('-C',"--copy", action="store_true",help="copy a file with its comments")
- parser.add_argument('-y',"--cp_force",action="store_true",help="copy over existing files")
- pars_m.add_argument('-e',"--erase", action="store_true",help="erase the comment on a file")
- pars_m.add_argument('-z',"--zap", action="store_true",help="clear the comment history on a file")
- pars_m.add_argument('-Z',"--zapall", action="store_true",help="clear the comment history in the entire database")
- parser.add_argument('file_list',nargs='*',help="file(s); list commands may omit this")
- args = parser.parse_args()
+ parser = argparse.ArgumentParser(description="Display or add comments to files",
+ epilog="Some options conflict. Use only one of: -l -c -a -H -e -z -Z and one of -d -x")
+ parser.add_argument('-V',"--version", action="version", version=f"dncli ver:{VERSION}")
+ parser.add_argument('-v',"--verbose", action='count', help="verbose, almost debugging; do not use in scripts",default=0)
+ parser.add_argument('-j',"--json", action="store_true",help="output in JSON format")
+ pars_m = parser.add_mutually_exclusive_group()
+ pars_m.add_argument('-l',"--listall", action="store_true",help="list all files, including those without comments")
+ parser.add_argument('-d',"--db", action="store_true",help="list comments from database")
+ parser.add_argument('-x',"--xattr", action="store_true",help="list comments from xattr")
+ parser.add_argument('-n',"--minimal", action="store_true",help="output only comments; useful in scripting")
+ parser.add_argument('-H',"--history", action="store_true",help="output the history of comments for a file")
+ pars_m.add_argument('-c',"--create", metavar="comment", help="add a comment to a file")
+ pars_m.add_argument('-a',"--append", metavar="comment", help="append to a comment on a file, separator=';'")
+ pars_m.add_argument('-C',"--copy", action="store_true",help="copy a file with its comments")
+ parser.add_argument('-y',"--cp_force",action="store_true",help="copy over existing files")
+ pars_m.add_argument('-e',"--erase", action="store_true",help="erase the comment on a file")
+ pars_m.add_argument('-z',"--zap", action="store_true",help="clear the comment history on a file")
+ pars_m.add_argument('-Z',"--zapall", action="store_true",help="clear the comment history in the entire database")
+ parser.add_argument('file_list',nargs='*',help="file(s); list commands may omit this")
+ args = parser.parse_args()
- # default is to display all files that have comments
+ # default is to display all files that have comments
- # major modes are: display ( -l -H), add-comment (-a -c -e), clear-history(-z -Z), copy (-C)
- # determine the major mode, then apply an appropriate function over the file_list
-
- args.display = not (args.create or args.append or args.copy or args.erase or args.zap or args.zapall)
- if args.cp_force and not args.copy:
- print("the -y/--cp_force options can only be used with the -C/--copy command")
- sys.exit(3)
- if args.json and not args.display:
- print("the -j/--json option can only be used with the display modes")
- sys.exit(4)
- if args.minimal and not args.display:
- print("the -n/--minimal option only applies to the display modes")
- sys.exit(5)
- if args.history and not args.display:
- print("the -H/--history option only applies to the display modes")
- sys.exit(5)
- if args.xattr and (args.zap or args.zapall):
- print("the -x/--xattr option doesn't apply to the -z/--zap and -Z/--zapall commands")
- sys.exit(7)
+ # major modes are: display ( -l -H), add-comment (-a -c -e), clear-history(-z -Z), copy (-C)
+ # determine the major mode, then apply an appropriate function over the file_list
+
+ args.display = not (args.create or args.append or args.copy or args.erase or args.zap or args.zapall)
+ if args.cp_force and not args.copy:
+ print("the -y/--cp_force options can only be used with the -C/--copy command")
+ sys.exit(3)
+ if args.json and not args.display:
+ print("the -j/--json option can only be used with the display modes")
+ sys.exit(4)
+ if args.minimal and not args.display:
+ print("the -n/--minimal option only applies to the display modes")
+ sys.exit(5)
+ if args.history and not args.display:
+ print("the -H/--history option only applies to the display modes")
+ sys.exit(5)
+ if args.xattr and (args.zap or args.zapall):
+ print("the -x/--xattr option doesn't apply to the -z/--zap and -Z/--zapall commands")
+ sys.exit(7)
- global verbose
- verbose = args.verbose
-
- #====== 1) build the file list =============
+ global verbose
+ verbose = args.verbose
+
+ #====== 1) build the file list =============
- files = args.file_list
- # for the list commands, auto-fill the file list with the current directory
- if not files and args.display:
- files = os.listdir(".")
- files.sort()
- # other command require explicity file lists, but 'dncli -c "new comment" *' will work
- if not files:
- print("please specify a file or files to use")
- sys.exit(10)
- print_d("got the files:", files)
+ files = args.file_list
+ # for the list commands, auto-fill the file list with the current directory
+ if not files and args.display:
+ files = os.listdir(".")
+ files.sort()
+ # other command require explicity file lists, but 'dncli -c "new comment" *' will work
+ if not files:
+ print("please specify a file or files to use")
+ sys.exit(10)
+ print_d("got the files:", files)
- #======= 2) build the function
- if args.create or args.append or args.erase:
- print_d(f"create/append/erase: {args.create} . {args.append} . {args.erase}")
- func = file_modify_comment
- loop_args = (args.create, args.append, args.erase)
- elif args.zap or args.zapall:
- print_d(f"got a zap command {args.zap} . {args.zapall}")
- func = file_zap
- loop_args = (args.zapall,)
- if args.zapall:
- files = (1,)
- elif args.copy:
- print_d(f"got a copy command to {args.copy}")
- # the last item on the file list is the target
- n_files = len(files)
- if n_files < 2:
- print_d(f"the copy command requires at least two arguments, the last one is the destination")
- sys.exit(1)
- target = files[-1]
- target_is_directory = os.path.isdir(target)
- files = files[:-1]
- print_d(f"copy from {files} to {target}")
- if n_files > 2 and not target_is_directory:
- print_d(f"multiple copy files must go to a target directory")
- sys.exit(3)
- func = file_copy
- loop_args = (target, target_is_directory, args.cp_force)
- else:
- assert(args.display)
- print_v(f"list files using {'database' if args.db else 'xattr'} priority")
- print_d(f"display command with option: {args.listall} and {args.history} and {args.json} and {args.minimal}")
- loop_args = (args.listall, args.history, args.json, args.minimal)
- func = file_display
+ #======= 2) build the function
+ if args.create or args.append or args.erase:
+ print_d(f"create/append/erase: {args.create} . {args.append} . {args.erase}")
+ func = file_modify_comment
+ loop_args = (args.create, args.append, args.erase)
+ elif args.zap or args.zapall:
+ print_d(f"got a zap command {args.zap} . {args.zapall}")
+ func = file_zap
+ loop_args = (args.zapall,)
+ if args.zapall:
+ files = (1,)
+ elif args.copy:
+ print_d(f"got a copy command to {args.copy}")
+ # the last item on the file list is the target
+ n_files = len(files)
+ if n_files < 2:
+ print_d(f"the copy command requires at least two arguments, the last one is the destination")
+ sys.exit(1)
+ target = files[-1]
+ target_is_directory = os.path.isdir(target)
+ files = files[:-1]
+ print_d(f"copy from {files} to {target}")
+ if n_files > 2 and not target_is_directory:
+ print_d(f"multiple copy files must go to a target directory")
+ sys.exit(3)
+ func = file_copy
+ loop_args = (target, target_is_directory, args.cp_force)
+ else:
+ assert(args.display)
+ print_v(f"list files using {'database' if args.db else 'xattr'} priority")
+ print_d(f"display command with option: {args.listall} and {args.history} and {args.json} and {args.minimal}")
+ loop_args = (args.listall, args.history, args.json, args.minimal)
+ func = file_display
- #====== 3) loop on the list, execute the function =============
- global db
- db = openDb()
+ #====== 3) loop on the list, execute the function =============
+ global db
+ db = openDb()
- for f in files:
- func(f,*loop_args)
+ for f in files:
+ func(f,*loop_args)
- if answer_json:
- print(json.dumps(answer_json))
+ if answer_json:
+ print(json.dumps(answer_json))
if __name__ == "__main__":
- main(sys.argv)
+ main(sys.argv)
diff --git a/dirnotes-cli.md b/dirnotes-cli.md
index 2958566..4318839 100644
--- a/dirnotes-cli.md
+++ b/dirnotes-cli.md
@@ -184,3 +184,4 @@ three attributes described in that file that are important:
> * start_mode
+