syncthing_folder: Factor folder configuration

The folder configuration is parametrized in one place, no need for
duplicates.
This commit is contained in:
Borjan Tchakaloff 2021-01-01 15:43:43 +01:00
parent 83e9add60c
commit 1136e9b06b

View File

@ -132,6 +132,13 @@ def get_config(module):
return json.loads(content) return json.loads(content)
# Get the folder configuration from the global configuration, if it exists
def get_folder_config(folder_id, config):
for folder in config['folders']:
if folder['id'] == folder_id:
return folder
return None
# Post the new configuration to Syncthing API # Post the new configuration to Syncthing API
def post_config(module, config, result): def post_config(module, config, result):
url, headers = make_headers(module.params['host'], module.params['api_key']) url, headers = make_headers(module.params['host'], module.params['api_key'])
@ -239,39 +246,16 @@ def run_module():
result['changed'] = True result['changed'] = True
break break
else: else:
# Bail-out if folder is already added folder_config = get_folder_config(module.params['id'], config)
for folder in config['folders']: folder_config_wanted = create_folder(module.params)
if folder['id'] == module.params['id']:
want_pause = module.params['state'] == 'pause'
already_configured = (
(want_pause and folder['paused'])
or
(not want_pause and not folder['paused'])
)
want_devices = sorted([ if folder_config is None:
{ config['folders'].append(folder_config_wanted)
'deviceID': device_id, result['changed'] = True
'introducedBy': '', elif folder_config != folder_config_wanted:
} for device_id in module.params['devices'] # Update the folder configuration in-place
], key=lambda d: d['deviceID']) folder_config.clear()
already_configured = ( folder_config.update(folder_config_wanted)
already_configured
and
want_devices == sorted(folder['devices'], key=lambda d: d['deviceID'])
)
if already_configured:
module.exit_json(**result)
else:
folder['paused'] = want_pause
result['changed'] = True
break
# Append the new folder into configuration
if not result['changed']:
folder = create_folder(module.params)
config['folders'].append(folder)
result['changed'] = True result['changed'] = True
if result['changed']: if result['changed']: