Skip to content

Commit

Permalink
feat: add command to change name of model
Browse files Browse the repository at this point in the history
fixes: lervag#12
  • Loading branch information
lervag committed Apr 21, 2020
1 parent f2393d3 commit fba5a10
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
20 changes: 20 additions & 0 deletions apy/anki.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,26 @@ def set_model(self, model_name):
self.col.models.setCurrent(model)
return model

def rename_model(self, old_model_name, new_model_name):
"""Rename a model"""
if old_model_name not in self.model_names:
click.echo('Can''t rename model!')
click.echo(f'No such model: {old_model_name}')
raise click.Abort()

# Change the name
model = self.get_model(old_model_name)
model['name'] = new_model_name

# Update local storage
self.model_name_to_id = {m['name']: m['id']
for m in self.col.models.all()}
self.model_names = self.model_name_to_id.keys()

# Save changes
self.col.models.save(model)
self.modified = True


def change_tags(self, query, tags, add=True):
"""Add/Remove tags from notes that match query"""
Expand Down
14 changes: 14 additions & 0 deletions apy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,20 @@ def tag(query, add_tags, remove_tags):
a.change_tags(query, remove_tags, add=False)


@main.group(context_settings=CONTEXT_SETTINGS, invoke_without_command=True)
@click.pass_context
def model(ctx):
"""Interact with Anki models."""

@model.command()
@click.argument('name1')
@click.argument('name2')
def rename(name1, name2):
"""Rename model from name1 to name2"""
with Anki(cfg['base']) as a:
a.rename_model(name1, name2)


if __name__ == '__main__':
# pylint: disable=no-value-for-parameter
main()
19 changes: 19 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Test model features"""
import os

from apy.anki import Anki


testDir = os.path.dirname(__file__)
testCol = testDir + '/data/test_base/Test/collection.anki2'


def test_rename_model():
"""Test that we can rename models"""
with Anki(path=testCol, debug=True) as a:
assert 'MyTest' in a.model_names

a.rename_model('MyTest', 'NewModelName')

assert 'NewModelName' in a.model_names
assert 'MyTest' not in a.model_names

0 comments on commit fba5a10

Please sign in to comment.