Skip to content

Commit

Permalink
Merge branch 'main' into add_prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
mathbunnyru authored Dec 9, 2024
2 parents 502e538 + f67914e commit a9f0944
Show file tree
Hide file tree
Showing 27 changed files with 226 additions and 115 deletions.
7 changes: 6 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@ repos:
- id: rst-backticks
- id: rst-directive-colons
- id: rst-inline-touching-normal
- repo: https://github.com/asottile/pyupgrade
rev: v3.19.0
hooks:
- id: pyupgrade
args: [--py39-plus]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.3
rev: v0.8.2
hooks:
- id: ruff
args: [--fix]
Expand Down
1 change: 1 addition & 0 deletions dev/environment-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ dependencies:
- pytest-asyncio
- pytest-timeout
- pytest-xprocess
- memory_profiler
- requests
- sel(win): pywin32
- sel(win): menuinst
Expand Down
27 changes: 0 additions & 27 deletions docs/source/installation/micromamba-installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -230,30 +230,3 @@ The executable can be striped to remove its size:
.. code:: bash
strip "build/micromamba/micromamba"
.. _shell_completion:

Shell completion
****************

For now, only ``micromamba`` provides shell completion on ``bash`` and ``zsh``.

To activate it, it's as simple as running:

.. code:: bash
micromamba shell completion
The completion is now available in any new shell opened or in the current shell after sourcing the configuration file to take modifications into account.

