trash 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #! /usr/bin/env python3
  2. from pathlib import Path
  3. import argparse
  4. import logging
  5. import sys
  6. import os
  7. import json
  8. DEFAULT_CONFIG = {
  9. 'trashes': [
  10. '$HOME/trash/',
  11. ]
  12. }
  13. def parse_args():
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument('names', nargs='+')
  16. return parser.parse_args()
  17. def lowest_mount(path: Path) -> Path:
  18. """Find lowest level mount point of given path"""
  19. while not path.is_mount() and path.parent != path:
  20. return lowest_mount(path.parent)
  21. return path
  22. def getconfig():
  23. config_file = Path('~/.config/trash.json').expanduser()
  24. config = DEFAULT_CONFIG
  25. if config_file.is_file():
  26. with open(config_file) as f:
  27. config.update(json.load(f))
  28. return config
  29. def main():
  30. args = parse_args()
  31. logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
  32. config = getconfig()
  33. logging.debug(config)
  34. trashes = []
  35. for trashdir in config['trashes']:
  36. trashdir = Path(os.path.expandvars(trashdir)).expanduser().resolve()
  37. if not trashdir.is_dir():
  38. logging.info(f'new trash created at {trashdir}.')
  39. trashdir.mkdir()
  40. trashes.append(trashdir)
  41. for name in args.names:
  42. name = Path(os.path.expandvars(name))
  43. if not (name.is_file() or name.is_dir()):
  44. logging.warning(f'{name} is not a file nor directory')
  45. continue
  46. name = name.absolute()
  47. trashed = False
  48. for trashdir in trashes:
  49. try:
  50. if lowest_mount(trashdir) == lowest_mount(name):
  51. logging.info(f'Will move {name} to {trashdir}')
  52. trashed = True
  53. break
  54. except ValueError:
  55. pass
  56. if not trashed:
  57. logging.warning(f'Unable to trash {name}')
  58. if __name__ == '__main__':
  59. main()