Coverage for jutil/sftp.py: 86%

# Coverage for jutil/sftp.py : 86%

## 36 statements 34 run 2 missing 0 excluded 7 partial

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 import re

2 from typing import Tuple

3

4

5 SFTP_CONNECTION_STRING_REGEX_1 = re.compile(r'^([^@:]+)(:[^@]+)?@([^:]+)(:.+)?')

6

7

8 def parse_sftp_connection(connection: str, exceptions: bool = True) -> Tuple[str, str, str, str]: # noqa

9 """

10 Parses SFTP connection string.

11 Connection string format 'USERNAME(:PASSWORD)@HOST(:PATH)' or

12 semicolon separated key-value pairs for example 'username=xxx;host=xxx'.

13 Returns the match if hostname can be parsed correctly.

14 :param connection: str

15 :param exceptions: bool

16 :return: sftp_user, sftp_password, sftp_host, sftp_path

17 """

18 username, password, host, remote_path = '', '', '', ''

19 m = SFTP_CONNECTION_STRING_REGEX_1.match(connection)

20 if m:

21 groups = m.groups()

22 if len(groups) == 4: 22 ↛ 31line 22 didn't jump to line 31, because the condition on line 22 was never false

23 if m.group(1): 23 ↛ 25line 23 didn't jump to line 25, because the condition on line 23 was never false

24 username = str(m.group(1))

25 if m.group(2):

26 password = str(m.group(2))[1:]

27 if m.group(3): 27 ↛ 29line 27 didn't jump to line 29, because the condition on line 27 was never false

28 host = str(m.group(3))

29 if m.group(4):

30 remote_path = str(m.group(4))[1:]

31 if not host:

32 for pair_str in connection.replace(' ', '').split(';'):

33 key_value_pair = pair_str.split('=')

34 if len(key_value_pair) == 2: 34 ↛ 32line 34 didn't jump to line 32, because the condition on line 34 was never false

35 k, v = key_value_pair

36 k = k.lower()

37 if k.startswith('sftp_'): 37 ↛ 38line 37 didn't jump to line 38, because the condition on line 37 was never true

38 k = k[5:]

39 if k in ('username', 'user'):

40 username = v

41 elif k in ('password', 'passwd', 'pass'):

42 password = v

43 elif k in ('host', 'hostname'):

44 host = v

45 elif k in ('path', 'remote_path', 'dir'): 45 ↛ 32line 45 didn't jump to line 32, because the condition on line 45 was never false

46 remote_path = v

47 if not host and exceptions: 47 ↛ 48line 47 didn't jump to line 48, because the condition on line 47 was never true

48 raise Exception('Invalid SFTP connection string "{}"'.format(connection))

49 return username, password, host, remote_path