Example #1
0
    def createScriptDoc(self, script: str):
        """Create script description.

        Folders and indices already exist, just call the scripts and get the help messages. Format the help message.

        :return: Script -- system name, script name, parsed help message
        """
        executor = "bash"
        scriptName = os.path.basename(script)
        systemName = script.split("/")[-3].replace("System", "")
        if scriptName.endswith(".py"):
            executor = "python"
            scriptName = scriptName.replace("_", "-")[:-3]

        if scriptName in self.config.com_ignore_commands:
            return

        LOG.info("Creating Doc for %r", scriptName)
        helpMessage = runCommand("%s %s -h" % (executor, script))
        if not helpMessage:
            LOG.warning("NO DOC for %s", scriptName)
            helpMessage = "Oops, we couldn't generate a description for this command."

        # Script reference
        fileContent = textwrap.dedent(f"""

                .. _{scriptName}:

                {'-' * len(scriptName)}
                {scriptName}
                {'-' * len(scriptName)}

            """)

        # Script description payload
        rstLines = []
        genOptions = False
        lineIndented = False
        for line in helpMessage.splitlines():
            line = line.rstrip()
            newLine = "\n" + ":".join(line.rsplit(
                "::", 1)) + ":\n" if line.endswith(":") else line
            # ensure dedented lines are separated by newline from previous block
            if lineIndented and not newLine.startswith(" "):
                newLine = "\n" + newLine
            rstLines.append(newLine)
            lineIndented = newLine.startswith(" ")
        fileContent += "\n\n" + "\n".join(rstLines).strip() + "\n"

        # remove the standalone '-' when no short option exists
        fileContent = fileContent.replace("-   --", "    --")
        return Script(scriptName, systemName, fileContent)
Example #2
0
  def createScriptDocFiles(self, script, sectionPath, scriptName, referencePrefix=''):
    """Create the RST files for all the scripts.

    Folders and indices already exist, just call the scripts and get the help messages. Format the help message.

    """
    if scriptName in self.config.com_ignore_commands:
      return False

    LOG.info('Creating Doc for %r in %r', scriptName, sectionPath)
    helpMessage = runCommand('python %s -h' % script)
    if not helpMessage:
      LOG.warning('NO DOC for %s', scriptName)
      return False

    rstLines = []
    rstLines.append(' .. _%s%s:' % (referencePrefix, scriptName))
    rstLines.append('')
    rstLines.append('=' * len(scriptName))
    rstLines.append('%s' % scriptName)
    rstLines.append('=' * len(scriptName))
    rstLines.append('')
    lineIndented = False
    genOptions = False
    for line in helpMessage.splitlines():
      line = line.rstrip()
      if not line:
        pass
      # strip general options from documentation
      elif line.lower().strip() == 'general options:':
        LOG.debug("Found general options in line %r", line) if self.debug else None
        genOptions = True
        continue
      elif genOptions and line.startswith(' '):
        LOG.debug("Skipping General options line %r", line) if self.debug else None
        continue
      elif genOptions and not line.startswith(' '):
        LOG.debug("General options done") if self.debug else None
        genOptions = False

      newLine = '\n' + line + ':\n' if line.endswith(':') else line
      # ensure dedented lines are separated by newline from previous block
      if lineIndented and not newLine.startswith(' '):
        newLine = '\n' + newLine
      rstLines.append(newLine)
      lineIndented = newLine.startswith(' ')

    scriptRSTPath = os.path.join(sectionPath, scriptName + '.rst')
    fileContent = '\n'.join(rstLines).strip() + '\n'

    for index, marker in enumerate(['example', '.. note::']):
      if scriptName in self.config.com_module_docstring:
        if index == 0:
          content = self.getContentFromModuleDocstring(script)
          fileContent += '\n' + content.strip() + '\n'
      else:
        content = self.getContentFromScriptDoc(scriptRSTPath, marker)
        if not content:
          break  # nothing in content, files probably does not exist
        if content and marker not in fileContent.lower():
          fileContent += '\n' + content.strip() + '\n'
      LOG.debug('\n' + '*' * 88 + '\n' + fileContent + '\n' + '*' * 88) if self.debug else None
    while '\n\n\n' in fileContent:
      fileContent = fileContent.replace('\n\n\n', '\n\n')

    # remove the standalone '-' when no short option exists
    fileContent = fileContent.replace('-   --', '--')
    writeLinesToFile(scriptRSTPath, fileContent)
    return True
Example #3
0
    def createScriptDocFiles(self, script, sectionPath, sectionDict):
        """Create the RST files for all the scripts.

        Folders and indices already exist, just call the scripts and get the help messages. Format the help message.
        """
        scriptName = os.path.basename(script)
        if scriptName.endswith(".py"):
            scriptName = scriptName[:-3]
        scriptName = scriptName.replace("_", "-")
        referencePrefix = sectionDict[PREFIX].lower()
        referencePrefix = referencePrefix + "_" if referencePrefix else ""

        if scriptName in self.config.com_ignore_commands:
            return scriptName, False

        LOG.info("Creating Doc for %r in %r", scriptName, sectionPath)
        helpMessage = runCommand("python %s -h" % script)
        if not helpMessage:
            LOG.warning("NO DOC for %s", scriptName)
            return scriptName, False

        rstLines = []
        rstLines.append(" .. _%s%s:" % (referencePrefix, scriptName))
        rstLines.append("")
        rstLines.append("=" * len(scriptName))
        rstLines.append("%s" % scriptName)
        rstLines.append("=" * len(scriptName))
        rstLines.append("")
        lineIndented = False
        genOptions = False
        for line in helpMessage.splitlines():
            line = line.rstrip()
            if not line:
                pass
            # strip general options from documentation
            elif line.lower().strip() == "general options:":
                LOG.debug("Found general options in line %r", line) if self.debug else None
                genOptions = True
                continue
            elif genOptions and line.startswith(" "):
                LOG.debug("Skipping General options line %r", line) if self.debug else None
                continue
            elif genOptions and not line.startswith(" "):
                LOG.debug("General options done") if self.debug else None
                genOptions = False

            newLine = "\n" + line + ":\n" if line.endswith(":") else line
            # ensure dedented lines are separated by newline from previous block
            if lineIndented and not newLine.startswith(" "):
                newLine = "\n" + newLine
            rstLines.append(newLine)
            lineIndented = newLine.startswith(" ")

        scriptRSTPath = os.path.join(sectionPath, scriptName + ".rst")
        fileContent = "\n".join(rstLines).strip() + "\n"

        for index, marker in enumerate(["example", ".. note::"]):
            if scriptName in self.config.com_module_docstring:
                if index == 0:
                    content = self.getContentFromModuleDocstring(script)
                    fileContent += "\n" + content.strip() + "\n"
            else:
                content = self.getContentFromScriptDoc(scriptRSTPath, marker)
                if not content:
                    break  # nothing in content, files probably does not exist
                if content and marker not in fileContent.lower():
                    fileContent += "\n" + content.strip() + "\n"
            LOG.debug("\n" + "*" * 88 + "\n" + fileContent + "\n" + "*" * 88) if self.debug else None
        while "\n\n\n" in fileContent:
            fileContent = fileContent.replace("\n\n\n", "\n\n")

        # remove the standalone '-' when no short option exists
        fileContent = fileContent.replace("-   --", "--")
        writeLinesToFile(scriptRSTPath, fileContent)
        return scriptName, True