Skip to content

Commit a38bb96

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 a38bb96

File tree

7 files changed

+87
-9
lines changed

7 files changed

+87
-9
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-2
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
@@ -63,7 +63,6 @@ def collections_for_pair(status_path, pair, from_cache=True,
6363

6464
a_discovered = _DiscoverResult(pair.config_a)
6565
b_discovered = _DiscoverResult(pair.config_b)
66-
6766
if list_collections:
6867
_print_collections(pair.config_a['instance_name'],
6968
a_discovered.get_self)
@@ -80,6 +79,21 @@ def collections_for_pair(status_path, pair, from_cache=True,
8079
get_b_discovered=b_discovered.get_self,
8180
_handle_collection_not_found=handle_collection_not_found
8281
))
82+
only_in_b = set(b_discovered.get_self().keys()) - set(a_discovered.get_self().keys())
83+
if only_in_b and 'delete' in pair.config_b.get('implicit'):
84+
for b in only_in_b:
85+
try:
86+
handle_collection_was_removed(pair.config_b, b)
87+
try:
88+
save_status(status_path, pair.name, b, data_type='metadata', data=None)
89+
except:
90+
pass
91+
try:
92+
save_status(status_path, pair.name, b, data_type='items', data=None)
93+
except:
94+
pass
95+
except NotImplementedError as e:
96+
cli_logger.error(e)
8397

8498
_sanity_check_collections(rv)
8599

vdirsyncer/cli/tasks.py

-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818

1919
def prepare_pair(wq, pair_name, collections, config, callback, **kwargs):
2020
pair = config.get_pair(pair_name)
21-
2221
all_collections = dict(collections_for_pair(
2322
status_path=config.general['status_path'], pair=pair
2423
))

vdirsyncer/cli/utils.py

+19-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,29 @@ def assert_permissions(path, wanted):
397399
os.chmod(path, wanted)
398400

399401

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

403420
cli_logger.warning('{}No collection {} found for storage {}.'
404421
.format(f'{e}\n' if e else '',
405422
json.dumps(collection), storage_name))
406423

407-
if click.confirm('Should vdirsyncer attempt to create it?'):
424+
if 'create' in config.get('implicit') or click.confirm('Should vdirsyncer attempt to create it?'):
408425
storage_type = config['type']
409426
cls, config = storage_class_from_config(config)
410427
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)