Skip to content

Commit 4ca0e6b

Browse files
dilyanpalauzovHugo Osvaldo Barrera
authored and
Hugo Osvaldo Barrera
committed
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 6af4dd1 commit 4ca0e6b

File tree

9 files changed

+116
-8
lines changed

9 files changed

+116
-8
lines changed

CHANGELOG.rst

+4
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ Version 0.19.0
2929
you're validating certificate fingerprints, use `sha256` instead.
3030
- The ``google`` storage types no longer require ``requests-oauthlib``, but
3131
require ``python-aiohttp-oauthlib`` instead.
32+
- Add ``implicit`` option to storage section. It creates/deletes implicitly
33+
collections in the destinations, when new collections are created/deleted
34+
in the source. The deletion is implemented only for the "filesystem" storage.
35+
See :ref:`storage_config`.
3236

3337
Version 0.18.0
3438
==============

docs/config.rst

+8
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,8 @@ Local
415415
#encoding = "utf-8"
416416
#post_hook = null
417417
#fileignoreext = ".tmp"
418+
#implicit = "create"
419+
#implicit = ["create", "delete"]
418420

419421
Can be used with `khal <http://lostpackets.de/khal/>`_. See :doc:`vdir` for
420422
a more formal description of the format.
@@ -437,6 +439,12 @@ Local
437439
new/updated file.
438440
:param fileeignoreext: The file extention to ignore. It is only useful
439441
if fileext is set to the empty string. The default is ``.tmp``.
442+
:param implicit: When a new collection is created on the source, and the
443+
value is "create", create the collection in the destination without
444+
asking questions. When the value is "delete" and a collection
445+
is removed on the source, remove it in the destination. The value
446+
can be a string or an array of strings. The deletion is implemented
447+
only for the "filesystem" storage.
440448

441449
.. storage:: singlefile
442450

tests/system/cli/test_config.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,13 @@ def test_read_config(read_config):
6060
"yesno": False,
6161
"number": 42,
6262
"instance_name": "bob_a",
63+
"implicit": [],
64+
},
65+
"bob_b": {
66+
"type": "carddav",
67+
"instance_name": "bob_b",
68+
"implicit": [],
6369
},
64-
"bob_b": {"type": "carddav", "instance_name": "bob_b"},
6570
}
6671

6772

tests/system/utils/test_main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def test_get_storage_init_args():
2121
from vdirsyncer.storage.memory import MemoryStorage
2222

2323
all, required = utils.get_storage_init_args(MemoryStorage)
24-
assert all == {"fileext", "collection", "read_only", "instance_name"}
24+
assert all == {"fileext", "collection", "read_only", "instance_name", "implicit"}
2525
assert not required
2626

2727

vdirsyncer/cli/config.py

+8
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,14 @@ def _parse_section(self, section_type, name, options):
115115
raise ValueError("More than one general section.")
116116
self._general = options
117117
elif section_type == "storage":
118+
if "implicit" not in options:
119+
options["implicit"] = []
120+
elif isinstance(options["implicit"], str):
121+
options["implicit"] = [options["implicit"]]
122+
elif not isinstance(options["implicit"], list):
123+
raise ValueError(
124+
"`implicit` parameter must be a list, string or absent."
125+
)
118126
self._storages[name] = options
119127
elif section_type == "pair":
120128
self._pairs[name] = options

vdirsyncer/cli/discover.py

+29
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
import aiostream
99

1010
from .. import exceptions
11+
from . import cli_logger
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
@@ -118,6 +120,33 @@ async def collections_for_pair(
118120
"cache_key": cache_key,
119121
},
120122
)
123+
124+
if "from b" in (pair.collections or []):
125+
only_in_a = set(a_discovered.get_self().keys()) - set(
126+
b_discovered.get_self().keys()
127+
)
128+
if only_in_a and "delete" in pair.config_a["implicit"]:
129+
for a in only_in_a:
130+
try:
131+
handle_collection_was_removed(pair.config_a, a)
132+
save_status(status_path, pair.name, a, data_type="metadata")
133+
save_status(status_path, pair.name, a, data_type="items")
134+
except NotImplementedError as e:
135+
cli_logger.error(e)
136+
137+
if "from a" in (pair.collections or []):
138+
only_in_b = set(b_discovered.get_self().keys()) - set(
139+
a_discovered.get_self().keys()
140+
)
141+
if only_in_b and "delete" in pair.config_b["implicit"]:
142+
for b in only_in_b:
143+
try:
144+
handle_collection_was_removed(pair.config_b, b)
145+
save_status(status_path, pair.name, b, data_type="metadata")
146+
save_status(status_path, pair.name, b, data_type="items")
147+
except NotImplementedError as e:
148+
cli_logger.error(e)
149+
121150
return rv
122151

