Ejemplo n.º 1
0
def dump(
    data: Mapping[str, Any],
    filename: PathLike,
    encoder: Union[Type[toml.TomlEncoder],
                   toml.TomlEncoder] = toml.TomlEncoder,
) -> str:
    r"""
	Writes out ``data`` as TOML to the given file.

	:param data:
	:param filename: The filename to write to.
	:param encoder: The :class:`toml.TomlEncoder` to use for constructing the output string.

	:returns: A string containing the ``TOML`` corresponding to ``data``.

	.. versionchanged:: 0.5.0

		The default value for ``encoder`` changed from :py:obj:`None` to :class:`toml.TomlEncoder`
		Explicitly passing ``encoder=None`` is deprecated and support will be removed in 1.0.0

	.. latex:clearpage::
	"""

    filename = PathPlus(filename)
    as_toml = dumps(data, encoder=encoder)
    filename.write_clean(as_toml)
    return as_toml
Ejemplo n.º 2
0
def convert_notebook(
		nb_file: PathLike,
		outfile: PathLike,
		):
	"""
	Convert a notebook to a Python file.

	:param nb_file: Filename of the Jupyter Notebook to convert.
	:param outfile: The filename to store the Python output as.
	"""

	nb_file = PathPlus(nb_file)
	outfile = PathPlus(outfile)
	outfile.parent.maybe_make()

	script, *_ = py_exporter.from_file(str(nb_file))

	outfile.write_clean(script)

	with importlib_resources.path("notebook2script", "isort.cfg") as isort_config:
		with importlib_resources.path("notebook2script", "style.yapf") as yapf_style:
			reformat_file(outfile, yapf_style=str(yapf_style), isort_config_file=str(isort_config))

	linter.process_file(outfile)

	with open(outfile, "r+b") as f:
		fix_encoding_pragma(f, remove=True, expected_pragma=b"# coding: utf-8")
Ejemplo n.º 3
0
def make_recipe(project_dir: PathLike, recipe_file: PathLike) -> None:
    """
	Make a Conda ``meta.yaml`` recipe.

	:param project_dir: The project directory.
	:param recipe_file: The file to save the recipe as.
	"""

    recipe_file = PathPlus(recipe_file)
    recipe_file.parent.maybe_make(parents=True)
    recipe_file.write_clean(MaryBerry(project_dir).make())
Ejemplo n.º 4
0
def make_recipe(repo_dir: PathLike, recipe_file: PathLike) -> None:
    """
	Make a Conda ``meta.yaml`` recipe.

	:param repo_dir: The repository directory.
	:param recipe_file: The file to save the recipe as.

	.. versionadded:: 2020.11.10
	"""

    # TODO: tests for this

    repo_dir = PathPlus(repo_dir)
    recipe_file = PathPlus(recipe_file)

    recipe_file.write_clean(CondaRecipeMaker(repo_dir).make())
Ejemplo n.º 5
0
def make_document(
    outfile: PathLike,
    *elements: Iterable[str],
    glossary: str = '',
):
    r"""
	Construct a LaTeX document from the given elements.

	:param outfile:
	:param \*elements:
	:param glossary:
	"""

    outfile = PathPlus(outfile)
    outfile.write_clean(
        main_template.render(elements=elements, glossary=glossary))
Ejemplo n.º 6
0
    def dump(
        self,
        filename: PathLike,
        encoder: Union[Type[toml.TomlEncoder],
                       toml.TomlEncoder] = PyProjectTomlEncoder,
    ):
        """
		Write as TOML to the given file.

		:param filename: The filename to write to.
		:param encoder: The :class:`toml.TomlEncoder` to use for constructing the output string.

		:returns: A string containing the TOML representation.
		"""

        filename = PathPlus(filename)
        as_toml = self.dumps(encoder=encoder)
        filename.write_clean(as_toml)
        return as_toml
Ejemplo n.º 7
0
def check_and_add_all(filename: PathLike, quote_type: str = '"') -> int:
	"""
	Check the given filename for the presence of a ``__all__`` declaration, and add one if none is found.

	:param filename: The filename of the Python source file (``.py``) to check.
	:param quote_type: The type of quote to use for strings.

	:returns:

	* ``0`` if the file already contains a ``__all__`` declaration,
	  has no function or class definitions, or has a ``  # noqa: DALL000  ` comment.
	* ``1`` If ``__all__`` is absent.
	* ``4`` if an error was encountered when parsing the file.

	.. versionchanged:: 0.2.0

		Now returns ``0`` and doesn't add ``__all__`` if the file contains a ``noqa: DALL000`` comment.
	"""

	quotes = {"'", '"'}
	quotes.remove(quote_type)
	bad_quote, *_ = tuple(quotes)

	filename = PathPlus(filename)

	try:
		source = filename.read_text()
		for line in source.splitlines():
			noqas = find_noqa(line)
			if noqas is not None:
				if noqas["codes"]:
					# pylint: disable=loop-invariant-statement
					noqa_list: List[str] = noqas["codes"].rstrip().upper().split(',')
					if "DALL000" in noqa_list:
						return 0
					# pylint: enable=loop-invariant-statement

		tree = ast.parse(source)
		if sys.version_info < (3, 8):  # pragma: no cover (py38+)
			mark_text_ranges(tree, source)

	except SyntaxError:
		stderr_writer(Fore.RED(f"'{filename}' does not appear to be a valid Python source file."))
		return 4

	visitor = Visitor(use_endlineno=True)
	visitor.visit(tree)

	if visitor.found_all:
		return 0
	else:
		docstring_start = (get_docstring_lineno(tree) or 0) - 1
		docstring = ast.get_docstring(tree, clean=False) or ''
		docstring_end = len(docstring.split('\n')) + docstring_start

		insertion_position = max(docstring_end, visitor.last_import) + 1

		if not visitor.members:
			return 0

		members = repr(sorted(visitor.members)).replace(bad_quote, quote_type)

		lines = filename.read_text().split('\n')

		# Ensure there don't end up too many lines
		if lines[insertion_position].strip():
			lines.insert(insertion_position, '\n')
		else:
			lines.insert(insertion_position, '')

		lines.insert(insertion_position, f"__all__ = {members}")

		filename.write_clean('\n'.join(lines))

		return 1