Coverage for icloudpy/utils.py: 84%

32 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2024-04-12 14:26 +0000

1"""Utils.""" 

2import getpass 

3from sys import stdout 

4 

5import keyring 

6 

7from .exceptions import ICloudPyNoStoredPasswordAvailableException 

8 

9KEYRING_SYSTEM = "icloudpy://icloud-password" 

10 

11 

12def get_password(username, interactive=stdout.isatty() if stdout else False): 

13 """Get the password from a username.""" 

14 try: 

15 return get_password_from_keyring(username) 

16 except ICloudPyNoStoredPasswordAvailableException: 

17 if not interactive: 

18 raise 

19 

20 return getpass.getpass(f"Enter iCloud password for {username}: ") 

21 

22 

23def password_exists_in_keyring(username): 

24 """Return true if the password of a username exists in the keyring.""" 

25 try: 

26 get_password_from_keyring(username) 

27 except ICloudPyNoStoredPasswordAvailableException: 

28 return False 

29 

30 return True 

31 

32 

33def get_password_from_keyring(username): 

34 """Get the password from a username.""" 

35 result = keyring.get_password(KEYRING_SYSTEM, username) 

36 if result is None: 

37 raise ICloudPyNoStoredPasswordAvailableException( 

38 f"No iCloudPy password for {username} could be found " 

39 "in the system keychain. Use the `--store-in-keyring` " 

40 "command-line option for storing a password for this " 

41 "username." 

42 ) 

43 

44 return result 

45 

46 

47def store_password_in_keyring(username, password): 

48 """Store the password of a username.""" 

49 return keyring.set_password(KEYRING_SYSTEM, username, password) 

50 

51 

52def delete_password_in_keyring(username): 

53 """Delete the password of a username.""" 

54 return keyring.delete_password(KEYRING_SYSTEM, username) 

55 

56 

57def underscore_to_camelcase(word, initial_capital=False): 

58 """Transform a word to camelCase.""" 

59 words = [x.capitalize() or "_" for x in word.split("_")] 

60 if not initial_capital: 

61 words[0] = words[0].lower() 

62 

63 return "".join(words)