Skip to content

Commit 4fd1c89

Browse files
cli/discover: remove local collections if the remote collection is deleted
This works when the destination backend is 'filesystem' and the source is CalDAV-calendar-home-set. pimutils#868
1 parent 73ca56c commit 4fd1c89

File tree

9 files changed

+106
-8
lines changed

9 files changed

+106
-8
lines changed

CHANGELOG.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ Version 0.19.0
2222
==============
2323

2424
- Add "shell" password fetch strategy to pass command string to a shell.
25+
- Add ``implicit`` option to storage section. It creates/deletes implicitly
26+
collections in the destinations, when new collections are created/deleted
27+
in the source. The deletion is implemented only for the "filesystem" storage.
28+
See :ref:`storage_config`.
2529
- Add "description" and "order" as metadata. These fetch the CalDAV:
2630
calendar-description, ``CardDAV:addressbook-description`` and
2731
``apple-ns:calendar-order`` properties respectively.

docs/config.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,8 @@ Local
373373
#encoding = "utf-8"
374374
#post_hook = null
375375
#fileignoreext = ".tmp"
376+
#implicit = "create"
377+
#implicit = ["create", "delete"]
376378

377379
Can be used with `khal <http://lostpackets.de/khal/>`_. See :doc:`vdir` for
378380
a more formal description of the format.
@@ -395,6 +397,12 @@ Local
395397
new/updated file.
396398
:param fileeignoreext: The file extention to ignore. It is only useful
397399
if fileext is set to the empty string. The default is ``.tmp``.
400+
:param implicit: When a new collection is created on the source,
401+
create it in the destination without asking questions, when
402+
the value is "create". When the value is "delete" and a collection
403+
is removed on the source, remove it in the destination. The value
404+
can be a string or an array of strings. The deletion is implemented
405+
only for the "filesystem" storage.
398406

399407
.. storage:: singlefile
400408

tests/system/cli/test_config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,9 @@ def test_read_config(read_config):
6060
"yesno": False,
6161
"number": 42,
6262
"instance_name": "bob_a",
63+
"implicit": [],
6364
},
64-
"bob_b": {"type": "carddav", "instance_name": "bob_b"},
65+
"bob_b": {'type': "carddav", "instance_name": "bob_b", "implicit": []},
6566
}
6667

6768

tests/system/utils/test_main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def test_get_storage_init_args():
2020
from vdirsyncer.storage.memory import MemoryStorage
2121

2222
all, required = utils.get_storage_init_args(MemoryStorage)
23-
assert all == {"fileext", "collection", "read_only", "instance_name"}
23+
assert all == {"fileext", "collection", "read_only", "instance_name", "implicit"}
2424
assert not required
2525

2626

vdirsyncer/cli/config.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,13 @@ def _parse_section(self, section_type, name, options):
113113
raise ValueError("More than one general section.")
114114
self._general = options
115115
elif section_type == "storage":
116+
if "implicit" not in options:
117+
options["implicit"] = []
118+
elif isinstance(options["implicit"], str):
119+
options["implicit"] = [options['implicit']]
120+
elif not isinstance(options["implicit"], list):
121+
raise ValueError(
122+
"`implicit` parameter must be a list, string or absent.")
116123
self._storages[name] = options
117124
elif section_type == "pair":
118125
self._pairs[name] = options

vdirsyncer/cli/discover.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
import aiohttp
88
import aiostream
99

10+
from . import cli_logger
1011
from .. import exceptions
1112
from .utils import handle_collection_not_found
13+
from .utils import handle_collection_was_removed
1214
from .utils import handle_storage_init_error
1315
from .utils import load_status
1416
from .utils import save_status
@@ -104,6 +106,29 @@ async def collections_for_pair(
104106
_handle_collection_not_found=handle_collection_not_found,
105107
)
106108
)
109+
if "from b" in (pair.collections or []):
110+
only_in_a = set((await a_discovered.get_self()).keys()) - set(
111+
(await b_discovered.get_self()).keys())
112+
if only_in_a and "delete" in pair.config_a["implicit"]:
113+
for a in only_in_a:
114+
try:
115+
handle_collection_was_removed(pair.config_a, a)
116+
save_status(status_path, pair.name, a, data_type="metadata")
117+
save_status(status_path, pair.name, a, data_type="items")
118+
except NotImplementedError as e:
119+
cli_logger.error(e)
120+
121+
if "from a" in (pair.collections or []):
122+
only_in_b = set((await b_discovered.get_self()).keys()) - set(
123+
(await a_discovered.get_self()).keys())
124+
if only_in_b and "delete" in pair.config_b["implicit"]:
125+
for b in only_in_b:
126+
try:
127+
handle_collection_was_removed(pair.config_b, b)
128+
save_status(status_path, pair.name, b, data_type="metadata")
129+
save_status(status_path, pair.name, b, data_type="items")
130+
except NotImplementedError as e:
131+
cli_logger.error(e)
107132