123152

vdirsyncer/cli/utils.py

+22-2
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,15 @@ 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+
try:
239+
os.remove(path)
240+
except OSError: # the file has not existed
241+
pass
242+
return
238243

239244
with atomic_write(path, mode="w", overwrite=True) as f:
240245
json.dump(data, f)
@@ -334,6 +339,19 @@ def assert_permissions(path, wanted):
334339
os.chmod(path, wanted)
335340

336341

342+
def handle_collection_was_removed(config, collection):
343+
if "delete" in config["implicit"]:
344+
storage_type = config["type"]
345+
cls, config = storage_class_from_config(config)
346+
config["collection"] = collection
347+
try:
348+
args = cls.delete_collection(**config)
349+
args["type"] = storage_type
350+
return args
351+
except NotImplementedError as e:
352+
cli_logger.error(e)
353+
354+
337355
async def handle_collection_not_found(config, collection, e=None):
338356
storage_name = config.get("instance_name", None)
339357

@@ -343,7 +361,9 @@ async def handle_collection_not_found(config, collection, e=None):
343361
)
344362
)
345363

346-
if click.confirm("Should vdirsyncer attempt to create it?"):
364+
if "create" in config["implicit"] or click.confirm(
365+
"Should vdirsyncer attempt to create it?"
366+
):
347367
storage_type = config["type"]
348368
cls, config = storage_class_from_config(config)
349369
config["collection"] = collection

vdirsyncer/storage/base.py

+23-1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ class Storage(metaclass=StorageMeta):
4242
4343
:param read_only: Whether the synchronization algorithm should avoid writes
4444
to this storage. Some storages accept no value other than ``True``.
45+
:param implicit: Whether the synchronization shall create/delete collections
46+
in the destination, when these were created/removed from the source. Must
47+
be a possibly empty list of strings.
4548
"""
4649

4750
fileext = ".txt"
@@ -65,9 +68,16 @@ class Storage(metaclass=StorageMeta):
6568
# The attribute values to show in the representation of the storage.
6669
_repr_attributes = ()
6770

68-
def __init__(self, instance_name=None, read_only=None, collection=None):
71+
def __init__(
72+
self,
73+
instance_name=None,
74+
read_only=None,
75+
collection=None,
76+
implicit=None,
77+
):
6978
if read_only is None:
7079
read_only = self.read_only
80+
self.implicit = implicit # unused from within the Storage classes
7181
if self.read_only and not read_only:
7282
raise exceptions.UserError("This storage can only be read-only.")
7383
self.read_only = bool(read_only)
@@ -109,6 +119,18 @@ async def create_collection(cls, collection, **kwargs):
109119
"""
110120
raise NotImplementedError()
111121

122+
@classmethod
123+
def delete_collection(cls, collection, **kwargs):
124+
"""
125+
Delete the specified collection and return the new arguments.
126+
127+
``collection=None`` means the arguments are already pointing to a
128+
possible collection location.
129+
130+
The returned args should contain the collection name, for UI purposes.
131+
"""
132+
raise NotImplementedError()
133+
112134
def __repr__(self):
113135
try:
114136
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
@@ -62,9 +63,7 @@ async def discover(cls, path, **kwargs):
6263
def _validate_collection(cls, path):
6364
if not os.path.isdir(path):
6465
return False
65-
if os.path.basename(path).startswith("."):
66-
return False
67-
return True
66+
return not os.path.basename(path).startswith(".")
6867

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

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

0 commit comments

Comments
 (0)