Repository: pimutils/khal (python)

Issue:
Configuration file created by programing giving a critical error saying default is not valid
After creating the configuration file using the built in configuration tool I get the error
``````
critical: in section [default] cal_local is not valid for 'default_calendar', must be one of ['default']
If your configuration file used to work, please have a look at the Changelog to see what changed.
``````
this is my configuration file
```
[calendars]

[[cal_local]]
path = ~/.calendars/*
type = discover

[locale]
timeformat = %I:%M %p
dateformat = %m/%d/%Y
longdateformat = %m/%d/%Y
datetimeformat = %m/%d/%Y %I:%M %p
longdatetimeformat = %m/%d/%Y %I:%M %p

[default]
default_calendar = cal_local
```
I have set up vdirsyncer correctly (unless I did it incorrectly for khal). Any suggestions for fixing my configuration file?

Pull request description:
Fix configure setting a valid default calendar
fix #1114 

Patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 8b8d2ef..0be8b07 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -17,7 +17,7 @@ not released
 * FIX if a `discover` collection is set to "readonly", discovered collections
   will now inherit the readonly property
 * FIX ikhal will not wrap date headers into the next line in narrow terminals
-  anymore
+* FIX `configure` should only suggest valid default collection names
 * NEW the `configure` command can now set up vdirsyncer
 * NEW better error message for misuses of `at` and `list`
 * NEW `discover` collection type now supports `**` (arbitrary depths)
diff --git a/khal/configwizard.py b/khal/configwizard.py
index 8da0554..0ef4965 100644
--- a/khal/configwizard.py
+++ b/khal/configwizard.py
@@ -34,7 +34,7 @@ import xdg
 from click import Choice, UsageError, confirm, prompt
 
 from .exceptions import FatalError
-from .settings import find_configuration_file
+from .settings import find_configuration_file, utils
 
 logger = logging.getLogger('khal')
 
@@ -122,8 +122,20 @@ def choose_time_format():
     return timeformat
 
 
+def get_collection_names_from_vdirs(vdirs):
+    names = []
+    for name, path, vtype in sorted(vdirs or ()):
+        if vtype == 'discover':
+            for vpath in utils.get_all_vdirs(utils.expand_path(path)):
+                names.append(utils.get_unique_name(vpath, names))
+        else:
+            names.append(name)
+    return names
+
+
 def choose_default_calendar(vdirs):
-    names = [name for name, _, _ in sorted(vdirs or ())]
+    names = get_collection_names_from_vdirs(vdirs)
+
     print("Which calendar do you want as a default calendar?")
     print("(The default calendar is used when no calendar is specified.)")
     print(f"Configured calendars: {', '.join(names)}")


Test patch:
diff --git a/tests/cli_test.py b/tests/cli_test.py
index bd32a27..47bc027 100644
--- a/tests/cli_test.py
+++ b/tests/cli_test.py
@@ -632,7 +632,25 @@ def test_configure_command(runner):
     result = runner.invoke(main_khal, ['configure'], input=choices())
     assert f'Successfully wrote configuration to {runner.config_file}' in result.output
     assert result.exit_code == 0
-    # TODO check the config file again
+    with open(str(runner.config_file)) as f:
+        actual_config = ''.join(f.readlines())
+
+    assert actual_config == f'''[calendars]
+
+[[private]]
+path = {runner.tmpdir}/vdirs/khal/calendars/private
+type = calendar
+
+[locale]
+timeformat = %H:%M
+dateformat = %Y-%m-%d
+longdateformat = %Y-%m-%d
+datetimeformat = %Y-%m-%d %H:%M
+longdatetimeformat = %Y-%m-%d %H:%M
+
+[default]
+default_calendar = private
+'''
 
     # if aborting, no config file should be written
     runner = runner_factory()
