mirror of
https://github.com/openswarm-ai/openswarm.git
synced 2026-09-28 04:24:51 +02:00
* [eric] ci: gitleaks-ignore the known historical secrets so our branch stops failing on leaks it didnt add * [eric] workflows: restore scheduled-tasks on the workflow line (revert removal, keep windows fixes + 1.1.69) * [eric] workflows: re-apply uncommitted scheduling wip (schedule pill, calendar view, slice) * [eric] ops: gitignore dev-team local state files * [eric] ops: backlog item for download-tracking visibility * [eric] ci: allowlist the cdp-routes redaction-test token in gitleaks * [aidan] feat/scheduled-tasks: keep step labels in sync on edit and show chevron on every step * [aidan] fix: schedule time in chat * [aidan] ux/workflows: add workflow step removal (#91) * [aidan] feat/scheduled-tasks: remember workflow tool permissions across runs * [aidan] feat/task-scheduling: add hourly and minute (15-min minimum) schedule intervals (#93) * [aidan] feat/scheduled-tasks: calendar, rename, and edit workflows (#94) * [aidan] bug: fix schedule button * [aidan] fix/agent-errors: surface provider rate limits * [aidan] ux/cards: click-to-rename for chat and workflow titles Single-click a card's title to enter edit mode inline. Commit on Enter/blur, cancel on Escape. Rename persists via PATCH for workflows and sessions. * [aidan] feat/workflows: seed build prompt for zero-step workflows When a new workflow has no steps, seed the agent with a prompt asking the user to describe what the workflow should do, rather than starting blank. * [aidan] feat/workflows: add-to-schedule popover for unscheduled workflows Clicking the "+" on an unscheduled workflow row opens a popover with two options: - Keep this schedule: enables the workflow's existing cadence and moves it to Scheduled - Change schedule: opens the scheduling editor to pick a different time * [aidan] ux/workflows: wire add-to-schedule popover and simplify New button - Made the "+" icon on unscheduled workflow rows clickable, opening a popover to keep or change the schedule - Removed AddIcon from toolbar "New" button (now reads "New" instead of "+ New") * [aidan] fix/scheduled-tasks: open schedule calendar when Schedule pill clicked Fixed the Schedule pill click being swallowed by the toolbar's dismiss handler. Exempted the toolbar pills via data-toolbar-pills so their click handlers fire. * [aidan] ux/workflows: open New workflow in agent build chat instead of empty card When creating a new workflow from the hub, open it in edit_agent view (with the agent builder chat) instead of a preview card. The workflow is created on the backend first so the embedded session has a real ID. * [aidan] feat/workflow-edit: add draft testing save flow * [aidan] ux/chat: remove continue chat button * [aidan] ux/workflows: polish workflow card interactions * [aidan] fix/workflow-scheduling: save unscheduled workflows as drafts * aidan ui: schedule naming changes * [aidan] ui: tool calling desc/naming * [aidan] ui: calendar sidebar naming * [aidan] ui: fix stop viewing closing chat * [aidan] feat/workflows: auto-name workflows and polish the build flow (#95) * [aidan] feat/workflow-auto-naming: auto-generate workflow titles from steps Generate a title + description from a workflow's steps (one aux call, reused for step labels) whenever it is still auto_named, so a workflow built in the Edit Agent names itself on commit instead of staying "New workflow". A manual rename sets auto_named=False and is never overwritten. Stream the aux call (non-streaming drops content on some 9router lanes) and fall back to a step-derived title when the model is unavailable. * [aidan] feat/workflows: hide unsaved new workflows until first save A brand-new "+ New" workflow is created with unsaved=true and kept out of the hub's scheduled/unscheduled lists while the user is still building it in the Edit Agent. The first commit (Save) clears the flag and the workflow appears. Every other create path stays visible immediately. * [aidan] ux/workflows: remove redundant save workflow button The Edit Agent already has Discard/Save controls in its strip, so the header "Save Workflow" button was a duplicate save path. Remove it and its pulse/edit-session-id wiring; the model/time subtitle stays. * [aidan] ux/workflows: animate title on auto-rename Wrap the workflow card title in the same Typewriter the chat card uses, so when the auto-generated name replaces the placeholder after Save it retypes letter-by-letter. Gated on a real (non-placeholder) title so it never animates on mount or for already-named workflows. * [aidan] ux/workflows: animate sidebar title on auto-rename Wrap the calendar hub's sidebar row title in the same Typewriter the workflow card uses, so a title that auto-renames retypes letter-by-letter in the sidebar too. Extract the placeholder/isRealTitle guard into the shared workflowVisuals so the card and sidebar stay in sync. * [aidan] fix/workflows: connect watch tether, keep watched chat open, wire draft run/history * [aidan] ui: grey out chat pill when not selected * [aidan] ui: fix running agent display * [aidan] feat/history-popover: add chat history and scheduled tasks run log tabs (#96) * [aidan] ux/schedule: toast when calendar view already open on expand * [aidan] ui: fix popover descs * [aidan] feat/workflow-runs: add pause, resume, and stop controls for live runs * [aidan] feat/schedule-calendar: add calendar occurrences endpoint and concrete timezones * [aidan] feat/workflows: require at least one step to save a workflow * [aidan] ux/edit-agent: hide Discard for an unsaved new workflow * [aidan] ux/edit-agent: move fix-prefix card below the step list * [aidan] feat/workflows: toast when an unattended scheduled run starts * [aidan] fix/dashboard-tethers: anchor workflow-sidecar tethers to measured card rects * [aidan] feat/workflows: validate steps before scheduling and keep chat tool memory * [aidan] feat/mcp-suggestions: dismissable integration banner with per-session cooldown * [aidan] feat/workflows: add scheduled-run "running now" toast with click-to-view (#97) * [aidan] ux/workflows: surface paused state on card, sidebar, and calendar; tidy run history * [aidan] feat/mcp-suggestions: suggest both Google and Microsoft when provider is ambiguous * [aidan] fix/agent-tokens: friendly out-of-tokens card across all agent surfaces * [aidan] feat/workflow-model: persist edit-agent model on save with switch notice and fresh drafts * [aidan] fix/workflow-chat: force stop on watched run mirrors workflow card stop * [aidan] fix/workflow-cards: keep watched run tethered on finish to avoid duplicate chat * [aidan] feat/schedule-calendar: mark current time with a now line in week view * [aidan] refactor/private-names: rename error and schedule classifiers from _ to p_ * [aidan] feat/scheduled-tasks: agent workflow scheduling and in-chat convert (#98) * [aidan] feat/workflow-suggest: nudge user to convert repeatable chat to workflow Add SuggestConvertToWorkflow MCP tool that agents call at the end of a task when they've completed something worth repeating (daily report, weekly check, recurring data pull). Frontend detects the tool call and glows the "Convert to workflow" button 3 times to draw the eye. When user clicks it, the suggested cadence (e.g. "every weekday at 9am") is stored in the draft and seeded into the scheduling agent's first prompt, so the agent can act on the suggestion rather than asking the user again. Tool is never auto-called — agents decide when a task is genuinely repeatable (not debugging, creative work, one-off lookup). Tool description emphasizes sparse, high-confidence use only (once per session max). Files changed: - backend/apps/agents/schedule_mcp_server.py: add SuggestConvertToWorkflow tool - frontend/src/shared/mcpToolMeta.ts: add label for new tool - frontend/src/app/pages/Dashboard/cards/AgentCard.tsx: detect suggestion in session messages, show+glow "Convert to workflow" button, pass cadence to draft - frontend/src/shared/state/workflowsSlice.ts: add suggested_cadence field to Workflow interface - frontend/src/app/pages/Workflows/SchedulingView.tsx: seed scheduling agent prompt with suggested cadence hint * [aidan] feat/agent-scheduling: route recurring asks through native workflows, deny claude cron skill * [aidan] feat/workflow-convert: in-chat convert popup and auto-open scheduled workflow card * [aidan] ux/calendar-page: schedule calendar restyle + popover fixes (#99) * [aidan] fix/dashboard-delete: remove workflows calendar panel on delete key * [aidan] ux/workflows-calendar: restyle hub, fix today highlight, add toolbar toggle * [aidan] ux/schedule-popover: compact density, fix sticky header bleed, add header spacing * [aidan] ux/schedule-calendar: hollow ring dot for past fires in month view * [aidan] ux/schedule-calendar: clickable +N more opens day's full run list * [aidan] feat/run-log-filters: add success and skipped pills to scheduled task history * [aidan] fix/convert-button: stop drag capture so convert-to-workflow click fires * [aidan] ux/calendar-card: match border color and radius to chat and workflow cards * [aidan] fix/minimap: render missed-runs card on the minimap * [aidan] ux/run-sparkline: simplify tooltip to plain run tally * [aidan] ux/run-history: collapse expanded run view to one clickable line * [aidan] ux/calendar-card: match corner radius to browser cards * [aidan] feat/workflows: launch-time scheduling UX and workflow-card polish (#101) * [aidan] feat/schedule-list: lazy-load list view via scroll sentinel * [aidan] feat/missed-runs: launch toast with per-workflow counts and pan-to-card * [aidan] fix/dashboard-tethers: keep watching line anchored on canvas zoom * [aidan] feat/scheduled-tasks: review missed runs at launch instead of auto-firing on_missed * [aidan] refactor/workflow-cards: use radius and status design tokens, polish card chrome * [aidan] ux/agent-card: keep convert-to-workflow visible during runs with mid-turn toast * [aidan] ux/mcp-bubble: drop redundant verb label when a workflow label is shown * [aidan] chore/backend: remove stale explanatory comments * [aidan] fix/workflows-hub: load workflows on hub mount so calendar fills at launch * [aidan] feat/workflows: generate title, description, step labels at convert time * [aidan] fix/tidy-layout: include workflows hub in tidy and fit-to-view * [aidan] feat/schedule-list: window long list via measured-height virtualizer * [aidan] ux/workflows-hub: remove time-saved badge from calendar header * [aidan] fix/types: add missing semantic-type labels and drop stray fade arg * [aidan] feat/schedule: pin monthly day-of-month and honor repeat-every intervals * [aidan] feat/schedule: inherit source-session tool surface for scheduled runs * [aidan] ux/calendar: restack hour-cell events as bars with overflow affordance * [aidan] feat/calendar: open the run card when clicking a scheduled occurrence * [aidan] ux/missed-runs: add per-group select-all toggle and rename skip action * [aidan] feat: new scheduled task design ported * [aidan] ui: sidebar reorder, repeat controls on schedule card * [aidan] ui: sidebar, scheduling time * [aidan] feat/schedule: pin monthly last-day-of-month * [aidan] feat/steps: per-step enable toggle * [aidan] feat/workflows: per-workflow color swatch * [aidan] feat/trash: soft-delete workflows with restore and purge * [aidan] feat/run-monitor: live run monitor card on the canvas * [aidan] feat/run-context: attach a run as removable chat context * [aidan] feat/compose: new-workflow landing page and auto-commit build flow * [aidan] ui/workflows: dark mode and design-system cohesion * [aidan] ui/calendar: overflow popover, condensed week view, scroll fix * [aidan] feat/home: ongoing runs, missed review, and accurate Coming-up counts * [aidan] fix/run-status: sync ongoing runs and heal stuck/interrupted runs * [aidan] ux/schedule: last-day-of-month UI, Run-at time typing, interval input * [aidan] ux/workflows: default window size and toolbar icon * [aidan] fix/schedule: measure ran_late from start and anchor recurrences to created_at * [aidan] feat/calendar: render fire times from backend, drop JS recurrence reimpl * [aidan] chore/dashboard: drop dead configure/missed-run cards, refetch on reconnect * [aidan] chore/agent-card: remove unreachable convert-to-workflow action * [aidan] fix/workflows: don't bump updated_at on a no-op draft commit so viewing a workflow doesn't reorder the sidebar * [aidan] feat/schedule: warn when scheduling a workflow that has no steps * [aidan] fix/selection-tool: never select the workflows app, and exit the tool on Escape without dropping selections * [aidan] ux/compose: diversify new-workflow starter prompts across personas * [aidan] ux/run-monitor: spawn the run card a bit farther right of the workflows app * [aidan] fix/schedule: harden run recovery and storage writes against crashes * [aidan] ux/compose: restyle new-workflow starters as a clean pill cluster with rich prompts * [aidan] fix/workflows: optimistically apply edits so the schedule banner updates instantly * [aidan] ui/workflows: three-tone surface depth so the window lifts off the canvas in both themes * [aidan] ui/workflows: close buttons turn red on hover, matching the chat card * [aidan] test/schedule: cover executor pipeline, storage durability, and recurrence gaps * [aidan] fix: remove package-lock json * [aidan] fix/workflows-compose: keep compose view until edit agent replies * [aidan] feat/workflows: auto-generate workflow + step titles with typewriter animation * [eric] deps: restore frontend/package-lock.json (PR #105 deletion broke npm ci) --------- Co-authored-by: Eric <ciregenz@berkeley.edu> Co-authored-by: cire <134991075+ciregenz@users.noreply.github.com>
654 lines
20 KiB
Python
654 lines
20 KiB
Python
from __future__ import annotations
|
|
|
|
import collections.abc as cabc
|
|
import os
|
|
import re
|
|
import sys
|
|
import typing as t
|
|
from functools import update_wrapper
|
|
from gettext import gettext as _
|
|
from types import ModuleType
|
|
from types import TracebackType
|
|
|
|
from ._compat import _default_text_stderr
|
|
from ._compat import _default_text_stdout
|
|
from ._compat import _find_binary_writer
|
|
from ._compat import auto_wrap_for_ansi
|
|
from ._compat import binary_streams
|
|
from ._compat import open_stream
|
|
from ._compat import should_strip_ansi
|
|
from ._compat import strip_ansi
|
|
from ._compat import text_streams
|
|
from ._compat import WIN
|
|
from .globals import resolve_color_default
|
|
|
|
if t.TYPE_CHECKING:
|
|
import typing_extensions as te
|
|
|
|
P = te.ParamSpec("P")
|
|
|
|
R = t.TypeVar("R")
|
|
|
|
|
|
def _posixify(name: str) -> str:
|
|
return "-".join(name.split()).lower()
|
|
|
|
|
|
def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:
|
|
"""Wraps a function so that it swallows exceptions."""
|
|
|
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
|
|
try:
|
|
return func(*args, **kwargs)
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
return update_wrapper(wrapper, func)
|
|
|
|
|
|
def make_str(value: t.Any) -> str:
|
|
"""Converts a value into a valid string."""
|
|
if isinstance(value, bytes):
|
|
try:
|
|
return value.decode(sys.getfilesystemencoding())
|
|
except UnicodeError:
|
|
return value.decode("utf-8", "replace")
|
|
return str(value)
|
|
|
|
|
|
def make_default_short_help(help: str, max_length: int = 45) -> str:
|
|
"""Returns a condensed version of help string.
|
|
|
|
:meta private:
|
|
"""
|
|
# Consider only the first paragraph.
|
|
paragraph_end = help.find("\n\n")
|
|
|
|
if paragraph_end != -1:
|
|
help = help[:paragraph_end]
|
|
|
|
# Collapse newlines, tabs, and spaces.
|
|
words = help.split()
|
|
|
|
if not words:
|
|
return ""
|
|
|
|
# The first paragraph started with a "no rewrap" marker, ignore it.
|
|
if words[0] == "\b":
|
|
words = words[1:]
|
|
|
|
total_length = 0
|
|
last_index = len(words) - 1
|
|
|
|
for i, word in enumerate(words):
|
|
total_length += len(word) + (i > 0)
|
|
|
|
if total_length > max_length: # too long, truncate
|
|
break
|
|
|
|
if word[-1] == ".": # sentence end, truncate without "..."
|
|
return " ".join(words[: i + 1])
|
|
|
|
if total_length == max_length and i != last_index:
|
|
break # not at sentence end, truncate with "..."
|
|
else:
|
|
return " ".join(words) # no truncation needed
|
|
|
|
# Account for the length of the suffix.
|
|
total_length += len("...")
|
|
|
|
# remove words until the length is short enough
|
|
while i > 0:
|
|
total_length -= len(words[i]) + (i > 0)
|
|
|
|
if total_length <= max_length:
|
|
break
|
|
|
|
i -= 1
|
|
|
|
return " ".join(words[:i]) + "..."
|
|
|
|
|
|
class LazyFile:
|
|
"""A lazy file works like a regular file but it does not fully open
|
|
the file but it does perform some basic checks early to see if the
|
|
filename parameter does make sense. This is useful for safely opening
|
|
files for writing.
|
|
"""
|
|
|
|
name: str
|
|
mode: str
|
|
encoding: str | None
|
|
errors: str | None
|
|
atomic: bool
|
|
_f: t.IO[t.Any] | None
|
|
should_close: bool
|
|
|
|
def __init__(
|
|
self,
|
|
filename: str | os.PathLike[str],
|
|
mode: str = "r",
|
|
encoding: str | None = None,
|
|
errors: str | None = "strict",
|
|
atomic: bool = False,
|
|
) -> None:
|
|
self.name = os.fspath(filename)
|
|
self.mode = mode
|
|
self.encoding = encoding
|
|
self.errors = errors
|
|
self.atomic = atomic
|
|
|
|
if self.name == "-":
|
|
self._f, self.should_close = open_stream(filename, mode, encoding, errors)
|
|
else:
|
|
if "r" in mode:
|
|
# Open and close the file in case we're opening it for
|
|
# reading so that we can catch at least some errors in
|
|
# some cases early.
|
|
open(filename, mode).close()
|
|
self._f = None
|
|
self.should_close = True
|
|
|
|
def __getattr__(self, name: str) -> t.Any:
|
|
return getattr(self.open(), name)
|
|
|
|
def __repr__(self) -> str:
|
|
if self._f is not None:
|
|
return repr(self._f)
|
|
return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
|
|
|
|
def open(self) -> t.IO[t.Any]:
|
|
"""Opens the file if it's not yet open. This call might fail with
|
|
a :exc:`FileError`. Not handling this error will produce an error
|
|
that Click shows.
|
|
"""
|
|
if self._f is not None:
|
|
return self._f
|
|
try:
|
|
rv, self.should_close = open_stream(
|
|
self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
|
|
)
|
|
except OSError as e:
|
|
from .exceptions import FileError
|
|
|
|
raise FileError(self.name, hint=e.strerror) from e
|
|
self._f = rv
|
|
return rv
|
|
|
|
def close(self) -> None:
|
|
"""Closes the underlying file, no matter what."""
|
|
if self._f is not None:
|
|
self._f.close()
|
|
|
|
def close_intelligently(self) -> None:
|
|
"""This function only closes the file if it was opened by the lazy
|
|
file wrapper. For instance this will never close stdin.
|
|
"""
|
|
if self.should_close:
|
|
self.close()
|
|
|
|
def __enter__(self) -> LazyFile:
|
|
return self
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: type[BaseException] | None,
|
|
exc_value: BaseException | None,
|
|
tb: TracebackType | None,
|
|
) -> None:
|
|
self.close_intelligently()
|
|
|
|
def __iter__(self) -> cabc.Iterator[t.AnyStr]:
|
|
self.open()
|
|
return iter(self._f) # type: ignore
|
|
|
|
|
|
class KeepOpenFile:
|
|
"""Proxy a file object but keep it open across a ``with`` block.
|
|
|
|
Wraps a borrowed file (such as ``sys.stdin`` or ``sys.stdout``) so that
|
|
leaving a ``with`` block does not close it, as used by :func:`open_file`
|
|
for the ``-`` filename. The caller stays responsible for the file: an
|
|
explicit :meth:`close` still passes through to the wrapped object.
|
|
|
|
Dunder methods are proxied explicitly: implicit special-method lookups
|
|
bypass :meth:`__getattr__`, because Python resolves them on the type rather
|
|
than the instance.
|
|
"""
|
|
|
|
_file: t.IO[t.Any]
|
|
|
|
def __init__(self, file: t.IO[t.Any]) -> None:
|
|
self._file = file
|
|
|
|
def __getattr__(self, name: str) -> t.Any:
|
|
return getattr(self._file, name)
|
|
|
|
def __enter__(self) -> KeepOpenFile:
|
|
return self
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: type[BaseException] | None,
|
|
exc_value: BaseException | None,
|
|
tb: TracebackType | None,
|
|
) -> None:
|
|
pass
|
|
|
|
def __repr__(self) -> str:
|
|
return repr(self._file)
|
|
|
|
def __iter__(self) -> cabc.Iterator[t.AnyStr]:
|
|
return iter(self._file)
|
|
|
|
|
|
def echo(
|
|
message: object = None,
|
|
file: t.IO[t.Any] | None = None,
|
|
nl: bool = True,
|
|
err: bool = False,
|
|
color: bool | None = None,
|
|
) -> None:
|
|
"""Print a message and newline to stdout or a file. This should be
|
|
used instead of :func:`print` because it provides better support
|
|
for different data, files, and environments.
|
|
|
|
Compared to :func:`print`, this does the following:
|
|
|
|
- Ensures that the output encoding is not misconfigured on Linux.
|
|
- Supports Unicode in the Windows console.
|
|
- Supports writing to binary outputs, and supports writing bytes
|
|
to text outputs.
|
|
- Supports colors and styles on Windows.
|
|
- Removes ANSI color and style codes if the output does not look
|
|
like an interactive terminal.
|
|
- Always flushes the output.
|
|
|
|
:param message: The string or bytes to output. Other objects are
|
|
converted to strings.
|
|
:param file: The file to write to. Defaults to ``stdout``.
|
|
:param err: Write to ``stderr`` instead of ``stdout``.
|
|
:param nl: Print a newline after the message. Enabled by default.
|
|
:param color: Force showing or hiding colors and other styles. By
|
|
default Click will remove color if the output does not look like
|
|
an interactive terminal.
|
|
|
|
.. versionchanged:: 6.0
|
|
Support Unicode output on the Windows console. Click does not
|
|
modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
|
|
will still not support Unicode.
|
|
|
|
.. versionchanged:: 4.0
|
|
Added the ``color`` parameter.
|
|
|
|
.. versionadded:: 3.0
|
|
Added the ``err`` parameter.
|
|
|
|
.. versionchanged:: 2.0
|
|
Support colors on Windows if colorama is installed.
|
|
"""
|
|
if file is None:
|
|
if err:
|
|
file = _default_text_stderr()
|
|
else:
|
|
file = _default_text_stdout()
|
|
|
|
# There are no standard streams attached to write to. For example,
|
|
# pythonw on Windows.
|
|
if file is None:
|
|
return
|
|
|
|
match message:
|
|
case str() | bytes() | bytearray():
|
|
out = message
|
|
case None:
|
|
out = ""
|
|
case _:
|
|
out = str(message)
|
|
|
|
if nl:
|
|
if isinstance(out, str):
|
|
out += "\n"
|
|
else:
|
|
out += b"\n"
|
|
|
|
if not out:
|
|
file.flush()
|
|
return
|
|
|
|
# If there is a message and the value looks like bytes, we manually
|
|
# need to find the binary stream and write the message in there.
|
|
# This is done separately so that most stream types will work as you
|
|
# would expect. Eg: you can write to StringIO for other cases.
|
|
if isinstance(out, (bytes, bytearray)):
|
|
binary_file = _find_binary_writer(file)
|
|
if binary_file is not None:
|
|
file.flush()
|
|
binary_file.write(out)
|
|
binary_file.flush()
|
|
return
|
|
|
|
# ANSI style code support. For no message or bytes, nothing happens.
|
|
# When outputting to a file instead of a terminal, strip codes.
|
|
else:
|
|
color = resolve_color_default(color)
|
|
|
|
if should_strip_ansi(file, color):
|
|
out = strip_ansi(out)
|
|
elif WIN:
|
|
if auto_wrap_for_ansi is not None:
|
|
file = auto_wrap_for_ansi(file, color) # type: ignore
|
|
elif not color:
|
|
out = strip_ansi(out)
|
|
|
|
file.write(out) # type: ignore
|
|
file.flush()
|
|
|
|
|
|
def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:
|
|
"""Returns a system stream for byte processing.
|
|
|
|
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
|
``'stdout'`` and ``'stderr'``
|
|
"""
|
|
opener = binary_streams.get(name)
|
|
if opener is None:
|
|
raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
|
|
return opener()
|
|
|
|
|
|
def get_text_stream(
|
|
name: t.Literal["stdin", "stdout", "stderr"],
|
|
encoding: str | None = None,
|
|
errors: str | None = "strict",
|
|
) -> t.TextIO:
|
|
"""Returns a system stream for text processing. This usually returns
|
|
a wrapped stream around a binary stream returned from
|
|
:func:`get_binary_stream` but it also can take shortcuts for already
|
|
correctly configured streams.
|
|
|
|
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
|
``'stdout'`` and ``'stderr'``
|
|
:param encoding: overrides the detected default encoding.
|
|
:param errors: overrides the default error mode.
|
|
"""
|
|
opener = text_streams.get(name)
|
|
if opener is None:
|
|
raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
|
|
return opener(encoding, errors)
|
|
|
|
|
|
def open_file(
|
|
filename: str | os.PathLike[str],
|
|
mode: str = "r",
|
|
encoding: str | None = None,
|
|
errors: str | None = "strict",
|
|
lazy: bool = False,
|
|
atomic: bool = False,
|
|
) -> t.IO[t.Any]:
|
|
"""Open a file, with extra behavior to handle ``'-'`` to indicate
|
|
a standard stream, lazy open on write, and atomic write. Similar to
|
|
the behavior of the :class:`~click.File` param type.
|
|
|
|
If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
|
|
wrapped so that using it in a context manager will not close it.
|
|
This makes it possible to use the function without accidentally
|
|
closing a standard stream:
|
|
|
|
.. code-block:: python
|
|
|
|
with open_file(filename) as f:
|
|
...
|
|
|
|
:param filename: The name or Path of the file to open, or ``'-'`` for
|
|
``stdin``/``stdout``.
|
|
:param mode: The mode in which to open the file.
|
|
:param encoding: The encoding to decode or encode a file opened in
|
|
text mode.
|
|
:param errors: The error handling mode.
|
|
:param lazy: Wait to open the file until it is accessed. For read
|
|
mode, the file is temporarily opened to raise access errors
|
|
early, then closed until it is read again.
|
|
:param atomic: Write to a temporary file and replace the given file
|
|
on close.
|
|
|
|
.. versionadded:: 3.0
|
|
"""
|
|
if lazy:
|
|
return t.cast(
|
|
"t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)
|
|
)
|
|
|
|
f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
|
|
|
|
if not should_close:
|
|
f = t.cast("t.IO[t.Any]", KeepOpenFile(f))
|
|
|
|
return f
|
|
|
|
|
|
def format_filename(
|
|
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],
|
|
shorten: bool = False,
|
|
) -> str:
|
|
"""Format a filename as a string for display. Ensures the filename can be
|
|
displayed by replacing any invalid bytes or surrogate escapes in the name
|
|
with the replacement character ``�``.
|
|
|
|
Invalid bytes or surrogate escapes will raise an error when written to a
|
|
stream with ``errors="strict"``. This will typically happen with ``stdout``
|
|
when the locale is something like ``en_GB.UTF-8``.
|
|
|
|
Many scenarios *are* safe to write surrogates though, due to PEP 538 and
|
|
PEP 540, including:
|
|
|
|
- Writing to ``stderr``, which uses ``errors="backslashreplace"``.
|
|
- The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
|
|
stdout and stderr with ``errors="surrogateescape"``.
|
|
- None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
|
|
- Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
|
|
Python opens stdout and stderr with ``errors="surrogateescape"``.
|
|
|
|
:param filename: formats a filename for UI display. This will also convert
|
|
the filename into unicode without failing.
|
|
:param shorten: this optionally shortens the filename to strip of the
|
|
path that leads up to it.
|
|
"""
|
|
if shorten:
|
|
filename = os.path.basename(filename)
|
|
else:
|
|
filename = os.fspath(filename)
|
|
|
|
if isinstance(filename, bytes):
|
|
filename = filename.decode(sys.getfilesystemencoding(), "replace")
|
|
else:
|
|
filename = filename.encode("utf-8", "surrogateescape").decode(
|
|
"utf-8", "replace"
|
|
)
|
|
|
|
return filename
|
|
|
|
|
|
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
|
|
r"""Returns the config folder for the application. The default behavior
|
|
is to return whatever is most appropriate for the operating system.
|
|
|
|
To give you an idea, for an app called ``"Foo Bar"``, something like
|
|
the following folders could be returned:
|
|
|
|
Mac OS X:
|
|
``~/Library/Application Support/Foo Bar``
|
|
Mac OS X (POSIX):
|
|
``~/.foo-bar``
|
|
Unix:
|
|
``~/.config/foo-bar``
|
|
Unix (POSIX):
|
|
``~/.foo-bar``
|
|
Windows (roaming):
|
|
``C:\Users\<user>\AppData\Roaming\Foo Bar``
|
|
Windows (not roaming):
|
|
``C:\Users\<user>\AppData\Local\Foo Bar``
|
|
|
|
.. versionadded:: 2.0
|
|
|
|
:param app_name: the application name. This should be properly capitalized
|
|
and can contain whitespace.
|
|
:param roaming: controls if the folder should be roaming or not on Windows.
|
|
Has no effect otherwise.
|
|
:param force_posix: if this is set to `True` then on any POSIX system the
|
|
folder will be stored in the home folder with a leading
|
|
dot instead of the XDG config home or darwin's
|
|
application support folder.
|
|
"""
|
|
if WIN:
|
|
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
|
folder = os.environ.get(key)
|
|
if folder is None:
|
|
folder = os.path.expanduser("~")
|
|
return os.path.join(folder, app_name)
|
|
if force_posix:
|
|
return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
|
|
if sys.platform == "darwin":
|
|
return os.path.join(
|
|
os.path.expanduser("~/Library/Application Support"), app_name
|
|
)
|
|
return os.path.join(
|
|
os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
|
|
_posixify(app_name),
|
|
)
|
|
|
|
|
|
class PacifyFlushWrapper:
|
|
"""This wrapper is used to catch and suppress BrokenPipeErrors resulting
|
|
from ``.flush()`` being called on broken pipe during the shutdown/final-GC
|
|
of the Python interpreter. Notably ``.flush()`` is always called on
|
|
``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
|
|
other cleanup code, and the case where the underlying file is not a broken
|
|
pipe, all calls and attributes are proxied.
|
|
"""
|
|
|
|
wrapped: t.IO[t.Any]
|
|
|
|
def __init__(self, wrapped: t.IO[t.Any]) -> None:
|
|
self.wrapped = wrapped
|
|
|
|
def flush(self) -> None:
|
|
try:
|
|
self.wrapped.flush()
|
|
except OSError as e:
|
|
import errno
|
|
|
|
if e.errno != errno.EPIPE:
|
|
raise
|
|
|
|
def __getattr__(self, attr: str) -> t.Any:
|
|
return getattr(self.wrapped, attr)
|
|
|
|
|
|
def _detect_program_name(
|
|
path: str | None = None, _main: ModuleType | None = None
|
|
) -> str:
|
|
"""Determine the command used to run the program, for use in help
|
|
text. If a file or entry point was executed, the file name is
|
|
returned. If ``python -m`` was used to execute a module or package,
|
|
``python -m name`` is returned.
|
|
|
|
This doesn't try to be too precise, the goal is to give a concise
|
|
name for help text. Files are only shown as their name without the
|
|
path. ``python`` is only shown for modules, and the full path to
|
|
``sys.executable`` is not shown.
|
|
|
|
:param path: The Python file being executed. Python puts this in
|
|
``sys.argv[0]``, which is used by default.
|
|
:param _main: The ``__main__`` module. This should only be passed
|
|
during internal testing.
|
|
|
|
.. versionadded:: 8.0
|
|
Based on command args detection in the Werkzeug reloader.
|
|
|
|
:meta private:
|
|
"""
|
|
if _main is None:
|
|
_main = sys.modules["__main__"]
|
|
|
|
if not path:
|
|
path = sys.argv[0]
|
|
|
|
# The value of __package__ indicates how Python was called. It may
|
|
# not exist if a setuptools script is installed as an egg. It may be
|
|
# set incorrectly for entry points created with pip on Windows.
|
|
# It is set to "" inside a Shiv or PEX zipapp.
|
|
if getattr(_main, "__package__", None) in {None, ""} or (
|
|
os.name == "nt"
|
|
and _main.__package__ == ""
|
|
and not os.path.exists(path)
|
|
and os.path.exists(f"{path}.exe")
|
|
):
|
|
# Executed a file, like "python app.py".
|
|
return os.path.basename(path)
|
|
|
|
# Executed a module, like "python -m example".
|
|
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
|
# Need to look at main module to determine how it was executed.
|
|
py_module = t.cast(str, _main.__package__)
|
|
name = os.path.splitext(os.path.basename(path))[0]
|
|
|
|
# A submodule like "example.cli".
|
|
if name != "__main__":
|
|
py_module = f"{py_module}.{name}"
|
|
|
|
return f"python -m {py_module.lstrip('.')}"
|
|
|
|
|
|
def _expand_args(
|
|
args: cabc.Iterable[str],
|
|
*,
|
|
user: bool = True,
|
|
env: bool = True,
|
|
glob_recursive: bool = True,
|
|
) -> list[str]:
|
|
"""Simulate Unix shell expansion with Python functions.
|
|
|
|
See :func:`glob.glob`, :func:`os.path.expanduser`, and
|
|
:func:`os.path.expandvars`.
|
|
|
|
This is intended for use on Windows, where the shell does not do any
|
|
expansion. It may not exactly match what a Unix shell would do.
|
|
|
|
:param args: List of command line arguments to expand.
|
|
:param user: Expand user home directory.
|
|
:param env: Expand environment variables.
|
|
:param glob_recursive: ``**`` matches directories recursively.
|
|
|
|
.. versionchanged:: 8.1
|
|
Invalid glob patterns are treated as empty expansions rather
|
|
than raising an error.
|
|
|
|
.. versionadded:: 8.0
|
|
|
|
:meta private:
|
|
"""
|
|
from glob import glob
|
|
|
|
out = []
|
|
|
|
for arg in args:
|
|
if user:
|
|
arg = os.path.expanduser(arg)
|
|
|
|
if env:
|
|
arg = os.path.expandvars(arg)
|
|
|
|
try:
|
|
matches = glob(arg, recursive=glob_recursive)
|
|
except re.error:
|
|
matches = []
|
|
|
|
if not matches:
|
|
out.append(arg)
|
|
else:
|
|
out.extend(matches)
|
|
|
|
return out
|