Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CLI option for custom metadata #124

Merged
merged 1 commit into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/tufup/repo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,8 @@ def add_bundle(
a patch file is also created and added to the repository, unless
`skip_patch` is True.

Optional `custom_metadata` can be specified as a dictionary.

If `required=True` (default is `False`), this release will always be
installed, even if newer releases are available. For example, suppose
an app is running at version 1.0, and version 2.0 is required, but version
Expand Down
20 changes: 20 additions & 0 deletions src/tufup/repo/cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import argparse
import json
import logging

import packaging.version
Expand All @@ -19,6 +20,7 @@
targets_add_bundle_dir='Directory containing application bundle.',
targets_add_skip_patch='Skip patch creation.',
targets_add_required='Mark release as "required".',
targets_add_meta='Specify custom metadata as a JSON object.',
targets_remove_latest='Remove latest app bundle from the repository.',
keys_subcommands='Optional commands to add or replace keys.',
keys_new_key_name='Name of new private key (public key gets .pub suffix).',
Expand All @@ -34,6 +36,15 @@
)


def json_object(arg: str) -> dict:
"""decodes a JSON object"""
value = json.loads(arg)
if not isinstance(value, dict):
# arg must represent a JSON object, which corresponds with a python dict
raise ValueError
return value


def _print_info(message: str):
return log_print(message=message, level=logging.INFO, logger=logger)

Expand Down Expand Up @@ -92,6 +103,14 @@ def get_parser() -> argparse.ArgumentParser:
required=False,
help=HELP['targets_add_required'],
)
subparser_targets_add.add_argument(
'-m',
'--meta',
action='store',
type=json_object,
required=False,
help=HELP['targets_add_meta'],
)
subparser_targets_remove = targets_subparsers.add_parser(
'remove-latest', help=HELP['targets_remove_latest']
)
Expand Down Expand Up @@ -281,6 +300,7 @@ def _cmd_targets(options: argparse.Namespace):
new_bundle_dir=options.bundle_dir,
skip_patch=options.skip_patch,
required=options.required,
custom_metadata=options.meta,
)
elif options.subcommand == 'remove-latest':
_print_info('Removing latest bundle...')
Expand Down
26 changes: 23 additions & 3 deletions tests/test_repo_cli.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import argparse
import json
import unittest
from unittest.mock import Mock, patch

Expand Down Expand Up @@ -33,9 +34,10 @@ def test_get_parser(self):
args = cmd.split()
options = parser.parse_args(args)
expected_func_name = '_cmd_' + args[0]
self.assertEqual(
args[0] in ['targets', 'keys'], hasattr(options, 'subcommand')
)
if args[0] in ['targets', 'keys']:
self.assertTrue(hasattr(options, 'subcommand'))
if args[:2] == ['targets', 'add']:
self.assertTrue(hasattr(options, 'meta'))
self.assertEqual(expected_func_name, options.func.__name__)

def test_get_parser_incomplete_commands(self):
Expand All @@ -54,6 +56,22 @@ def test_get_parser_incomplete_commands(self):
with self.assertRaises(SystemExit):
parser.parse_args(args)

def test_get_parser_meta_json(self):
parser = tufup.repo.cli.get_parser()
args = 'targets add 1.0 c:\\my_bundle_dir c:\\private_keys'.split()
with self.subTest(msg='no metadata'):
self.assertIsNone(parser.parse_args(args).meta)
json_object = '{"changes": ["line 1", "line2"]}'
with self.subTest(msg='valid json object'):
options = parser.parse_args(args + ['-m', json_object])
self.assertEqual(json.loads(json_object), options.meta)
with self.subTest(msg='invalid json'):
with self.assertRaises(SystemExit):
parser.parse_args(args + ['-m', '{'])
with self.subTest(msg='valid json but not an object'):
with self.assertRaises(SystemExit):
parser.parse_args(args + ['-m', '["item 1", "item 2"]'])


class CommandTests(TempDirTestCase):
def setUp(self) -> None:
Expand Down Expand Up @@ -142,6 +160,7 @@ def test__cmd_targets_add(self):
key_dirs=['c:\\my_private_keys'],
skip_patch=True,
required=False,
meta=dict(),
)
options = argparse.Namespace(**kwargs)
with patch('tufup.repo.cli.Repository', self.mock_repo_class):
Expand All @@ -151,6 +170,7 @@ def test__cmd_targets_add(self):
new_bundle_dir=kwargs['bundle_dir'],
skip_patch=kwargs['skip_patch'],
required=kwargs['required'],
custom_metadata=kwargs['meta'],
)
self.mock_repo.publish_changes.assert_called_with(
private_key_dirs=kwargs['key_dirs']
Expand Down
Loading