Skip to content

Commit 1c1cd3f

Browse files
cli/discover: remove/add local collections if the remote collection is deleted/created
This works when the destination backend is 'filesystem'. -- add a new parameter to storage section: implicit = ["create", "delete"] Changes cli/utils.py:save_status(): when data is None, remove the underlaying file.
1 parent a42906b commit 1c1cd3f

File tree

6 files changed

+85
-7
lines changed

6 files changed

+85
-7
lines changed

CHANGELOG.rst

+7
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ Package maintainers and users who have to manually update their installation
99
may want to subscribe to `GitHub's tag feed
1010
<https://github.com/pimutils/vdirsyncer/tags.atom>`_.
1111

12+
Unreleased 0.1
13+
==============
14+
- Add ``implicit`` option to storage section. It creates/deletes implicitly
15+
collections in the destinations, when new collections are created/deleted
16+
in the source. The deletion is implemented only for the "filesystem" storage.
17+
See :ref:`storage_config`.
18+
1219
Version 0.16.8
1320
==============
1421

docs/config.rst

+8
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,8 @@ Local
408408
fileext = "..."
409409
#encoding = "utf-8"
410410
#post_hook = null
411+
#implicit = "create"
412+
#implicit = ["create", "delete"]
411413

412414
Can be used with `khal <http://lostpackets.de/khal/>`_. See :doc:`vdir` for
413415
a more formal description of the format.
@@ -426,6 +428,12 @@ Local
426428
:param post_hook: A command to call for each item creation and
427429
modification. The command will be called with the path of the
428430
new/updated file.
431+
:param implicit: When a new collection is created on the source, and the
432+
value is "create", create the collection in the destination without
433+
asking questions. When the value is "delete" and a collection
434+
is removed on the source, remove it in the destination. The value
435+
can be a string or an array of strings. The deletion is implemented
436+
only for the "filesystem" storage.
429437

430438
.. storage:: singlefile
431439

vdirsyncer/cli/discover.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from .. import exceptions
77
from ..utils import cached_property
8-
from .utils import handle_collection_not_found
8+
from .utils import handle_collection_not_found, handle_collection_was_removed
99
from .utils import handle_storage_init_error
1010
from .utils import load_status
1111
from .utils import save_status
@@ -80,6 +80,21 @@ def collections_for_pair(status_path, pair, from_cache=True,
8080
get_b_discovered=b_discovered.get_self,
8181
_handle_collection_not_found=handle_collection_not_found
8282
))
83+
only_in_b = set(b_discovered.get_self().keys()) - set(a_discovered.get_self().keys())
84+
if only_in_b and 'delete' in pair.config_b.get('implicit'):
85+
for b in only_in_b:
86+
try:
87+
handle_collection_was_removed(pair.config_b, b)
88+
try:
89+
save_status(status_path, pair.name, b, data_type='metadata', data=None)
90+
except:
91+
pass
92+
try:
93+
save_status(status_path, pair.name, b, data_type='items', data=None)
94+
except:
95+
pass
96+
except NotImplementedError as e:
97+
cli_logger.error(e)
8398

8499
_sanity_check_collections(rv)
85100

vdirsyncer/cli/utils.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,12 @@ def manage_sync_status(base_path, pair_name, collection_name):
231231

232232
def save_status(base_path, pair, collection=None, data_type=None, data=None):
233233
assert data_type is not None
234-
assert data is not None
235234
status_name = get_status_name(pair, collection)
236235
path = expand_path(os.path.join(base_path, status_name)) + '.' + data_type
237236
prepare_status_path(path)
237+
if data is None:
238+
os.remove(path)
239+
return
238240

239241
with atomic_write(path, mode='w', overwrite=True) as f:
240242
json.dump(data, f)
@@ -397,14 +399,27 @@ def assert_permissions(path, wanted):
397399
os.chmod(path, wanted)
398400

399401

