Coverage for src/pyselector/helpers.py: 82%

38 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-24 11:53 -0300

1# helpers.ey 

2 

3import logging 

4import shutil 

5import subprocess 

6import sys 

7from typing import Iterable 

8from typing import Union 

9 

10from pyselector.interfaces import ExecutableNotFoundError 

11 

12ENCODE = sys.getdefaultencoding() 

13 

14 

15log = logging.getLogger(__name__) 

16 

17 

18def check_command(name: str, reference: str) -> str: 

19 command = shutil.which(name) 

20 if not command: 

21 raise ExecutableNotFoundError( 

22 f"command '{name}' not found in $PATH ({reference})" 

23 ) 

24 return command 

25 

26 

27def parse_bytes_line(b: bytes) -> str: 

28 return " ".join(b.decode(encoding="utf-8").split()) 

29 

30 

31def parse_multiple_bytes_lines(b: bytes) -> list[str]: 

32 multi = b.decode(encoding="utf-8").splitlines() 

33 return [" ".join(line.split()) for line in multi] 

34 

35 

36def get_clipboard_data() -> str: 

37 """Read clipboard to add a new bookmark.""" 

38 with subprocess.Popen( 

39 ["xclip", "-selection", "clipboard", "-o"], 

40 stdout=subprocess.PIPE, 

41 ) as proc: 

42 data = proc.stdout.read() 

43 return data.decode("utf-8") 

44 

45 

46def set_clipboard_data(url: str) -> None: 

47 """Copy selected bookmark to the system clipboard.""" 

48 data = bytes(url, "utf-8") 

49 with subprocess.Popen( 

50 ["xclip", "-selection", "clipboard"], 

51 stdin=subprocess.PIPE, 

52 ) as proc: 

53 proc.stdin.write(data) 

54 log.debug("Copied '%s' to clipboard", url) 

55 

56 

57def _execute(args: list[str], items: Iterable[Union[str, int]]) -> tuple[bytes, int]: 

58 log.debug("Executing: %s", args) 

59 with subprocess.Popen( 

60 args, 

61 stdout=subprocess.PIPE, 

62 stdin=subprocess.PIPE, 

63 ) as proc: 

64 items_str = list(map(str, items)) 

65 bytes_items = "\n".join(items_str).encode(encoding=ENCODE) 

66 selected, _ = proc.communicate(input=bytes_items) 

67 return_code = proc.wait() 

68 

69 if not selected: 

70 sys.exit(1) 

71 

72 return selected, return_code