Coverage for liitos/labels.py: 84.35%

111 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-11-25 15:36:16 +00:00

1from collections.abc import Iterable 

2from typing import Union 

3 

4from liitos import log 

5 

6NO_LABEL = 'no-label-found-ERROR' 

7 

8 

9def is_include_graphics(text: str) -> bool: 

10 """Only DRY.""" 

11 ntoken = r'\pandocbounded' # nosec B105 

12 pos_after = len(ntoken) 

13 if len(text) > len(ntoken) and text.startswith(ntoken) and text[pos_after] in ('[', '{'): 

14 return True 

15 token = r'\includegraphics' # nosec B105 

16 pos_after = len(token) 

17 return len(text) > len(token) and text.startswith(token) and text[pos_after] in ('[', '{') 

18 

19 

20def extract_image_path(include_graphics_line: str) -> str: 

21 """We had a bug, so we isolate in a function.""" 

22 if include_graphics_line and 'pandocbounded{' in include_graphics_line: 

23 return include_graphics_line.split('{', 2)[2].rstrip().rstrip('}') 

24 if include_graphics_line and '{' in include_graphics_line: 

25 return include_graphics_line.split('{', 1)[1].rstrip().rstrip('}') 

26 else: 

27 return 'IMAGE_PATH_NOT_FOUND' 

28 

29 

30def inject(incoming: Iterable[str], lookup: Union[dict[str, str], None] = None) -> list[str]: 

31 """Later alligator.""" 

32 outgoing = [] 

33 modus = 'copy' 

34 label = NO_LABEL 

35 figure: list[str] = [] 

36 caption: list[str] = [] 

37 precondition = r'\begin{figure}' 

38 precondition_met = False 

39 for slot, line in enumerate(incoming): 

40 if line.startswith(precondition) and not precondition_met: 

41 log.info(f'start of a figure environment at line #{slot + 1}') 

42 precondition_met = True 

43 outgoing.append(line) 

44 continue 

45 

46 if modus == 'copy': 

47 if is_include_graphics(line) and not precondition_met: 

48 log.warning(f'graphics include outside of a figure environment at line #{slot + 1}') 

49 log.debug(f'line#{slot + 1}|{line.rstrip()}') 

50 log.info('trying to fix temporarily ... watch for marker MISSING-CAPTION-IN-MARKDOWN') 

51 adhoc_label = 'FIX-AT-SOURCE' 

52 try: 

53 lab = line.split('{', 1)[1] 

54 lab = lab.rsplit('.', 1)[0] 

55 lab = lab.rsplit('/', 1)[1] 

56 adhoc_label = r'\label{fig:' + lab + '}' 

57 log.info(adhoc_label) 

58 except Exception as err: 

59 log.error(f'failed to extract generic label from {line.strip()} with err: {err}') 

60 captain = 'MISSING-CAPTION-IN-MARKDOWN' 

61 try: 

62 token = extract_image_path(line) 

63 log.debug(f'- looking up key ({token}) for captions ...') 

64 if lookup is not None: 

65 cand = lookup.get(token, None) 

66 if cand is not None: 

67 captain = cand 

68 log.debug(f' + found ({captain})') 

69 else: 

70 log.debug(f' ? no match for key ({token})') 

71 else: 

72 log.debug(' + no lut?') 

73 except Exception as err: 

74 log.error( 

75 f'failed to extract file path token for caption lookup from {line.strip()} with err: {err}' 

76 ) 

77 outgoing.append(r'\begin{figure}' + '\n') 

78 outgoing.append(r'\centering' + '\n') 

79 outgoing.append(line) 

80 outgoing.append(r'\caption{' + captain + ' ' + adhoc_label + '}' + '\n') 

81 outgoing.append(r'\end{figure}' + '\n') 

82 elif is_include_graphics(line) and precondition_met: 

83 log.info(f'within a figure environment at line #{slot + 1}') 

84 log.info(line.rstrip()) 

85 modus = 'figure' 

86 figure = [line] 

87 try: 

88 lab = line.split('{', 1)[1] 

89 lab = lab.rsplit('.', 1)[0] 

90 lab = lab.rsplit('/', 1)[1] 

91 label = r'\label{fig:' + lab + '}' 

92 log.info(label) 

93 except Exception as err: 

94 log.error(f'failed to extract generic label from {line.strip()} with err: {err}') 

95 caption = [] 

96 else: 

97 log.debug(f'- copying {slot + 1 :3d}|{line.rstrip()}') 

98 outgoing.append(line) 

99 continue 

100 

101 if modus == 'figure': 101 ↛ 126line 101 didn't jump to line 126 because the condition on line 101 was always true

102 if line.startswith(r'\caption{'): 

103 log.info(f'- found the caption start at line #{slot + 1}') 

104 caption.append(line) 

105 if not line.strip().endswith('}'): 105 ↛ 106line 105 didn't jump to line 106 because the condition on line 105 was never true

106 log.info(f'- multi line caption at line #{slot + 1}') 

107 modus = 'caption' 

108 elif line.startswith(r'\end{figure}'): 108 ↛ 122line 108 didn't jump to line 122 because the condition on line 108 was always true

109 log.info(f'end of figure env detected at line #{slot + 1}') 

110 outgoing.extend(figure) 

111 caption_text = '\n'.join(caption) 

112 if r'\label{' not in caption_text: 112 ↛ 114line 112 didn't jump to line 114 because the condition on line 112 was always true

113 caption_text = f"{caption_text.rstrip().rstrip('}')} {label}" + '}' 

114 if caption_text == caption_text.rstrip(): 114 ↛ 116line 114 didn't jump to line 116 because the condition on line 114 was always true

115 caption_text += '\n' 

116 outgoing.append(caption_text) 

117 outgoing.append(line) 

118 modus = 'copy' 

119 label = NO_LABEL 

120 precondition_met = False 

121 else: 

122 log.debug(f'- figure continues at line #{slot + 1}') 

123 figure.append(line) 

124 continue 

125 

126 if modus == 'caption': 

127 caption.append(line) 

128 if line.strip().endswith(r'}'): 

129 log.info(f'- caption read at line #{slot + 1}') 

130 modus = 'figure' 

131 continue 

132 

133 return outgoing