402+
def handle_collection_was_removed(config, collection):
403+
if 'delete' in config.get('implicit'):
404+
storage_type = config['type']
405+
cls, config = storage_class_from_config(config)
406+
config['collection'] = collection
407+
try:
408+
args = cls.delete_collection(**config)
409+
args['type'] = storage_type
410+
return args
411+
except NotImplementedError as e:
412+
cli_logger.error(e)
413+
414+
400415
def handle_collection_not_found(config, collection, e=None):
401416
storage_name = config.get('instance_name', None)
402417

403418
cli_logger.warning('{}No collection {} found for storage {}.'
404419
.format(f'{e}\n' if e else '',
405420
json.dumps(collection), storage_name))
406421

407-
if click.confirm('Should vdirsyncer attempt to create it?'):
422+
if 'create' in config.get('implicit') or click.confirm('Should vdirsyncer attempt to create it?'):
408423
storage_type = config['type']
409424
cls, config = storage_class_from_config(config)
410425
config['collection'] = collection

vdirsyncer/storage/base.py

+22-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ class Storage(metaclass=StorageMeta):
4040
4141
:param read_only: Whether the synchronization algorithm should avoid writes
4242
to this storage. Some storages accept no value other than ``True``.
43+
:param implicit: Whether the synchronization shall create/delete collections
44+
in the destination, when these were created/removed from the source. Can
45+
be a string, an array of strings, or skipped.
4346
'''
4447

4548
fileext = '.txt'
@@ -63,9 +66,15 @@ class Storage(metaclass=StorageMeta):
6366
# The attribute values to show in the representation of the storage.
6467
_repr_attributes = ()
6568

66-
def __init__(self, instance_name=None, read_only=None, collection=None):
69+
def __init__(self, instance_name=None, read_only=None, collection=None, implicit=None):
6770
if read_only is None:
6871
read_only = self.read_only
72+
if implicit is None:
73+
self.implicit = []
74+
elif isinstance(implicit, str):
75+
self.implicit = [implicit]
76+
else:
77+
self.implicit = implicit
6978
if self.read_only and not read_only:
7079
raise exceptions.UserError('This storage can only be read-only.')
7180
self.read_only = bool(read_only)
@@ -105,6 +114,18 @@ def create_collection(cls, collection, **kwargs):
105114
'''
106115
raise NotImplementedError()
107116

117+
@classmethod
118+
def delete_collection(cls, collection, **kwargs):
119+
'''
120+
Delete the specified collection and return the new arguments.
121+
122+
``collection=None`` means the arguments are already pointing to a
123+
possible collection location.
124+
125+
The returned args should contain the collection name, for UI purposes.
126+
'''
127+
raise NotImplementedError()
128+
108129
def __repr__(self):
109130
try:
110131
if self.instance_name:

vdirsyncer/storage/filesystem.py

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import errno
22
import logging
33
import os
4+
import shutil
45
import subprocess
56

67
from atomicwrites import atomic_write
@@ -55,9 +56,7 @@ def discover(cls, path, **kwargs):
5556
def _validate_collection(cls, path):
5657
if not os.path.isdir(path):
5758
return False
58-
if os.path.basename(path).startswith('.'):
59-
return False
60-
return True
59+
return not os.path.basename(path).startswith('.')
6160

6261
@classmethod
6362
def create_collection(cls, collection, **kwargs):
@@ -73,6 +72,19 @@ def create_collection(cls, collection, **kwargs):
7372
kwargs['collection'] = collection
7473
return kwargs
7574

75+
@classmethod
76+
def delete_collection(cls, collection, **kwargs):
77+
kwargs = dict(kwargs)
78+
path = kwargs['path']
79+
80+
if collection is not None:
81+
path = os.path.join(path, collection)
82+
shutil.rmtree(path, ignore_errors=True)
83+
84+
kwargs['path'] = path
85+
kwargs['collection'] = collection
86+
return kwargs
87+
7688
def _get_filepath(self, href):
7789
return os.path.join(self.path, href)
7890

0 commit comments

Comments
 (0)