File: extractfile.py

package info (click to toggle)
openmolcas 25.02-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 170,204 kB
  • sloc: f90: 498,088; fortran: 139,779; python: 13,587; ansic: 5,745; sh: 745; javascript: 660; pascal: 460; perl: 325; makefile: 17
file content (166 lines) | stat: -rw-r--r-- 6,285 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# -*- coding: utf-8 -*-
#***********************************************************************
# This file is part of OpenMolcas.                                     *
#                                                                      *
# OpenMolcas is free software; you can redistribute it and/or modify   *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties.   *
# For more details see the full text of the license in the file        *
# LICENSE or in <http://www.gnu.org/licenses/>.                        *
#                                                                      *
# Copyright (C) 2015, Ignacio Fdez. Galván                             *
#***********************************************************************

from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.util.nodes import set_source_info
from sphinx.directives.code import container_wrapper, CodeBlock
import codecs
import os, os.path

# Create the extractfile directive
#
class ExtractFileDirective(Directive):
  has_content = True
  required_arguments = 1
  optional_arguments = 0
  final_argument_whitespace = False
  option_spec = {
  }

  def run(self):
    code = u'\n'.join(self.content)
    literal = nodes.literal_block(code, code)
    filename = self.arguments[0]
    addCode(self.state.document.settings.env, filename, code)
    return [literal]

# This is just a copy of the CodeBlock directive,
# with the filename argument and the additional extracting code
#
class ExtractCodeBlock(CodeBlock):
  has_content = True
  required_arguments = 0
  optional_arguments = 1
  final_argument_whitespace = False
  option_spec = {
    'force': directives.flag,
    'linenos': directives.flag,
    'dedent': int,
    'lineno-start': int,
    'emphasize-lines': directives.unchanged_required,
    'caption': directives.unchanged_required,
    'class': directives.class_option,
    'name': directives.unchanged,
    ###########################################
    'filename': directives.unchanged_required,
    ###########################################
  }
  def run(self):
    document = self.state.document
    code = '\n'.join(self.content)
    location = self.state_machine.get_source_and_line(self.lineno)
    linespec = self.options.get('emphasize-lines')
    if linespec:
      try:
        nlines = len(self.content)
        hl_lines = parselinenos(linespec, nlines)
        if any(i >= nlines for i in hl_lines):
          logger.warning(__('line number spec is out of range(1-%d): %r') %
                         (nlines, self.options['emphasize-lines']),
                         location=location)
        hl_lines = [x + 1 for x in hl_lines if x < nlines]
      except ValueError as err:
        return [document.reporter.warning(err, line=self.lineno)]
    else:
      hl_lines = None
    if 'dedent' in self.options:
      location = self.state_machine.get_source_and_line(self.lineno)
      lines = code.split('\n')
      lines = dedent_lines(lines, self.options['dedent'], location=location)
      code = '\n'.join(lines)
    literal = nodes.literal_block(code, code)  # type: Element
    if 'linenos' in self.options or 'lineno-start' in self.options:
      literal['linenos'] = True
    literal['classes'] += self.options.get('class', [])
    literal['force'] = 'force' in self.options
    if self.arguments:
      literal['language'] = self.arguments[0]
    else:
      literal['language'] = self.env.temp_data.get('highlight_language',
                                                   self.config.highlight_language)
    extra_args = literal['highlight_args'] = {}
    if hl_lines is not None:
      extra_args['hl_lines'] = hl_lines
    if 'lineno-start' in self.options:
      extra_args['linenostart'] = self.options['lineno-start']
    self.set_source_info(literal)
    caption = self.options.get('caption')
    if caption:
      try:
        literal = container_wrapper(self, literal, caption)
      except ValueError as exc:
        return [document.reporter.warning(exc, line=self.lineno)]
    self.add_name(literal)
    ###########################################
    filename = self.options.get('filename')
    addCode(self.state.document.settings.env, filename, code)
    ###########################################
    return [literal]
  def set_source_info(self, literal):
    try:
      super(ExtractCodeBlock, self).set_source_info(literal)
    except AttributeError:
      set_source_info(self, literal)

# Add code to the environment
#
def addCode (env, filename, code):
  # Add a global "FilesToExtract" attribute to the environment
  if not hasattr(env, 'FilesToExtract'):
    env.FilesToExtract = []
  filenames = [item['filename'] for item in env.FilesToExtract]
  i = 0
  # Prevent multiple files with the same name
  while (filename in filenames):
    i += 1
    filename = '%s.%i' % (filename, i)
  env.FilesToExtract.append({
    'docname': env.docname,
    'filename': filename,
    'content': code,
  })

# Extract the files to extract
#
def extractFiles (app, exception):
  env = app.builder.env
  if hasattr(env, 'FilesToExtract'):
    ext_dir = app.config.extract_dir
    for item in env.FilesToExtract:
      filename = os.path.join(ext_dir, item['filename'])
      directory = os.path.dirname(filename)
      if (not os.path.exists(directory)):
          os.makedirs(directory)
      try:
        with codecs.open(filename, 'w', 'utf-8') as extractedfile:
          extractedfile.write(item['content'])
      except:
        print ('Error creating file %s' % filename)

# Purge the extractfile items from a file when it is changed
#
def purge_FilesToExtract(app, env, docname):
  if hasattr(env, 'FilesToExtract'):
    env.FilesToExtract = [item for item in env.FilesToExtract
                          if item['docname'] != docname]

# Setup
#
def setup(app):
  app.add_directive('extractfile', ExtractFileDirective)
  app.add_directive('extractcode-block', ExtractCodeBlock)
  app.connect('env-purge-doc', purge_FilesToExtract)
  app.connect('build-finished', extractFiles)
  app.add_config_value('extract_dir', 'extracted_files', '')