5.11%

105 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-10 18:56:07 +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 token = r'\includegraphics' # nosec B105 

12 pos_after = len(token) 

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

14 

15 

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

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

18 if include_graphics_line and '{' in include_graphics_line: 

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

20 else: 

21 return 'IMAGE_PATH_NOT_FOUND' 

22 

23 

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

25 """Later alligator.""" 

26 outgoing = [] 

27 modus = 'copy' 

28 label = NO_LABEL 

29 figure: list[str] = [] 

30 caption: list[str] = [] 

31 precondition = r'\begin{figure}' 

32 precondition_met = False 

33 for slot, line in enumerate(incoming): 

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

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

36 precondition_met = True 

37 outgoing.append(line) 

38 continue 

39 

40 if modus == 'copy': 

41 if is_include_graphics(line) and not precondition_met: 

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

43 log.error(f'line#{slot + 1}|{line.rstrip()}') 

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

45 adhoc_label = 'FIX-AT-SOURCE' 

46 try: 

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

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

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

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

51 log.info(adhoc_label) 

52 except Exception as err: 

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

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

55 try: 

56 token = extract_image_path(line) 

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

58 if lookup is not None: 

59 cand = lookup.get(token, None) 

60 if cand is not None: 

61 captain = cand 

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

63 else: 

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

65 else: 

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

67 except Exception as err: 

68 log.error( 

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

70 ) 

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

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

73 outgoing.append(line) 

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

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

76 elif is_include_graphics(line) and precondition_met: 

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

78 log.info(line.rstrip()) 

79 modus = 'figure' 

80 figure = [line] 

81 try: 

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

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

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

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

86 log.info(label) 

87 except Exception as err: 

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

89 caption = [] 

90 else: 

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

92 outgoing.append(line) 

93 continue 

94 

95 if modus == 'figure': 

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

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

98 caption.append(line) 

99 if not line.strip().endswith('}'): 

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

101 modus = 'caption' 

102 elif line.startswith(r'\end{figure}'): 

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

104 outgoing.extend(figure) 

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

106 if r'\label{' not in caption_text: 

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

108 if caption_text == caption_text.rstrip(): 

109 caption_text += '\n' 

110 outgoing.append(caption_text) 

111 outgoing.append(line) 

112 modus = 'copy' 

113 label = NO_LABEL 

114 precondition_met = False 

115 else: 

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

117 figure.append(line) 

118 continue 

119 

120 if modus == 'caption': 

121 caption.append(line) 

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

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

124 modus = 'figure' 

125 continue 

126 

127 return outgoing