# Buggy code
def handle(self, *args, **options):
    """Automatic import of components."""
    # Get project
    try:
        project = Project.objects.get(slug=options["project"])
    except Project.DoesNotExist:
        raise CommandError("Project does not exist!")

    # Get main component
    main_component = None
    if options["main_component"]:
        try:
            main_component = Component.objects.get(
                project=project, slug=options["main_component"]
            )
        except Component.DoesNotExist:
            raise CommandError("Main component does not exist!")

    try:
        data = json.load(options["json-file"])
    except ValueError:
        raise CommandError("Failed to parse JSON file!")
    finally:
        options["json-file"].close()

    for item in data:
        if "filemask" not in item or "name" not in item:
            raise CommandError("Missing required fields in JSON!")

        if "slug" not in item:
            item["slug"] = slugify(item["name"])

        if "repo" not in item:
            if main_component is None:
                raise CommandError("No main component and no repository URL!")
            item["repo"] = main_component.get_repo_link_url()

        item["project"] = project

        try:
            component = Component.objects.get(
                slug=item["slug"], project=item["project"]
            )
            self.stderr.write("Component {0} already exists".format(component))
            if options["ignore"]:
                continue
            if options["update"]:
                for key in item:
                    if key in ("project", "slug"):
                        continue
                    setattr(component, key, item[key])
                component.save()
                continue
            raise CommandError("Component already exists, use --ignore or --update!")

        except Component.DoesNotExist:
            component = Component.objects.create(**item)
            self.stdout.write(
                "Imported {0} with {1} translations".format(
                    component, component.translation_set.count()
                )
            )


# Traceback (weblate.vcs.base.RepositoryException)
Traceback (most recent call last):
File "/app/.global/bin/weblate", line 11, in <module>
sys.exit(main())
File "/app/.global/lib/python3.7/site-packages/weblate/runner.py", line 34, in main
execute_from_command_line(argv)
File "/app/.global/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/app/.global/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.global/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.global/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/app/.global/lib/python3.7/site-packages/weblate/trans/management/commands/import_json.py", line 143, in handle
component = Component.objects.create(**item)
File "/app/.global/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/app/.global/lib/python3.7/site-packages/django/db/models/query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "/app/.global/lib/python3.7/site-packages/weblate/trans/models/component.py", line 1388, in save
self.sync_git_repo(skip_push=kwargs.get('force_insert', False))
File "/app/.global/lib/python3.7/site-packages/weblate/trans/models/component.py", line 1055, in sync_git_repo
self.configure_branch()
File "/app/.global/lib/python3.7/site-packages/weblate/trans/models/component.py", line 606, in configure_branch
self.repository.configure_branch(self.branch)
File "/app/.global/lib/python3.7/site-packages/weblate/vcs/git.py", line 322, in configure_branch
['checkout', '-b', branch, 'origin/{0}'.format(branch)]
File "/app/.global/lib/python3.7/site-packages/weblate/vcs/base.py", line 188, in execute
args, self.path, fullcmd=fullcmd, local=self.local
File "/app/.global/lib/python3.7/site-packages/weblate/vcs/base.py", line 172, in _popen
output.decode('utf-8')
weblate.vcs.base.RepositoryException: fatal: Cannot update paths and switch to branch 'master' at the same time.
Did you intend to checkout 'origin/master' which can not be resolved as commit? (128)
Traceback (most recent call last):
File "/app/.global/lib/python3.7/site-packages/weblate/trans/management/commands/import_json.py", line 124, in handle
slug=item['slug'], project=item['project']
File "/app/.global/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/app/.global/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
weblate.trans.models.component.DoesNotExist: Component matching query does not exist.

# Fixed code
def handle(self, *args, **options):
    """Automatic import of components."""
    # Get project
    try:
        project = Project.objects.get(slug=options["project"])
    except Project.DoesNotExist:
        raise CommandError("Project does not exist!")

    # Get main component
    main_component = None
    if options["main_component"]:
        try:
            main_component = Component.objects.get(
                project=project, slug=options["main_component"]
            )
        except Component.DoesNotExist:
            raise CommandError("Main component does not exist!")

    try:
        data = json.load(options["json-file"])
    except ValueError:
        raise CommandError("Failed to parse JSON file!")
    finally:
        options["json-file"].close()

    for item in data:
        if "filemask" not in item or "name" not in item:
            raise CommandError("Missing required fields in JSON!")

        if "slug" not in item:
            item["slug"] = slugify(item["name"])

        if "repo" not in item:
            if main_component is None:
                raise CommandError("No main component and no repository URL!")
            item["repo"] = main_component.get_repo_link_url()

        item["project"] = project

        try:
            component = Component.objects.get(
                slug=item["slug"], project=item["project"]
            )
            self.stderr.write("Component {0} already exists".format(component))
            if options["ignore"]:
                continue
            if options["update"]:
                for key in item:
                    if key in ("project", "slug"):
                        continue
                    setattr(component, key, item[key])
                component.save()
                continue
            raise CommandError("Component already exists, use --ignore or --update!")

        except Component.DoesNotExist:
            component = Component(**item)
            try:
                component.full_clean()
            except ValidationError as error:
                for key, value in error.message_dict.items():
                    self.stderr.write("Error in {}: {}".format(key, ", ".join(value)))
                raise CommandError("Component failed validation!")
            component.save(force_insert=True)
            self.stdout.write(
                "Imported {0} with {1} translations".format(
                    component, component.translation_set.count()
                )
            )