Coverage for pyguymer3/tar.py: 6%

17 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-08 18:47 +0000

1#!/usr/bin/env python3 

2 

3# Define function ... 

4def tar( 

5 tarName, 

6 fnames, 

7 /, 

8 *, 

9 cwd = None, 

10 stderr = None, 

11 stdout = None, 

12 tarPath = None, 

13 timeout = 60.0, 

14): 

15 """Create a PAX formatted TAR file (without any frills or size limits). 

16 

17 Parameters 

18 ---------- 

19 tarName : str 

20 the name of the TAR file to create 

21 fnames : list of str 

22 the list of files to put in the TAR file 

23 cwd : str, optional 

24 the child working directory (default None) 

25 stderr : subprocess.PIPE, subprocess.DEVNULL, io.TextIOWrapper, optional 

26 the destination of STDERR (default None) 

27 stdout : subprocess.PIPE, subprocess.DEVNULL, io.TextIOWrapper, optional 

28 the destination of STDOUT (default None) 

29 tarPath : str, optional 

30 the path to the "tar" binary (if not provided then Python will attempt 

31 to find the binary itself) 

32 timeout : float, optional 

33 the timeout for any requests/subprocess calls 

34 

35 Notes 

36 ----- 

37 I still need to provide justification for using this function over https://docs.python.org/3.12/library/tarfile.html 

38 

39 Copyright 2017 Thomas Guymer [1]_ 

40 

41 References 

42 ---------- 

43 .. [1] PyGuymer3, https://github.com/Guymer/PyGuymer3 

44 """ 

45 

46 # Import standard modules ... 

47 import shutil 

48 import subprocess 

49 import tempfile 

50 

51 # ************************************************************************** 

52 

53 # Try to find the paths if the user did not provide them ... 

54 if tarPath is None: 

55 tarPath = shutil.which("tar") 

56 assert tarPath is not None, "\"tar\" is not installed" 

57 

58 # Check inputs ... 

59 if not isinstance(fnames, list): 

60 raise Exception("\"fnames\" is not a list") from None 

61 if len(fnames) == 0: 

62 raise Exception("\"fnames\" is empty") from None 

63 

64 # Create temporary directory ... 

65 with tempfile.TemporaryDirectory(prefix = "tar.") as tname: 

66 # Deduce temporary name ... 

67 tmpName = f"{tname}/fnames.txt" 

68 

69 # Make list of files to archive ... 

70 with open(tmpName, "wt", encoding = "utf-8") as fObj: 

71 for fname in fnames: 

72 fObj.write(f"{fname}\n") 

73 

74 # Make archive ... 

75 subprocess.run( 

76 [ 

77 tarPath, 

78 "--create", 

79 "--file", tarName, 

80 "--files-from", tmpName, 

81 "--format", "pax", 

82 "--no-acls", 

83 "--no-fflags", 

84 "--no-xattrs", 

85 ], 

86 check = True, 

87 cwd = cwd, 

88 encoding = "utf-8", 

89 stderr = stderr, 

90 stdout = stdout, 

91 timeout = timeout, 

92 )