dirnotes-cli 8.4 KB

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