db.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. This is meant to be used for LA4Falcon_pre/post hooks.
  3. dbdir is probably /dev/shm.
  4. """
  5. import os, shutil, sys
  6. # We will ignore track files (.anno/.data).
  7. suffixes = ('.idx', '.bps')
  8. def log(msg):
  9. print(msg)
  10. def rm(bn, dn):
  11. """Remove bn from directory.
  12. Skip silently if not found.
  13. Leave the directory tree.
  14. """
  15. fn = os.path.join(dn, bn)
  16. if os.path.exists(fn):
  17. log('rm -f "{}"'.format(fn))
  18. os.remove(fn)
  19. def cp(bn, src_dn, dst_dn):
  20. """Copy bn from src to dst.
  21. Create dirs for dst_dn as needed.
  22. Over-write if exists in dst.
  23. Raise Exception if bn is not found in src_dn.
  24. """
  25. src_fn = os.path.join(src_dn, bn)
  26. dst_fn = os.path.join(dst_dn, bn)
  27. if not os.path.exists(src_fn):
  28. msg = 'Nothing found at "{}"'.format(src_fn)
  29. raise Exception(msg)
  30. if not os.path.isdir(dst_dn):
  31. log('mkdir -p "{}"'.format(dst_dn))
  32. os.makedirs(dst_dn)
  33. if os.path.exists(dst_fn):
  34. log('WARNING: {!r} already exists. Deleting and re-copying.'.format(dst_fn))
  35. rm(bn, dst_dn)
  36. log('cp -f "{}" "{}"'.format(src_fn, dst_fn))
  37. shutil.copy2(src_fn, dst_fn)
  38. def clean(db, dbdir):
  39. """
  40. Remove db and dot-db files from dbdir.
  41. Assume the same basename was used.
  42. """
  43. bn = os.path.basename(db)
  44. assert bn.endswith('.db'), '{} does not end in .db'.format(bn)
  45. dbname = bn[:-3] # drop .db
  46. rm(bn, dbdir)
  47. for suffix in suffixes:
  48. bn = '.'+dbname+suffix
  49. rm(bn, dbdir)
  50. def copy(db, dbdir):
  51. """
  52. Copy db and dot-db files into dbdir.
  53. (dbdir is probably /dev/shm.)
  54. """
  55. dn, bn = os.path.split(db)
  56. assert bn.endswith('.db'), '{} does not end in .db'.format(bn)
  57. dbname = bn[:-3] # drop .db
  58. cp(bn, dn, dbdir)
  59. for suffix in suffixes:
  60. bn = '.'+dbname+suffix
  61. cp(bn, dn, dbdir)
  62. def main(prog, subcmd, db, dbdir):
  63. cmd2func = {'clean': clean, 'copy': copy}
  64. func = cmd2func[subcmd]
  65. func(db, dbdir)
  66. if __name__ == "__main__":
  67. main(*sys.argv) # pylint: disable=no-value-for-parameter