Coverage for app/venv/lib/python3.14/site-packages/weblate/auth/management/commands/importusers.py: 0%

48 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 07:15 +0000

1# Copyright © Michal Čihař <michal@weblate.org> 

2# 

3# SPDX-License-Identifier: GPL-3.0-or-later 

4from __future__ import annotations 

5 

6import json 

7from pathlib import Path 

8from typing import TYPE_CHECKING 

9 

10from django.core.management.base import CommandError 

11 

12from weblate.auth.models import User 

13from weblate.utils.management.base import BaseCommand 

14 

15if TYPE_CHECKING: 

16 from django.core.management.base import CommandParser 

17 

18 

19class Command(BaseCommand): 

20 help = "imports users from JSON dump of database" 

21 

22 def add_arguments(self, parser: CommandParser) -> None: 

23 parser.add_argument( 

24 "--check", 

25 action="store_true", 

26 help="Only check import, do not actually create users", 

27 ) 

28 parser.add_argument( 

29 "json-file", 

30 type=Path, 

31 help="JSON file containing user dump to import", 

32 ) 

33 

34 def handle(self, *args, **options) -> None: 

35 try: 

36 with options["json-file"].open("r") as handle: 

37 data = json.load(handle) 

38 except OSError as error: 

39 msg = f"Could not open file: {error}" 

40 raise CommandError(msg) from error 

41 

42 for line in data: 

43 if "fields" in line: 

44 line = line["fields"] 

45 

46 if "is_active" in line and not line["is_active"]: 

47 continue 

48 

49 username = line["username"] 

50 email = line["email"] 

51 

52 if not email or not username: 

53 self.stderr.write(f"Skipping {line}, has blank username or email") 

54 continue 

55 

56 if User.objects.filter(username=username).exists(): 

57 self.stderr.write(f"Skipping {username}, username exists") 

58 continue 

59 

60 if User.objects.filter(email=email).exists(): 

61 self.stderr.write(f"Skipping {email}, email exists") 

62 continue 

63 

64 last_name = line.get("last_name", "") 

65 first_name = line.get("first_name", "") 

66 if last_name and last_name not in first_name: 

67 full_name = f"{first_name} {last_name}" 

68 elif first_name: 

69 full_name = first_name 

70 elif last_name: 

71 full_name = last_name 

72 else: 

73 full_name = username 

74 

75 if not options["check"]: 

76 User.objects.create( 

77 username=username, 

78 full_name=full_name, 

79 password=line.get("password", ""), 

80 email=email, 

81 )