fake_btrfs.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import argparse
  2. import json
  3. import os
  4. import shutil
  5. import sys
  6. def parse_arguments(*unparsed_arguments):
  7. global_parser = argparse.ArgumentParser(add_help=False)
  8. action_parsers = global_parser.add_subparsers(dest='action')
  9. subvolume_parser = action_parsers.add_parser('subvolume')
  10. subvolume_subparser = subvolume_parser.add_subparsers(dest='subaction')
  11. list_parser = subvolume_subparser.add_parser('list')
  12. list_parser.add_argument('-s', dest='snapshots_only', action='store_true')
  13. list_parser.add_argument('subvolume_path')
  14. snapshot_parser = subvolume_subparser.add_parser('snapshot')
  15. snapshot_parser.add_argument('-r', dest='read_only', action='store_true')
  16. snapshot_parser.add_argument('subvolume_path')
  17. snapshot_parser.add_argument('snapshot_path')
  18. delete_parser = subvolume_subparser.add_parser('delete')
  19. delete_parser.add_argument('snapshot_path')
  20. return global_parser.parse_args(unparsed_arguments)
  21. BUILTIN_SUBVOLUME_LIST_LINES = (
  22. '261 gen 29 top level 5 path sub',
  23. '262 gen 29 top level 5 path other',
  24. )
  25. SUBVOLUME_LIST_LINE_PREFIX = '263 gen 29 top level 5 path '
  26. def load_snapshots():
  27. try:
  28. return json.load(open('/tmp/fake_btrfs.json'))
  29. except FileNotFoundError:
  30. return []
  31. def save_snapshots(snapshot_paths):
  32. json.dump(snapshot_paths, open('/tmp/fake_btrfs.json', 'w'))
  33. def print_subvolume_list(arguments, snapshot_paths):
  34. assert arguments.subvolume_path == '/mnt/subvolume'
  35. if not arguments.snapshots_only:
  36. for line in BUILTIN_SUBVOLUME_LIST_LINES:
  37. print(line)
  38. for snapshot_path in snapshot_paths:
  39. print(SUBVOLUME_LIST_LINE_PREFIX + snapshot_path[snapshot_path.index('.borgmatic-snapshot-'):])
  40. def main():
  41. arguments = parse_arguments(*sys.argv[1:])
  42. snapshot_paths = load_snapshots()
  43. if arguments.subaction == 'list':
  44. print_subvolume_list(arguments, snapshot_paths)
  45. elif arguments.subaction == 'snapshot':
  46. snapshot_paths.append(arguments.snapshot_path)
  47. save_snapshots(snapshot_paths)
  48. subdirectory = os.path.join(arguments.snapshot_path, 'subdir')
  49. os.makedirs(subdirectory, mode=0o700, exist_ok=True)
  50. test_file = open(os.path.join(subdirectory, 'file.txt'), 'w')
  51. test_file.write('contents')
  52. test_file.close()
  53. elif arguments.subaction == 'delete':
  54. subdirectory = os.path.join(arguments.snapshot_path, 'subdir')
  55. shutil.rmtree(subdirectory)
  56. snapshot_paths = [
  57. snapshot_path for snapshot_path in snapshot_paths
  58. if snapshot_path.endswith('/' + arguments.snapshot_path)
  59. ]
  60. save_snapshots(snapshot_paths)
  61. if __name__ == '__main__':
  62. main()