dirnotes-cli 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #!/usr/bin/python3
  2. # TODO: get rid of the -n option; multiple files are prefixed by 'filename:', single files aren't
  3. VERSION = "0.3"
  4. import os, sys, argparse, xattr, json, sqlite3
  5. answer_json = []
  6. verbose = 0
  7. db = None
  8. xattr_comment = "user.xdg.comment"
  9. xattr_author = "user.xdg.comment.author"
  10. xattr_date = "user.xdg.comment.date"
  11. #======= debugging/verbose ===========
  12. def print_d(*a):
  13. if verbose > 1:
  14. print('>>',*a)
  15. def print_v(*a):
  16. if verbose:
  17. print('>',*a)
  18. #============= the functions that are called from the main.loop ===============
  19. def file_copy(f,target,target_is_dir,force):
  20. print_d(f"call file_copy with args={target},{target_is_dir} and {force}")
  21. dest = target if not target_is_dir else target+'/'+os.path.basename(f)
  22. if os.path.exists(dest) and not force:
  23. go = input("The copy target <<" + dest + ">> exists. Overwrite? (y or n) ")
  24. if go != 'y' and go != 'Y':
  25. return
  26. print_d(f"copy from {f} to {dest}")
  27. def file_zap(f,all_flag):
  28. print_d(f"zapping the comment history of {f}")
  29. if all_flag:
  30. print_d("zapping the entire database")
  31. def file_modify_comment(f, create, append, erase):
  32. print_d(f"modify the comment on file {f} with extra={(create,append,erase)}")
  33. if not os.path.exists(f):
  34. print(f"the target file does not exist; please check the spelling of the file: {f}")
  35. # sys.exit() here?
  36. def file_display(f, listall, history, json, minimal):
  37. print_d(f"list file details {f}")
  38. x_comment = None
  39. try:
  40. x_comment = xattr.getxattr(f,xattr_comment).decode()
  41. x_author = xattr.getxattr(f,xattr_author).decode()
  42. x_date = xattr.getxattr(f,xattr_date).decode()
  43. except:
  44. pass
  45. full_f = os.path.realpath(f)
  46. d_comment = getDbComment(full_f)
  47. if d_comment:
  48. d_comment, d_author, d_date = d_comment
  49. print_d(f"for file {f}, database comment is <{d_comment}>, xattr comment is <{x_comment}>")
  50. if os.path.isdir(f):
  51. f = f+'/'
  52. if x_comment or listall:
  53. if x_comment and (d_comment != x_comment):
  54. x_comment += '*'
  55. if not json:
  56. if minimal:
  57. print(f"{x_comment}")
  58. else:
  59. print(f"{f}: {x_comment}")
  60. else:
  61. if verbose:
  62. answer_json.append( {"file":f,"comment":x_comment,"author":x_author,"date":x_date } )
  63. else:
  64. answer_json.append( {"file":f,"comment":x_comment} )
  65. def getDbComment(full_filename):
  66. global db
  67. print_d(f"db access for {full_filename}")
  68. c = db.cursor()
  69. c.execute("select comment,author,comment_date from dirnotes where name=? and comment<>'' order by comment_date desc",(full_filename,))
  70. a = c.fetchone()
  71. if a:
  72. return a[0:3]
  73. def openDb():
  74. global db
  75. dbName = "~/.dirnotes.db"
  76. dbName = os.path.expanduser(dbName)
  77. db = sqlite3.connect(dbName)
  78. try:
  79. c = db.cursor()
  80. c.execute("select * from dirnotes")
  81. except sqlite3.OperationalError:
  82. c.execute("create table dirnotes (name TEXT, date DATETIME, size INTEGER, comment TEXT, comment_date DATETIME, author TEXT)")
  83. return db
  84. def main(args):
  85. parser = argparse.ArgumentParser(description="Display or add comments to files",
  86. epilog="Some options conflict. Use only one of: -l -c -a -H -e -z -Z and one of -d -x")
  87. parser.add_argument('-V',"--version", action="version", version=f"dncli ver:{VERSION}")
  88. parser.add_argument('-v',"--verbose", action='count', help="verbose, almost debugging; do not use in scripts",default=0)
  89. parser.add_argument('-j',"--json", action="store_true",help="output in JSON format")
  90. pars_m = parser.add_mutually_exclusive_group()
  91. pars_m.add_argument('-l',"--listall", action="store_true",help="list all files, including those without comments")
  92. parser.add_argument('-d',"--db", action="store_true",help="list comments from database")
  93. parser.add_argument('-x',"--xattr", action="store_true",help="list comments from xattr")
  94. parser.add_argument('-n',"--minimal", action="store_true",help="output only comments; useful in scripting")
  95. parser.add_argument('-H',"--history", action="store_true",help="output the history of comments for a file")
  96. pars_m.add_argument('-c',"--create", metavar="comment", help="add a comment to a file")
  97. pars_m.add_argument('-a',"--append", metavar="comment", help="append to a comment on a file, separator=';'")
  98. pars_m.add_argument('-C',"--copy", action="store_true",help="copy a file with its comments")
  99. parser.add_argument('-y',"--cp_force",action="store_true",help="copy over existing files")
  100. pars_m.add_argument('-e',"--erase", action="store_true",help="erase the comment on a file")
  101. pars_m.add_argument('-z',"--zap", action="store_true",help="clear the comment history on a file")
  102. pars_m.add_argument('-Z',"--zapall", action="store_true",help="clear the comment history in the entire database")
  103. parser.add_argument('file_list',nargs='*',help="file(s); list commands may omit this")
  104. args = parser.parse_args()
  105. # default is to display all files that have comments
  106. # major modes are: display (<none> -l -H), add-comment (-a -c -e), clear-history(-z -Z), copy (-C)
  107. # determine the major mode, then apply an appropriate function over the file_list
  108. args.display = not (args.create or args.append or args.copy or args.erase or args.zap or args.zapall)
  109. if args.cp_force and not args.copy:
  110. print("the -y/--cp_force options can only be used with the -C/--copy command")
  111. sys.exit(3)
  112. if args.json and not args.display:
  113. print("the -j/--json option can only be used with the display modes")
  114. sys.exit(4)
  115. if args.minimal and not args.display:
  116. print("the -n/--minimal option only applies to the display modes")
  117. sys.exit(5)
  118. if args.history and not args.display:
  119. print("the -H/--history option only applies to the display modes")
  120. sys.exit(5)
  121. if args.xattr and (args.zap or args.zapall):
  122. print("the -x/--xattr option doesn't apply to the -z/--zap and -Z/--zapall commands")
  123. sys.exit(7)
  124. global verbose
  125. verbose = args.verbose
  126. #====== 1) build the file list =============
  127. files = args.file_list
  128. # for the list commands, auto-fill the file list with the current directory
  129. if not files and args.display:
  130. files = os.listdir(".")
  131. files.sort()
  132. # other command require explicity file lists, but 'dncli -c "new comment" *' will work
  133. if not files:
  134. print("please specify a file or files to use")
  135. sys.exit(10)
  136. print_d("got the files:", files)
  137. #======= 2) build the function
  138. if args.create or args.append or args.erase:
  139. print_d(f"create/append/erase: {args.create} . {args.append} . {args.erase}")
  140. func = file_modify_comment
  141. loop_args = (args.create, args.append, args.erase)
  142. elif args.zap or args.zapall:
  143. print_d(f"got a zap command {args.zap} . {args.zapall}")
  144. func = file_zap
  145. loop_args = (args.zapall,)
  146. if args.zapall:
  147. files = (1,)
  148. elif args.copy:
  149. print_d(f"got a copy command to {args.copy}")
  150. # the last item on the file list is the target
  151. n_files = len(files)
  152. if n_files < 2:
  153. print_d(f"the copy command requires at least two arguments, the last one is the destination")
  154. sys.exit(1)
  155. target = files[-1]
  156. target_is_directory = os.path.isdir(target)
  157. files = files[:-1]
  158. print_d(f"copy from {files} to {target}")
  159. if n_files > 2 and not target_is_directory:
  160. print_d(f"multiple copy files must go to a target directory")
  161. sys.exit(3)
  162. func = file_copy
  163. loop_args = (target, target_is_directory, args.cp_force)
  164. else:
  165. assert(args.display)
  166. print_v(f"list files using {'database' if args.db else 'xattr'} priority")
  167. print_d(f"display command with option: {args.listall} and {args.history} and {args.json} and {args.minimal}")
  168. loop_args = (args.listall, args.history, args.json, args.minimal)
  169. func = file_display
  170. #====== 3) loop on the list, execute the function =============
  171. global db
  172. db = openDb()
  173. for f in files:
  174. func(f,*loop_args)
  175. if answer_json:
  176. print(json.dumps(answer_json))
  177. if __name__ == "__main__":
  178. main(sys.argv)