diff --git a/tests/configwizard_test.py b/tests/configwizard_test.py
index 80923a0..1b2a52a 100644
--- a/tests/configwizard_test.py
+++ b/tests/configwizard_test.py
@@ -1,7 +1,7 @@
 import click
 import pytest
 
-from khal.configwizard import validate_int
+from khal.configwizard import get_collection_names_from_vdirs, validate_int
 
 
 def test_validate_int():
@@ -10,3 +10,11 @@ def test_validate_int():
         validate_int('3', 0, 2)
     with pytest.raises(click.UsageError):
         validate_int('two', 0, 2)
+
+
+def test_default_vdir(metavdirs):
+    names = get_collection_names_from_vdirs([('found', f'{metavdirs}/**/', 'discover')])
+    assert names == [
+        'my private calendar', 'my calendar', 'public', 'home', 'public1', 'work',
+        'cfgcolor', 'cfgcolor_again', 'cfgcolor_once_more', 'dircolor', 'singlecollection',
+    ]
diff --git a/tests/conftest.py b/tests/conftest.py
index 289c927..d5e436e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -12,6 +12,37 @@ from khal.khalendar.vdir import Vdir
 from .utils import LOCALE_BERLIN, CollVdirType, cal1, example_cals
 
 
+@pytest.fixture
+def metavdirs(tmpdir):
+    tmpdir = str(tmpdir)
+    dirstructure = [
+        '/cal1/public/',
+        '/cal1/private/',
+        '/cal2/public/',
+        '/cal3/public/',
+        '/cal3/work/',
+        '/cal3/home/',
+        '/cal4/cfgcolor/',
+        '/cal4/dircolor/',
+        '/cal4/cfgcolor_again/',
+        '/cal4/cfgcolor_once_more/',
+        '/singlecollection/',
+    ]
+    for one in dirstructure:
+        os.makedirs(tmpdir + one)
+    filestructure = [
+        ('/cal1/public/displayname', 'my calendar'),
+        ('/cal1/public/color', 'dark blue'),
+        ('/cal1/private/displayname', 'my private calendar'),
+        ('/cal1/private/color', '#FF00FF'),
+        ('/cal4/dircolor/color', 'dark blue'),
+    ]
+    for filename, content in filestructure:
+        with open(tmpdir + filename, 'w') as metafile:
+            metafile.write(content)
+    return tmpdir
+
+
 @pytest.fixture
 def coll_vdirs(tmpdir) -> CollVdirType:
     calendars, vdirs = {}, {}
diff --git a/tests/settings_test.py b/tests/settings_test.py
index 1d937bd..b9b411a 100644
--- a/tests/settings_test.py
+++ b/tests/settings_test.py
@@ -158,37 +158,6 @@ default_calendar = home
             config_checks(get_config(conf_path))
 
 
-@pytest.fixture
-def metavdirs(tmpdir):
-    tmpdir = str(tmpdir)
-    dirstructure = [
-        '/cal1/public/',
-        '/cal1/private/',
-        '/cal2/public/',
-        '/cal3/public/',
-        '/cal3/work/',
-        '/cal3/home/',
-        '/cal4/cfgcolor/',
-        '/cal4/dircolor/',
-        '/cal4/cfgcolor_again/',
-        '/cal4/cfgcolor_once_more/',
-        '/singlecollection/',
-    ]
-    for one in dirstructure:
-        os.makedirs(tmpdir + one)
-    filestructure = [
-        ('/cal1/public/displayname', 'my calendar'),
-        ('/cal1/public/color', 'dark blue'),
-        ('/cal1/private/displayname', 'my private calendar'),
-        ('/cal1/private/color', '#FF00FF'),
-        ('/cal4/dircolor/color', 'dark blue'),
-    ]
-    for filename, content in filestructure:
-        with open(tmpdir + filename, 'w') as metafile:
-            metafile.write(content)
-    return tmpdir
-
-
 def test_broken_color(metavdirs):
     path = metavdirs
     newvdir = path + '/cal5/'