Skip to content

Commit

Permalink
✨ Add a tool for REPL
Browse files Browse the repository at this point in the history
  • Loading branch information
Freed-Wu committed Sep 9, 2023
1 parent d8e6aae commit bf64f9a
Show file tree
Hide file tree
Showing 8 changed files with 255 additions and 41 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ repos:
hooks:
- id: yamllint
- repo: https://github.com/executablebooks/mdformat
rev: 0.7.16
rev: 0.7.17
hooks:
- id: mdformat
additional_dependencies:
Expand All @@ -67,7 +67,7 @@ repos:
- mdformat-black
- mdformat-config
- repo: https://github.com/DavidAnson/markdownlint-cli2
rev: v0.8.1
rev: v0.9.2
hooks:
- id: markdownlint-cli2
additional_dependencies:
Expand Down
49 changes: 49 additions & 0 deletions docs/resources/tools.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Tools

## `python -m translate_shell.tools.po`

A command line interface of
[github action](https://translate-shell.readthedocs.io/en/latest/#github-action).

## `python -m translate_shell.tools.generate_prompt`

A tool to generate a prompt for:

### [lftp](https://github.com/lavv17/lftp/discussions/711)

```sh
install -d ~/.config/lftp/lftp
python -m translate_shell.tools.generate_prompt > ~/.config/lftp/lftp/rc
echo 'source ~/.config/lftp/lftp/rc' >> ~/.config/lftp/rc
```

![lftp](https://github.com/lavv17/lftp/assets/32936898/e2193cda-2ac0-4020-ac3b-a7ac2156cff6)

### [gdb](https://github.com/Freed-Wu/gdb-prompt#alternatives)

```sh
touch ~/.config/gdb/gdbinit
install -d ~/.config/gdb/gdb
python -m translate_shell.tools.generate_prompt \
--format='set extended-prompt {text}' \
--prompt-string="\n(gdb) " \
--section WHITE BLUE ' \w' \
--section WHITE BLACK '󰊕 \f' \
--section BLACK YELLOW ' \t ' >> ~/.config/gdb/gdb/gdbinit
echo 'source ~/.config/gdb/gdb/gdbinit' >> ~/.config/gdb/gdbinit
```

![gdb](https://user-images.githubusercontent.com/32936898/263782466-4dd002fd-9259-4d44-a854-5e132c32b4db.png)

## `python -m translate_shell.tools.repl`

Enter a beautiful REPL for python. Or add the following code to your
[`$PYTHONSTARTUP`](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONSTARTUP):

```python
from translate_shell.tools.repl.main import interact

interact()
```

![python](https://user-images.githubusercontent.com/32936898/205494856-6f11d1a1-b2e3-469d-91c7-8a24c400fa78.jpg)
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ file = "requirements/openai.txt"
[tool.setuptools.dynamic.optional-dependencies.po]
file = "requirements/po.txt"

[tool.setuptools.dynamic.optional-dependencies.repl]
file = "requirements/repl.txt"

[tool.setuptools.dynamic.optional-dependencies.rich]
file = "requirements/rich.txt"

Expand Down
6 changes: 6 additions & 0 deletions requirements/repl.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env -S pip install -r
# For `python -m translate_shell.tools.repl`.

jedi
repl-python-codestats
rich
96 changes: 96 additions & 0 deletions src/translate_shell/tools/repl/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
r"""This module can be called by
`python -m <https://docs.python.org/3/library/__main__.html>`_.
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from datetime import datetime

from ... import __name__ as NAME
from ... import __version__

try:
import shtab
except ImportError:
from ...external import shtab

NAME = NAME.replace("_", "-")
VERSION = rf"""{NAME} {__version__}
Copyright (C) {datetime.now().year}
Written by Wu Zhenyu
"""
EPILOG = """
Report bugs to <wuzhenyu@ustc.edu>.
"""


def get_parser() -> ArgumentParser:
r"""Get a parser for unit test."""
parser = ArgumentParser(
epilog=EPILOG, formatter_class=RawDescriptionHelpFormatter
)
parser.add_argument("--version", version=VERSION, action="version")
shtab.add_argument_to(parser)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-wakatime",
action="store_false",
dest="wakatime",
help="disable wakatime",
)
group.add_argument(
"--wakatime", action="store_true", help="enable wakatime (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-codestats",
action="store_false",
dest="codestats",
help="disable codestats",
)
group.add_argument(
"--codestats", action="store_true", help="enable codestats (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-jedi",
action="store_false",
dest="jedi",
help="disable jedi",
)
group.add_argument(
"--jedi", action="store_true", help="enable jedi (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-rich",
action="store_false",
dest="rich",
help="disable rich",
)
group.add_argument(
"--rich", action="store_true", help="enable rich (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-ps1",
action="store_false",
dest="ps1",
help="disable ps1",
)
group.add_argument(
"--ps1", action="store_true", help="enable ps1 (default)"
)
return parser


def main() -> None:
r"""Parse arguments and provide shell completions."""
parser = get_parser()
args = parser.parse_args()

from .main import interact

interact(**args.__dict__)


if __name__ == "__main__":
main()
66 changes: 66 additions & 0 deletions src/translate_shell/tools/repl/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
r"""Utils
=========
Generate a `powerlevel10k <https://github.com/romkatv/powerlevel10k>`_ -like
prompt for python.
"""
import os
import sys
from contextlib import suppress

from .ps1 import Ps1


def interact(**kwargs: bool) -> None:
"""Interact.
:param kwargs:
:type kwargs: bool
:rtype: None
"""
from code import interact as _interact

if kwargs.get("wakatime", True):
sys.ps1 = Ps1()

if kwargs.get("wakatime", True):
with suppress(ImportError):
from repl_python_wakatime.python import install_hook

install_hook()

if kwargs.get("codestats", True):
with suppress(ImportError):
from repl_python_codestats.python import (
install_hook as install_codestats_hook,
)

install_codestats_hook()

if kwargs.get("jedi", True):
with suppress(ImportError):
# Windows doesn't have readline
import readline

from jedi import settings
from jedi.utils import setup_readline

setup_readline()
settings.add_bracket_after_function = True

if kwargs.get("rich", True):
with suppress(ImportError):
import logging

from rich import pretty, traceback
from rich.logging import RichHandler

pretty.install()
traceback.install()
logging.basicConfig(
format="%(message)s",
handlers=[RichHandler(rich_tracebacks=True, markup=True)],
)

if len(sys.argv) and os.path.basename(sys.argv[0]) == "__main__.py":
_interact()
Original file line number Diff line number Diff line change
@@ -1,27 +1,12 @@
r"""PS1
=======
Generate a `powerlevel10k <https://github.com/romkatv/powerlevel10k>`_ -like
prompt for python.
Usage
~~~~~
Add the following code to your ``$PYTHONSTARTUP``:
..code:: python
import sys
from translate_shell.utils.ps1 import Ps1
sys.ps1 = Ps1()
"""
import sys
from typing import Callable

from translate_shell.utils.misc import (
from ...utils.misc import (
p10k_sections,
section_os,
section_os_icon,
section_path,
section_time,
)
Expand Down Expand Up @@ -50,7 +35,7 @@ def __init__(
self.prompt_string = prompt_string
if sections is None:
self.sections = [
("BLACK", "YELLOW", section_os()),
("BLACK", "YELLOW", section_os_icon()),
(
"GREEN",
"BLACK",
Expand Down
51 changes: 30 additions & 21 deletions src/translate_shell/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,27 @@

from ..external.colorama import Back, Fore, Style, init

ICONS = {
"emscripten": "ﰍ",
"linux": "",
"linux2": "",
"linux3": "",
"hurd": "",
"darwin": "",
"dos": "",
"win16": "",
"win32": "",
"cygwin": "",
"java": "",
"android": "",
"arch": "",
"gentoo": "",
"ubuntu": "",
"cent": "",
"debian": "",
"nixos": "",
}

init()


Expand All @@ -29,28 +50,16 @@ def section_os() -> str:
except OSError:
if os.getenv("PREFIX") == "/data/data/com.termux/files/usr":
os_name = "android"
return os_name


def section_os_icon() -> str:
"""Section os icon.
icons = {
"emscripten": "ﰍ",
"linux": "",
"linux2": "",
"linux3": "",
"hurd": "",
"darwin": "",
"dos": "",
"win16": "",
"win32": "",
"cygwin": "",
"java": "",
"android": "",
"arch": "",
"gentoo": "",
"ubuntu": "",
"cent": "",
"debian": "",
"nixos": "",
}
return icons.get(os_name, "?")
:rtype: str
"""
os_name = section_os()
return ICONS.get(os_name, "?")


def section_path() -> str:
Expand Down

0 comments on commit bf64f9a

Please sign in to comment.