Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Documentation site at <https://techcode-io.github.io/proclet/>: guides, recipes, migration
guides from `sh` and plumbum, and an API reference generated from the docstrings.
- Docstrings for the public type aliases (`Process`, `RedirectIn`, `RedirectOut`...).
- `Command.copy()` without argument returns an independent duplicate of the command, without
looking the binary up again.

## [0.1.1] - 2026-11-26

Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ Requires Python 3.12 or newer, on Linux, macOS or Windows. No runtime dependency
pip install proclet
```

Or with another package manager:

```bash
uv add proclet
poetry add proclet
pdm add proclet
pipenv install proclet
```

```python
import asyncio
from io import StringIO
Expand Down
2 changes: 1 addition & 1 deletion docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default defineConfig({
items: [
{ text: "Running commands", link: "/guide/running-commands" },
{ text: "Input and output", link: "/guide/input-output" },
{ text: "asyncio", link: "/guide/asyncio" },
{ text: "Async execution", link: "/guide/asyncio" },
{ text: "Pipelines", link: "/guide/pipelines" },
{ text: "Environment and PATH", link: "/guide/environment" },
{ text: "Privileges and priority", link: "/guide/privileges" },
Expand Down
106 changes: 98 additions & 8 deletions docs/.vitepress/theme/components/InstallCommand.vue
Original file line number Diff line number Diff line change
@@ -1,13 +1,37 @@
<script setup lang="ts">
import { ref } from "vue";
import { computed, ref } from "vue";

const command = "pip install proclet";
const installers = [
{ name: "pip", command: "pip install proclet" },
{ name: "uv", command: "uv add proclet" },
{ name: "poetry", command: "poetry add proclet" },
{ name: "pdm", command: "pdm add proclet" },
{ name: "pipenv", command: "pipenv install proclet" },
];

const selected = ref(0);
const command = computed(() => installers[selected.value].command);
const copied = ref(false);
let reset: ReturnType<typeof setTimeout> | undefined;

function select(index: number) {
selected.value = index;
copied.value = false;
}

function onKeydown(event: KeyboardEvent) {
const step = { ArrowRight: 1, ArrowLeft: -1 }[event.key];
if (!step) return;
event.preventDefault();
const next = (selected.value + step + installers.length) % installers.length;
select(next);
const tabs = (event.currentTarget as HTMLElement).querySelectorAll<HTMLElement>("[role=tab]");
tabs[next]?.focus();
}

async function copy() {
try {
await navigator.clipboard.writeText(command);
await navigator.clipboard.writeText(command.value);
} catch {
return;
}
Expand All @@ -19,19 +43,85 @@ async function copy() {

<template>
<div class="install">
<code class="install-command"><span class="install-prompt" aria-hidden="true">$</span> {{ command }}</code>
<button type="button" class="install-copy" @click="copy">
{{ copied ? "Copied" : "Copy" }}
</button>
<div class="install-tabs" role="tablist" aria-label="Package manager" @keydown="onKeydown">
<button
v-for="(installer, index) in installers"
:key="installer.name"
type="button"
role="tab"
class="install-tab"
:id="`install-tab-${installer.name}`"
:aria-selected="index === selected"
aria-controls="install-panel"
:tabindex="index === selected ? 0 : -1"
@click="select(index)"
>
{{ installer.name }}
</button>
</div>
<div
id="install-panel"
class="install-box"
role="tabpanel"
:aria-labelledby="`install-tab-${installers[selected].name}`"
>
<code class="install-command"><span class="install-prompt" aria-hidden="true">$</span> {{ command }}</code>
<button type="button" class="install-copy" @click="copy">
{{ copied ? "Copied" : "Copy" }}
</button>
</div>
<span class="visually-hidden" aria-live="polite">{{ copied ? "Install command copied" : "" }}</span>
</div>
</template>

<style scoped>
.install {
margin-top: 28px;
max-width: 100%;
}

.install-tabs {
display: flex;
flex-wrap: wrap;
gap: 4px;
justify-content: center;
margin-bottom: 8px;
}

@media (min-width: 960px) {
.install-tabs {
justify-content: flex-start;
}
}

.install-tab {
padding: 2px 10px;
border-radius: 6px;
color: var(--vp-c-text-2);
font-family: var(--vp-font-family-mono);
font-size: 13px;
transition:
color 0.2s,
background-color 0.2s;
}

.install-tab:hover {
color: var(--vp-c-text-1);
}

.install-tab[aria-selected="true"] {
color: var(--vp-c-brand-1);
background: var(--vp-c-brand-soft);
}

.install-tab:focus-visible {
outline: 2px solid var(--vp-c-brand-1);
outline-offset: 2px;
}

.install-box {
display: inline-flex;
align-items: stretch;
margin-top: 28px;
border: 1px solid var(--pc-pipe-wall);
border-radius: 8px;
background: var(--vp-c-bg);
Expand Down
7 changes: 5 additions & 2 deletions docs/guide/asyncio.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# asyncio
# Async execution

Run the same commands from `asyncio` code.

Expand All @@ -11,10 +11,11 @@ from proclet import Command


async def uptimes(hosts: list[str]) -> dict[str, str]:
ssh = Command("ssh").timeout(10)
outputs = {host: StringIO() for host in hosts}
await asyncio.gather(
*(
Command("ssh").args(host, "uptime").stdout(out).timeout(10).aexec()
ssh.copy().args(host, "uptime").stdout(out).aexec()
for host, out in outputs.items()
)
)
Expand All @@ -26,3 +27,5 @@ print(asyncio.run(uptimes(["alpha", "beta", "gamma"])))

- Every way of running a command has an `asyncio` counterpart prefixed with `a`: `aexec()`, `apipe()` and `apipeline()`. They return an `asyncio.subprocess.Process`.
- The configuration is shared: the same `Command` runs with either.
- `ssh` is looked up on `PATH` once; `copy()` gives each host its own command with the shared
settings, so their args and redirects don't overwrite each other.
12 changes: 12 additions & 0 deletions docs/guide/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ pip install proclet
uv add proclet
```

```bash [poetry]
poetry add proclet
```

```bash [pdm]
pdm add proclet
```

```bash [pipenv]
pipenv install proclet
```

:::

## First commands
Expand Down
7 changes: 4 additions & 3 deletions docs/guide/reuse-and-wrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ from pathlib import Path
from proclet import Command

base = Command("git").cwd(Path("repo")).timeout(30)
Command("git").copy(base).args("fetch", "--all").exec()
Command("git").copy(base).args("gc").exec()
base.copy().args("fetch", "--all").exec()
base.copy().args("gc").exec()
```

- `copy(other)` takes every setting of `other` (args, env, cwd, redirects, timeout, exit codes, privileges, niceness, observers) while keeping its own binary.
- `copy()` returns a new command with the same binary and every setting (args, env, cwd, redirects, timeout, exit codes, privileges, niceness, observers), without looking the binary up again. Changing the copy leaves `base` untouched.
- `copy(other)` takes every setting of `other` into an existing command while keeping its own binary.

## Wrap a binary into a typed API

Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ Command("pg_dump").args("shop").stderr(to_log).timeout(600).pipe(
<dl class="pc-capabilities">
<div class="pc-capability">
<dt><span class="pc-emoji" aria-hidden="true">⚡</span>Sync and async</dt>
<dd>One <code>Command</code>, run with <code>exec()</code> or <code>await aexec()</code>. <a href="./guide/asyncio">asyncio guide</a></dd>
<dd>One <code>Command</code>, run with <code>exec()</code> or <code>await aexec()</code>. <a href="./guide/asyncio">Async guide</a></dd>
</div>
<div class="pc-capability">
<dt><span class="pc-emoji" aria-hidden="true">🚰</span>Pipelines without a shell</dt>
Expand Down
10 changes: 6 additions & 4 deletions docs/recipes/asyncio-concurrency.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,25 @@ from io import StringIO
from proclet import Command


async def uptime(host: str, limit: asyncio.Semaphore) -> str:
async def uptime(ssh: Command, host: str, limit: asyncio.Semaphore) -> str:
out = StringIO()
async with limit:
await Command("ssh").args(host, "uptime").stdout(out).timeout(10).aexec()
await ssh.copy().args(host, "uptime").stdout(out).aexec()
return out.getvalue().strip()


async def main(hosts: list[str]) -> None:
ssh = Command("ssh").timeout(10)
limit = asyncio.Semaphore(8)
results = await asyncio.gather(
*(uptime(host, limit) for host in hosts), return_exceptions=True
*(uptime(ssh, host, limit) for host in hosts), return_exceptions=True
)
for host, result in zip(hosts, results):
print(host, result)
```

- `aexec()` takes the same configuration as `exec()`: redirects, timeout, exit codes, env.
- `ssh` is looked up on `PATH` once in `main()`; each host runs its own `copy()` of it.
- A failure raises `ErrorReturnCode`, a timeout `TimeoutException` (after terminating the
process), and `gather(..., return_exceptions=True)` collects them per host.
- Cancelling the awaiting task terminates the process too, so an `asyncio.timeout(...)`
Expand Down Expand Up @@ -93,4 +95,4 @@ async def main() -> None:
asyncio.run(main())
```

See also: [asyncio](/guide/asyncio), [`Command.aexec`](/reference/api#proclet.Command.aexec).
See also: [Async execution](/guide/asyncio), [`Command.aexec`](/reference/api#proclet.Command.aexec).
2 changes: 1 addition & 1 deletion src/proclet/bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def _command(self, *args: str) -> Command:
Returns:
a new command, independent from the bind and from other operations.
"""
cmd = Command(self._template.binary_path()).copy(self._template)
cmd = self._template.copy()
return cmd.args(*args) if args else cmd

def add_observer(self, observer: ProcessObserver) -> Self:
Expand Down
19 changes: 16 additions & 3 deletions src/proclet/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,16 +441,29 @@ def add_observer(self, observer: ProcessObserver) -> Self:
self.__observers.append(observer)
return self

def copy(self, cmd: Command) -> Self:
"""Copy all parameters from another command, keeping this one's binary.
@overload
def copy(self) -> Command: ...

@overload
def copy(self, cmd: Command, /) -> Self: ...

def copy(self, cmd: Command | None = None) -> Command | Self:
"""Duplicate this command, or copy all parameters from another one.

Without argument, returns a new command running the same binary with the
same parameters, without looking the binary up again. With a command,
copies its parameters into this one, keeping this one's binary.

Collections are copied; redirect targets and observers are shared.

Args:
cmd: the command to copy parameters from.
Returns:
self for chaining.
a new command if no command is provided, otherwise self for chaining.
"""
if cmd is None:
return Command(Path(self.__cmd_path)).copy(self)

self.__env = None if cmd.__env is None else cmd.__env.copy()
self.__cwd = cmd.__cwd
self.__args = cmd.__args
Expand Down
19 changes: 19 additions & 0 deletions tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,25 @@ def test_copy_from_another_command(self) -> None:
assert dst.group() == os.getgid()
assert dst.extra_groups() == []

def test_copy_without_argument_duplicates(self) -> None:
src = Command(PYTHON).args("hello").env({"X": "1"}).cwd(Path("sub"))
dup = src.copy()
assert dup is not src
assert dup.binary_path() == src.binary_path()
assert dup.args() == ("hello",)
assert dup.env() == {"X": "1"}
assert dup.cwd() == Path("sub")
dup.args("other").env({"Y": "2"})
assert src.args() == ("hello",)
assert src.env() == {"X": "1"}

def test_copy_without_argument_skips_lookup(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
src = Command(PYTHON)
monkeypatch.setenv("PATH", "")
assert src.copy().binary_path() == src.binary_path()

def test_exec_success(self) -> None:
cmd = echo("hello")
process = cmd.exec()
Expand Down
Loading