.. code-block:: sh
source ~/.<shell>rc
| Just hit ``<TAB><TAB>`` to get completion when typing your command.
| For example the following command will help you to pick a named environment to activate:
.. code-block:: bash
micromamba activate <TAB><TAB>
23 changes: 10 additions & 13 deletions docs/source/tools/mermaid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.statemachine import ViewList
from six import text_type
from sphinx.application import Sphinx
from sphinx.errors import SphinxError
from sphinx.locale import _
Expand Down Expand Up @@ -96,7 +95,7 @@ def get_mm_code(self):
try:
with codecs.open(filename, "r", "utf-8") as fp:
mmcode = fp.read()
except (IOError, OSError): # noqa
except OSError: # noqa
return [
document.reporter.warning(
"External Mermaid file %r not found or reading " "it failed" % filename,
Expand Down Expand Up @@ -144,8 +143,8 @@ def render_mm(self, code, options, fmt, prefix="mermaid"):
"utf-8"
)

basename = "%s-%s" % (prefix, sha1(hashkey).hexdigest())
fname = "%s.%s" % (basename, fmt)
basename = f"{prefix}-{sha1(hashkey).hexdigest()}"
fname = f"{basename}.{fmt}"
relfn = posixpath.join(self.builder.imgpath, fname)
outdir = os.path.join(self.builder.outdir, self.builder.imagedir)
outfn = os.path.join(outdir, fname)
Expand All @@ -157,7 +156,7 @@ def render_mm(self, code, options, fmt, prefix="mermaid"):
ensuredir(os.path.dirname(outfn))

# mermaid expects UTF-8 by default
if isinstance(code, text_type):
if isinstance(code, str):
code = code.encode("utf-8")

with open(tmpfn, "wb") as t:
Expand Down Expand Up @@ -235,19 +234,19 @@ def render_mm_html(self, node, code, options, prefix="mermaid", imgcls=None, alt
alt = node.get("alt", self.encode(code).strip())
imgcss = imgcls and 'class="%s"' % imgcls or ""
if fmt == "svg":
svgtag = """<object data="%s" type="image/svg+xml">
<p class="warning">%s</p></object>\n""" % (
svgtag = """<object data="{}" type="image/svg+xml">
<p class="warning">{}</p></object>\n""".format(
fname,
alt,
)
self.body.append(svgtag)
else:
if "align" in node:
self.body.append(
'<div align="%s" class="align-%s">' % (node["align"], node["align"])
'<div align="{}" class="align-{}">'.format(node["align"], node["align"])
)

self.body.append('<img src="%s" alt="%s" %s/>\n' % (fname, alt, imgcss))
self.body.append(f'<img src="{fname}" alt="{alt}" {imgcss}/>\n')
if "align" in node:
self.body.append("</div>\n")

Expand Down Expand Up @@ -310,9 +309,7 @@ def render_mm_latex(self, node, code, options, prefix="mermaid"):
elif node["align"] == "right":
self.body.append("{\\hspace*{\\fill}")
post = "}"
self.body.append(
"%s\\sphinxincludegraphics{%s}%s" % (para_separator, fname, para_separator)
)
self.body.append(f"{para_separator}\\sphinxincludegraphics{{{fname}}}{para_separator}")
if post:
self.body.append(post)

Expand Down Expand Up @@ -356,7 +353,7 @@ def man_visit_mermaid(self, node):

def config_inited(app, config):
version = config.mermaid_version
mermaid_js_url = "https://unpkg.com/mermaid@{}/dist/mermaid.min.js".format(version)
mermaid_js_url = f"https://unpkg.com/mermaid@{version}/dist/mermaid.min.js"
app.add_js_file(mermaid_js_url)
app.add_js_file(
None,
Expand Down
25 changes: 13 additions & 12 deletions docs/source/tools/mermaid_inheritance.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ class E(B): pass
:license: BSD, see LICENSE for details.
"""

from typing import Any, Dict, Iterable, List, cast
from typing import Any, cast
from collections.abc import Iterable

import sphinx
from docutils import nodes
Expand Down Expand Up @@ -80,22 +81,22 @@ class MermaidGraph(InheritanceGraph):
# 'style': '"setlinewidth(0.5)"',
# }

def _format_node_attrs(self, attrs: Dict) -> str:
def _format_node_attrs(self, attrs: dict) -> str:
# return ','.join(['%s=%s' % x for x in sorted(attrs.items())])
return ""

def _format_graph_attrs(self, attrs: Dict) -> str:
def _format_graph_attrs(self, attrs: dict) -> str:
# return ''.join(['%s=%s;\n' % x for x in sorted(attrs.items())])
return ""

def generate_dot(
self,
name: str,
urls: Dict = {}, # noqa
urls: dict = {}, # noqa
env: BuildEnvironment = None,
graph_attrs: Dict = {}, # noqa
node_attrs: Dict = {}, # noqa
edge_attrs: Dict = {}, # noqa
graph_attrs: dict = {}, # noqa
node_attrs: dict = {}, # noqa
edge_attrs: dict = {}, # noqa
) -> str:
"""Generate a mermaid graph from the classes that were passed in
to __init__.
Expand All @@ -120,17 +121,17 @@ def generate_dot(
res.append("classDiagram\n")
for name, fullname, bases, tooltip in sorted(self.class_info):
# Write the node
res.append(" class {!s}\n".format(name))
res.append(f" class {name!s}\n")
if fullname in urls:
res.append(
' link {!s} "./{!s}" {!s}\n'.format(
name, urls[fullname], tooltip or '"{}"'.format(name)
name, urls[fullname], tooltip or f'"{name}"'
)
)

# Write the edges
for base_name in bases:
res.append(" {!s} <|-- {!s}\n".format(base_name, name))
res.append(f" {base_name!s} <|-- {name!s}\n")

return "".join(res)

Expand Down Expand Up @@ -159,7 +160,7 @@ class MermaidDiagram(InheritanceDiagram):
"top-classes": directives.unchanged_required,
}

def run(self) -> List[Node]:
def run(self) -> list[Node]:
node = mermaid_inheritance()
node.document = self.state.document
class_names = self.arguments[0].split()
Expand Down Expand Up @@ -283,7 +284,7 @@ def texinfo_visit_mermaid_inheritance(self: TexinfoTranslator, node: inheritance
raise nodes.SkipNode


def setup(app: Sphinx) -> Dict[str, Any]:
def setup(app: Sphinx) -> dict[str, Any]:
app.setup_extension("mermaid")
app.add_node(
mermaid_inheritance,
Expand Down
15 changes: 15 additions & 0 deletions docs/source/user_guide/concepts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,18 @@ Deactivation
************

The *deactivation* is the opposite operation of :ref:`activation<activation>`, removing from your shell what makes the environment content accessible.


.. _shell_completion:

Shell completion
****************

After initialization, shell completion is available in any new shell.
Just hit ``<TAB><TAB>`` to get completion when typing your command.

For example the following command will help you to pick a named environment to activate:

.. code-block:: bash
micromamba activate <TAB><TAB>
5 changes: 5 additions & 0 deletions libmamba/include/mamba/util/string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,11 @@ namespace mamba::util
[[nodiscard]] auto strip(std::string_view input) -> std::string_view;
[[nodiscard]] auto strip(std::wstring_view input) -> std::wstring_view;

/**
* Dedicated implementation for inplace stripping of `std::string` to avoid copies
*/
void inplace_strip(std::string& input);

[[nodiscard]] auto strip_parts(std::string_view input, char c) -> std::array<std::string_view, 3>;
[[nodiscard]] auto strip_parts(std::wstring_view input, wchar_t c)
-> std::array<std::wstring_view, 3>;
Expand Down
23 changes: 11 additions & 12 deletions libmamba/src/api/install.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,8 @@ namespace mamba
{
throw std::runtime_error(util::concat("Got an empty file: ", file));
}

// Inferring potential explicit environment specification
for (std::size_t i = 0; i < file_contents.size(); ++i)
{
auto& line = file_contents[i];
Expand Down Expand Up @@ -930,26 +932,23 @@ namespace mamba
}
}

std::vector<std::string> f_specs;
for (auto& line : file_contents)
{
if (line[0] != '#' && line[0] != '@')
{
f_specs.push_back(line);
}
}

// If we reach here, we have a file with no explicit env, and the content of the
// file just lists MatchSpecs.
if (specs.cli_configured())
{
auto current_specs = specs.cli_value<std::vector<std::string>>();
current_specs.insert(current_specs.end(), f_specs.cbegin(), f_specs.cend());
current_specs.insert(
current_specs.end(),
file_contents.cbegin(),
file_contents.cend()
);
specs.set_cli_value(current_specs);
}
else
{
if (!f_specs.empty())
if (!file_contents.empty())
{
specs.set_cli_value(f_specs);
specs.set_cli_value(file_contents);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions libmamba/src/core/activation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ namespace mamba
{
return "base";
}
// if ../miniconda3/envs/my_super_env, return `my_super_env`, else path
if (prefix.parent_path().stem() == "envs")
// if ../miniconda3/envs/my_super.env, return `my_super.env`, else path
if (prefix.parent_path().filename() == "envs")
{
return prefix.stem().string();
return prefix.filename().string();
}
else
{
Expand Down
28 changes: 28 additions & 0 deletions libmamba/src/core/util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,34 @@ namespace mamba
line.pop_back();
}

// Remove leading and trailing whitespace in place not to create a new string.
util::inplace_strip(line);

// Skipping empty lines
if (line.empty())
{
continue;
}

// Skipping comment lines starting with #
if (util::starts_with(line, "#"))
{
continue;
}

// Skipping comment lines starting with @ BUT headers of explicit environment specs
if (util::starts_with(line, "@"))
{
auto is_explicit_header = util::starts_with(line, "@EXPLICIT");

if (is_explicit_header)
{
output.push_back(line);
}
continue;
}

// By default, add the line to the output (MatchSpecs, etc.)
output.push_back(line);
}
file_stream.close();
Expand Down
2 changes: 1 addition & 1 deletion libmamba/src/download/curl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ namespace mamba::download
}

// Set error buffer
m_errorbuffer[0] = '\0';
std::fill(m_errorbuffer.begin(), m_errorbuffer.end(), '\0');
set_opt(CURLOPT_ERRORBUFFER, m_errorbuffer.data());
}

Expand Down
20 changes: 20 additions & 0 deletions libmamba/src/util/string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,26 @@ namespace mamba::util
return strip_if(input, [](Char c) { return !is_graphic(c); });
}

void inplace_strip(std::string& input)
{
if (input.empty())
{
return;
}

const auto start = input.find_first_not_of(" \t\n\v\f\r");

if (start == std::string::npos)
{
input.clear();
return;
}

const auto end = input.find_last_not_of(" \t\n\v\f\r");

input = input.substr(start, end - start + 1);
}

/*********************************************
* Implementation of strip_parts functions *
*********************************************/
Expand Down
18 changes: 18 additions & 0 deletions libmamba/tests/src/core/test_activation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,23 @@ namespace mamba
// std::endl; std::cout << a.activate("/home/wolfv/miniconda3/", false) <<
// std::endl;
}

TEST_CASE("Activator::get_default_env")
{
Context ctx;
ctx.prefix_params.root_prefix = "/home/user/miniforge";
PosixActivator a(ctx);
REQUIRE(a.get_default_env("/home/user/miniforge") == "base");
REQUIRE(a.get_default_env("/home/user/miniforge/envs/env") == "env");
REQUIRE(a.get_default_env("/home/user/miniforge/envs/an.env") == "an.env");
REQUIRE(a.get_default_env("/home/user/miniforge/envs/an-oth.er") == "an-oth.er");
REQUIRE(a.get_default_env("/opt/envs/yet.an-oth.er") == "yet.an-oth.er");

const fs::u8path& alternative_folder = "/opt/envs.d/env";
REQUIRE(a.get_default_env(alternative_folder) == alternative_folder);

const fs::u8path& alt_folder = "/home/user/some/env";
REQUIRE(a.get_default_env(alt_folder) == alt_folder);
}
}
} // namespace mamba
Loading

0 comments on commit a9f0944

Please sign in to comment.