108133
await _sanity_check_collections(rv, connector=connector)
109134

vdirsyncer/cli/utils.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,10 +227,15 @@ def manage_sync_status(base_path, pair_name, collection_name):
227227

228228
def save_status(base_path, pair, collection=None, data_type=None, data=None):
229229
assert data_type is not None
230-
assert data is not None
231230
status_name = get_status_name(pair, collection)
232231
path = expand_path(os.path.join(base_path, status_name)) + "." + data_type
233232
prepare_status_path(path)
233+
if data is None:
234+
try:
235+
os.remove(path)
236+
except OSError: # the file has not existed
237+
pass
238+
return
234239

235240
with atomic_write(path, mode="w", overwrite=True) as f:
236241
json.dump(data, f)
@@ -330,6 +335,19 @@ def assert_permissions(path, wanted):
330335
os.chmod(path, wanted)
331336

332337

338+
def handle_collection_was_removed(config, collection):
339+
if "delete" in config["implicit"]:
340+
storage_type = config["type"]
341+
cls, config = storage_class_from_config(config)
342+
config["collection"] = collection
343+
try:
344+
args = cls.delete_collection(**config)
345+
args["type"] = storage_type
346+
return args
347+
except NotImplementedError as e:
348+
cli_logger.error(e)
349+
350+
333351
async def handle_collection_not_found(config, collection, e=None):
334352
storage_name = config.get("instance_name", None)
335353

@@ -339,7 +357,8 @@ async def handle_collection_not_found(config, collection, e=None):
339357
)
340358
)
341359

342-
if click.confirm("Should vdirsyncer attempt to create it?"):
360+
if "create" in config["implicit"] or click.confirm(
361+
"Should vdirsyncer attempt to create it?"):
343362
storage_type = config["type"]
344363
cls, config = storage_class_from_config(config)
345364
config["collection"] = collection

vdirsyncer/storage/base.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ class Storage(metaclass=StorageMeta):
5252
5353
:param read_only: Whether the synchronization algorithm should avoid writes
5454
to this storage. Some storages accept no value other than ``True``.
55+
:param implicit: Whether the synchronization shall create/delete collections
56+
in the destination, when these were created/removed from the source. Must
57+
be a possibly empty list of strings.
5558
"""
5659

5760
fileext = ".txt"
@@ -75,9 +78,16 @@ class Storage(metaclass=StorageMeta):
7578
# The attribute values to show in the representation of the storage.
7679
_repr_attributes: List[str] = []
7780

78-
def __init__(self, instance_name=None, read_only=None, collection=None):
81+
def __init__(self, instance_name=None, read_only=None, collection=None,
82+
implicit=None):
7983
if read_only is None:
8084
read_only = self.read_only
85+
if implicit is None:
86+
self.implicit = []
87+
elif isinstance(implicit, str):
88+
self.implicit = [implicit]
89+
else:
90+
self.implicit = implicit
8191
if self.read_only and not read_only:
8292
raise exceptions.UserError("This storage can only be read-only.")
8393
self.read_only = bool(read_only)
@@ -119,6 +129,18 @@ async def create_collection(cls, collection, **kwargs):
119129
"""
120130
raise NotImplementedError
121131

132+
@classmethod
133+
def delete_collection(cls, collection, **kwargs):
134+
'''
135+
Delete the specified collection and return the new arguments.
136+
137+
``collection=None`` means the arguments are already pointing to a
138+
possible collection location.
139+
140+
The returned args should contain the collection name, for UI purposes.
141+
'''
142+
raise NotImplementedError()
143+
122144
def __repr__(self):
123145
try:
124146
if self.instance_name:

vdirsyncer/storage/filesystem.py

Lines changed: 15 additions & 3 deletions
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
@@ -61,9 +62,7 @@ async def discover(cls, path, **kwargs):
6162
def _validate_collection(cls, path):
6263
if not os.path.isdir(path) or os.path.islink(path):
6364
return False
64-
if os.path.basename(path).startswith("."):
65-
return False
66-
return True
65+
return not os.path.basename(path).startswith(".")
6766

6867
@classmethod
6968
async def create_collection(cls, collection, **kwargs):
@@ -79,6 +78,19 @@ async def create_collection(cls, collection, **kwargs):
7978
kwargs["collection"] = collection
8079
return kwargs
8180

81+
@classmethod
82+
def delete_collection(cls, collection, **kwargs):
83+
kwargs = dict(kwargs)
84+
path = kwargs['path']
85+
86+
if collection is not None:
87+
path = os.path.join(path, collection)
88+
shutil.rmtree(path, ignore_errors=True)
89+
90+
kwargs["path"] = path
91+
kwargs["collection"] = collection
92+
return kwargs
93+
8294
def _get_filepath(self, href):
8395
return os.path.join(self.path, href)
8496

0 commit comments

Comments
 (0)