| 146 | Directive.__init__(self, *args, **keys) |
| 147 | |
| 148 | def run(self): |
| 149 | settings = self.state.document.settings |
| 150 | if not settings.file_insertion_enabled: |
| 151 | raise self.warning(f'{self.name!r} directive disabled.') |
| 152 | |
| 153 | env = self.state.document.settings.env |
| 154 | rel_path, path = env.relfn2path(self.arguments[0]) |
| 155 | path = os.path.normpath(path) |
| 156 | encoding = self.options.get('encoding', settings.input_encoding) |
| 157 | e_handler = settings.input_encoding_error_handler |
| 158 | try: |
| 159 | settings.record_dependencies.add(path) |
| 160 | f = io.FileInput(source_path=path, encoding=encoding, |
| 161 | error_handler=e_handler) |
| 162 | except UnicodeEncodeError: |
| 163 | msg = (f'Problems with {self.name!r} directive path:\n' |
| 164 | f'Cannot encode input file path {path!r} (wrong locale?).') |
| 165 | raise self.severe(msg) |
| 166 | except IOError as error: |
| 167 | msg = f'Problems with {self.name!r} directive path:\n{error}.' |
| 168 | raise self.severe(msg) |
| 169 | raw_lines = f.read().splitlines() |
| 170 | f.close() |
| 171 | rst = None |
| 172 | lines = [] |
| 173 | for line in raw_lines: |
| 174 | if rst is not None and rst != '#': |
| 175 | # Bracket mode: check for end bracket |
| 176 | pos = line.find(rst) |
| 177 | if pos >= 0: |
| 178 | if line[0] == '#': |
| 179 | line = '' |
| 180 | else: |
| 181 | line = line[0:pos] |
| 182 | rst = None |
| 183 | else: |
| 184 | # Line mode: check for .rst start (bracket or line) |
| 185 | m = self.re_start.match(line) |
| 186 | if m: |
| 187 | rst = f']{m.group("eq")}]' |
| 188 | line = '' |
| 189 | elif line == '#.rst:': |
| 190 | rst = '#' |
| 191 | line = '' |
| 192 | elif rst == '#': |
| 193 | if line == '#' or line[:2] == '# ': |
| 194 | line = line[2:] |
| 195 | else: |
| 196 | rst = None |
| 197 | line = '' |
| 198 | elif rst is None: |
| 199 | line = '' |
| 200 | lines.append(line) |
| 201 | if rst is not None and rst != '#': |
| 202 | raise self.warning(f'{self.name!r} found unclosed bracket ' |
| 203 | f'"#[{rst[1:-1]}[.rst:" in {path!r}') |
| 204 | self.state_machine.insert_input(lines, path) |
| 205 | return [] |