mintterm 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mintterm/__init__.py +3 -0
- mintterm/__main__.py +38 -0
- mintterm/app.py +765 -0
- mintterm/assets/icon.svg +12 -0
- mintterm/assets/logo.svg +15 -0
- mintterm/branding.py +21 -0
- mintterm/clipboard.py +22 -0
- mintterm/helper.py +132 -0
- mintterm/prompt.py +64 -0
- mintterm/render.py +23 -0
- mintterm/runner.py +106 -0
- mintterm/safety.py +97 -0
- mintterm/storage.py +82 -0
- mintterm/themes.py +34 -0
- mintterm/trash.py +68 -0
- mintterm/views.py +412 -0
- mintterm-0.2.0.dist-info/METADATA +168 -0
- mintterm-0.2.0.dist-info/RECORD +22 -0
- mintterm-0.2.0.dist-info/WHEEL +5 -0
- mintterm-0.2.0.dist-info/entry_points.txt +2 -0
- mintterm-0.2.0.dist-info/licenses/LICENSE +21 -0
- mintterm-0.2.0.dist-info/top_level.txt +1 -0
mintterm/assets/icon.svg
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-label="mintterm icon">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#2b3629"/>
|
|
5
|
+
<stop offset="1" stop-color="#1d211c"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<rect x="16" y="16" width="480" height="480" rx="104" fill="url(#bg)"/>
|
|
9
|
+
<path d="M128 168 L236 256 L128 344" fill="none" stroke="#87cf3e" stroke-width="44" stroke-linecap="round" stroke-linejoin="round"/>
|
|
10
|
+
<rect x="270" y="326" width="122" height="36" rx="18" fill="#87cf3e"/>
|
|
11
|
+
<path d="M400 112 C 334 112 292 156 292 212 C 352 212 400 170 400 112 Z" fill="#4f8f24"/>
|
|
12
|
+
</svg>
|
mintterm/assets/logo.svg
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 160" role="img" aria-label="mintterm logo">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#2b3629"/>
|
|
5
|
+
<stop offset="1" stop-color="#1d211c"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<g transform="translate(8 8) scale(0.13)">
|
|
9
|
+
<rect x="16" y="16" width="480" height="480" rx="104" fill="url(#bg)"/>
|
|
10
|
+
<path d="M128 168 L236 256 L128 344" fill="none" stroke="#87cf3e" stroke-width="44" stroke-linecap="round" stroke-linejoin="round"/>
|
|
11
|
+
<rect x="270" y="326" width="122" height="36" rx="18" fill="#87cf3e"/>
|
|
12
|
+
<path d="M400 112 C 334 112 292 156 292 212 C 352 212 400 170 400 112 Z" fill="#4f8f24"/>
|
|
13
|
+
</g>
|
|
14
|
+
<text x="150" y="98" font-family="Ubuntu, 'Noto Sans', system-ui, sans-serif" font-size="64" font-weight="700" fill="#1f2a1c" letter-spacing="-1">mintterm</text>
|
|
15
|
+
</svg>
|
mintterm/branding.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Window icon. Matches assets/icon.svg, drawn at runtime because pygame cannot load SVG."""
|
|
2
|
+
|
|
3
|
+
import pygame
|
|
4
|
+
|
|
5
|
+
DARK = (29, 33, 28)
|
|
6
|
+
MINT = (135, 207, 62)
|
|
7
|
+
LEAF = (79, 143, 36)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_icon(size=64):
|
|
11
|
+
surf = pygame.Surface((size, size), pygame.SRCALPHA)
|
|
12
|
+
s = size / 512
|
|
13
|
+
pygame.draw.rect(surf, DARK, (0, 0, size, size), border_radius=int(104 * s))
|
|
14
|
+
|
|
15
|
+
width = max(2, int(44 * s))
|
|
16
|
+
pygame.draw.lines(surf, MINT, False, [(128 * s, 168 * s), (236 * s, 256 * s), (128 * s, 344 * s)], width)
|
|
17
|
+
pygame.draw.rect(surf, MINT, (270 * s, 326 * s, 122 * s, 36 * s), border_radius=int(18 * s))
|
|
18
|
+
|
|
19
|
+
leaf = [(400 * s, 112 * s), (330 * s, 130 * s), (292 * s, 212 * s), (352 * s, 212 * s)]
|
|
20
|
+
pygame.draw.polygon(surf, LEAF, leaf)
|
|
21
|
+
return surf
|
mintterm/clipboard.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Copy text to the clipboard through wl-copy (Wayland) or xclip/xsel (X11)."""
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import subprocess
|
|
5
|
+
|
|
6
|
+
_TOOLS = [
|
|
7
|
+
["wl-copy"],
|
|
8
|
+
["xclip", "-selection", "clipboard"],
|
|
9
|
+
["xsel", "--clipboard", "--input"],
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def copy_text(text):
|
|
14
|
+
for tool in _TOOLS:
|
|
15
|
+
if shutil.which(tool[0]) is None:
|
|
16
|
+
continue
|
|
17
|
+
try:
|
|
18
|
+
subprocess.run(tool, input=text.encode("utf-8"), timeout=3, check=True)
|
|
19
|
+
return True
|
|
20
|
+
except (subprocess.SubprocessError, OSError):
|
|
21
|
+
continue
|
|
22
|
+
return False
|
mintterm/helper.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""The ? helper: plain-English suggestions, command explanations, and tab completion.
|
|
2
|
+
|
|
3
|
+
Nothing here runs a command. Suggestions are text the user can copy or type.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from .views import kv_view, text_view
|
|
10
|
+
|
|
11
|
+
# (pattern, idea, command, what it does)
|
|
12
|
+
INTENTS = [
|
|
13
|
+
(r"git.*undo|undo.*commit", "Undo the last commit, keep the changes",
|
|
14
|
+
"git reset --soft HEAD~1", "Moves the last commit back into your staged changes."),
|
|
15
|
+
(r"extract|unzip|untar", "Extract an archive",
|
|
16
|
+
"tar -xf ARCHIVE.tar.gz", "Unpacks a .tar.gz into the current folder. For .zip use unzip ARCHIVE.zip."),
|
|
17
|
+
(r"zip|compress|archive", "Compress a folder",
|
|
18
|
+
"tar -czf NAME.tar.gz FOLDER", "Makes a compressed archive of FOLDER."),
|
|
19
|
+
(r"big|large|space|biggest", "Biggest folders in your home",
|
|
20
|
+
"du -h --max-depth=1 ~ | sort -rh | head -n 10", "Shows the 10 largest folders in your home directory."),
|
|
21
|
+
(r"port|listen", "Programs listening on network ports",
|
|
22
|
+
"ss -tulpn", "Lists each open port and the program using it. Type ss on its own for a table."),
|
|
23
|
+
(r"update|upgrade", "Update packages",
|
|
24
|
+
"sudo apt update && sudo apt upgrade", "Refreshes package lists, then installs updates."),
|
|
25
|
+
(r"kill|stuck|frozen|not respond", "Stop a stuck program by name",
|
|
26
|
+
"pkill -f NAME", "Stops every process whose name contains NAME. Replace NAME first."),
|
|
27
|
+
(r"disk|free space|storage", "Free space on each drive",
|
|
28
|
+
"df -h", "Shows used and free space per drive. Type df on its own for bars."),
|
|
29
|
+
(r"memory|ram", "Memory use",
|
|
30
|
+
"free -h", "Shows total, used, and available RAM and swap."),
|
|
31
|
+
(r"ip address|my ip|network address", "Your local IP addresses",
|
|
32
|
+
"ip -br addr", "Lists each network interface with its addresses."),
|
|
33
|
+
(r"find.*file|where is|locate", "Find a file by name",
|
|
34
|
+
"find ~ -iname '*NAME*'", "Searches your home folder. Replace NAME with part of the filename."),
|
|
35
|
+
(r"search text|grep|contains", "Search text inside files",
|
|
36
|
+
"grep -rn 'TEXT' .", "Searches every file under this folder for TEXT, with line numbers."),
|
|
37
|
+
(r"permission|chmod|executable|runnable", "Make a script runnable",
|
|
38
|
+
"chmod +x SCRIPT", "Adds the execute permission to SCRIPT."),
|
|
39
|
+
(r"failed service|broken service", "Services that failed to start",
|
|
40
|
+
"systemctl --failed", "Lists systemd services that did not start correctly."),
|
|
41
|
+
(r"undo|restore|deleted|trash", "Bring back removed files",
|
|
42
|
+
"undo", "Restores the last move or trash action made in mintterm."),
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
EXPLAIN = {
|
|
46
|
+
"ls": "Lists files in a folder. In mintterm it becomes a table with size, date, and permissions. ls --raw gives plain text.",
|
|
47
|
+
"cd": "Changes folder. mintterm remembers it across commands, so the prompt always shows where you are.",
|
|
48
|
+
"rm": "Deletes files. In mintterm, rm moves them to the mintterm trash, so undo can restore them. rm --really deletes for good.",
|
|
49
|
+
"mv": "Moves or renames files. mintterm records the move, so undo can put it back.",
|
|
50
|
+
"cp": "Copies files. The originals stay where they are. Copies are not undone automatically.",
|
|
51
|
+
"chmod": "Changes file permissions. chmod +x makes a file runnable. chmod -R changes a whole folder tree at once.",
|
|
52
|
+
"chown": "Changes who owns a file. Usually needs sudo.",
|
|
53
|
+
"sudo": "Runs one command as administrator. It asks for your password in the terminal that started mintterm.",
|
|
54
|
+
"apt": "Package manager for Mint and Ubuntu. apt update refreshes the lists, apt upgrade installs updates.",
|
|
55
|
+
"grep": "Searches text for a pattern. grep -rn searches a whole folder and shows line numbers.",
|
|
56
|
+
"find": "Searches for files by name, type, or size. find . -name '*.log' finds .log files below this folder.",
|
|
57
|
+
"du": "Shows how much space folders use. In mintterm it shows the biggest folders first, with shares.",
|
|
58
|
+
"df": "Shows used and free space per drive.",
|
|
59
|
+
"ps": "Lists running processes. In mintterm it shows the busiest ones first with CPU bars.",
|
|
60
|
+
"kill": "Sends a signal to a process by its ID. The default asks it to stop, kill -9 forces it.",
|
|
61
|
+
"ss": "Shows network connections and which program owns each port.",
|
|
62
|
+
"tar": "Packs or unpacks archives. -czf makes a .tar.gz, -xzf extracts one.",
|
|
63
|
+
"git": "Version control. git status shows what changed, git log shows the history.",
|
|
64
|
+
"dd": "Copies raw data byte by byte. Used to write disk images. A wrong target can erase a whole disk.",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def ask(question):
|
|
69
|
+
"""Return view items answering a ? question."""
|
|
70
|
+
q = question.strip().lower()
|
|
71
|
+
if not q:
|
|
72
|
+
return text_view([
|
|
73
|
+
"Ask in plain English, for example: ? find big files",
|
|
74
|
+
"Or ask what a command does: ? explain tar",
|
|
75
|
+
])
|
|
76
|
+
|
|
77
|
+
if q.startswith("explain"):
|
|
78
|
+
words = q.split()
|
|
79
|
+
name = words[1] if len(words) > 1 else ""
|
|
80
|
+
if name in EXPLAIN:
|
|
81
|
+
return text_view([EXPLAIN[name]])
|
|
82
|
+
return text_view([f"No explanation for '{name}' yet. Try: ls, rm, mv, chmod, grep, find, tar, git."])
|
|
83
|
+
|
|
84
|
+
hits = [item for item in INTENTS if re.search(item[0], q)]
|
|
85
|
+
if not hits:
|
|
86
|
+
return text_view([
|
|
87
|
+
"No suggestion for that yet. Try 'find big files', 'which ports are open', or 'free disk space'.",
|
|
88
|
+
])
|
|
89
|
+
|
|
90
|
+
items = []
|
|
91
|
+
for _, idea, command, does in hits[:3]:
|
|
92
|
+
items += kv_view([("idea", idea), ("command", command), ("does", does)])
|
|
93
|
+
items += text_view(["Nothing runs from here. Type the command yourself after changing the CAPITALISED parts."])
|
|
94
|
+
return items
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def complete(line, cwd):
|
|
98
|
+
"""Complete the last word of a command line against files in cwd.
|
|
99
|
+
|
|
100
|
+
Returns (new_line, options). options is non-empty only when several names match.
|
|
101
|
+
"""
|
|
102
|
+
head, sep, token = line.rpartition(" ")
|
|
103
|
+
prefix = head + sep
|
|
104
|
+
|
|
105
|
+
expanded = os.path.expanduser(token)
|
|
106
|
+
dir_part, base = os.path.split(expanded)
|
|
107
|
+
search = dir_part if os.path.isabs(dir_part) else os.path.join(cwd, dir_part)
|
|
108
|
+
try:
|
|
109
|
+
entries = os.listdir(search)
|
|
110
|
+
except OSError:
|
|
111
|
+
return line, []
|
|
112
|
+
|
|
113
|
+
show_hidden = base.startswith(".")
|
|
114
|
+
matches = sorted(
|
|
115
|
+
e for e in entries if e.startswith(base) and (show_hidden or not e.startswith("."))
|
|
116
|
+
)
|
|
117
|
+
if not matches:
|
|
118
|
+
return line, []
|
|
119
|
+
|
|
120
|
+
orig_dir = os.path.split(token)[0]
|
|
121
|
+
|
|
122
|
+
def as_token(name):
|
|
123
|
+
full = os.path.join(search, name)
|
|
124
|
+
t = os.path.join(orig_dir, name) if orig_dir else name
|
|
125
|
+
return t + ("/" if os.path.isdir(full) else "")
|
|
126
|
+
|
|
127
|
+
if len(matches) == 1:
|
|
128
|
+
return prefix + as_token(matches[0]), []
|
|
129
|
+
|
|
130
|
+
common = os.path.commonprefix(matches)
|
|
131
|
+
new_token = os.path.join(orig_dir, common) if orig_dir else common
|
|
132
|
+
return prefix + new_token, matches
|
mintterm/prompt.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Build the prompt from enabled segments: time, user, host, path, git, venv, exit code."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import socket
|
|
5
|
+
import subprocess
|
|
6
|
+
|
|
7
|
+
HOME = os.path.expanduser("~")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def identity():
|
|
11
|
+
user = os.environ.get("USER") or os.environ.get("LOGNAME") or "user"
|
|
12
|
+
host = socket.gethostname().split(".")[0]
|
|
13
|
+
return user, host
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def short_path(path):
|
|
17
|
+
if path == HOME:
|
|
18
|
+
return "~"
|
|
19
|
+
if path.startswith(HOME + os.sep):
|
|
20
|
+
return "~" + path[len(HOME):]
|
|
21
|
+
return path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def git_branch(cwd):
|
|
25
|
+
try:
|
|
26
|
+
proc = subprocess.run(
|
|
27
|
+
["git", "-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"],
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
timeout=1,
|
|
31
|
+
)
|
|
32
|
+
except (OSError, subprocess.SubprocessError):
|
|
33
|
+
return None
|
|
34
|
+
if proc.returncode != 0:
|
|
35
|
+
return None
|
|
36
|
+
return proc.stdout.strip() or None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def build(segments, cwd, ok, branch, venv, user, host, now):
|
|
40
|
+
"""Return the prompt as a list of (text, color_key) pieces."""
|
|
41
|
+
pieces = []
|
|
42
|
+
if "time" in segments:
|
|
43
|
+
pieces.append((f"{now} ", "muted"))
|
|
44
|
+
|
|
45
|
+
who = []
|
|
46
|
+
if "user" in segments:
|
|
47
|
+
who.append((user, "prompt"))
|
|
48
|
+
if "host" in segments:
|
|
49
|
+
if who:
|
|
50
|
+
who.append(("@", "muted"))
|
|
51
|
+
who.append((host, "muted"))
|
|
52
|
+
if who:
|
|
53
|
+
pieces += who + [(" ", "fg")]
|
|
54
|
+
|
|
55
|
+
if "path" in segments:
|
|
56
|
+
pieces.append((f"{short_path(cwd)} ", "fg"))
|
|
57
|
+
if "git" in segments and branch:
|
|
58
|
+
pieces.append((f"⎇ {branch} ", "accent"))
|
|
59
|
+
if "venv" in segments and venv:
|
|
60
|
+
pieces.append((f"({os.path.basename(venv)}) ", "muted"))
|
|
61
|
+
if "exit" in segments and not ok:
|
|
62
|
+
pieces.append(("✗ ", "warn"))
|
|
63
|
+
pieces.append(("❯ ", "prompt"))
|
|
64
|
+
return pieces
|
mintterm/render.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Turn plain command output into structured rows the UI can draw."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def parse_df(text: str) -> list[dict]:
|
|
5
|
+
"""Parse `df -h` output into rows with a usage percentage for each mount."""
|
|
6
|
+
rows = []
|
|
7
|
+
for line in text.splitlines()[1:]: # skip the header line
|
|
8
|
+
parts = line.split(None, 5)
|
|
9
|
+
if len(parts) < 6:
|
|
10
|
+
continue
|
|
11
|
+
_fs, size, used, avail, pct, mount = parts
|
|
12
|
+
if not (pct.endswith("%") and pct[:-1].isdigit()):
|
|
13
|
+
continue
|
|
14
|
+
rows.append(
|
|
15
|
+
{
|
|
16
|
+
"mount": mount,
|
|
17
|
+
"size": size,
|
|
18
|
+
"used": used,
|
|
19
|
+
"avail": avail,
|
|
20
|
+
"pct": int(pct[:-1]),
|
|
21
|
+
}
|
|
22
|
+
)
|
|
23
|
+
return rows
|
mintterm/runner.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Run commands in bash, keep track of the working directory, and allow cancelling."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import signal
|
|
6
|
+
import subprocess
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
# Printed after every command so we can learn where `cd` left us.
|
|
11
|
+
MARK = "__MINTTERM_CWD__"
|
|
12
|
+
ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
|
|
13
|
+
HOME = os.path.expanduser("~")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Block:
|
|
18
|
+
"""One command and its output, shown as a card.
|
|
19
|
+
|
|
20
|
+
An empty command means a note (for example "Cancelled" or help text).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
command: str
|
|
24
|
+
cwd: str
|
|
25
|
+
prompt: list = field(default_factory=list)
|
|
26
|
+
view: list = field(default_factory=list)
|
|
27
|
+
output: str = ""
|
|
28
|
+
code: int | None = None
|
|
29
|
+
seconds: float = 0.0
|
|
30
|
+
running: bool = False
|
|
31
|
+
folded: bool = False
|
|
32
|
+
pinned: bool = False
|
|
33
|
+
render: object = None # optional function that turns a Result into view items
|
|
34
|
+
on_success: object = None # optional callback run in the UI thread after exit 0
|
|
35
|
+
result: object = None # filled by the worker thread, read by the UI thread
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Result:
|
|
40
|
+
output: str
|
|
41
|
+
code: int
|
|
42
|
+
seconds: float
|
|
43
|
+
cwd: str # folder after the command (tracks cd)
|
|
44
|
+
start_cwd: str # folder the command started in
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run(command, cwd, holder=None, timeout=None):
|
|
48
|
+
"""Run `command` in bash from `cwd`.
|
|
49
|
+
|
|
50
|
+
If holder is a list, the Popen object is appended so another thread can cancel it.
|
|
51
|
+
"""
|
|
52
|
+
if not os.path.isdir(cwd):
|
|
53
|
+
cwd = HOME
|
|
54
|
+
|
|
55
|
+
wrapped = (
|
|
56
|
+
f"{command}\n"
|
|
57
|
+
f"__mt_rc=$?\n"
|
|
58
|
+
f'printf "\\n{MARK}%s\\n" "$PWD"\n'
|
|
59
|
+
f"exit $__mt_rc"
|
|
60
|
+
)
|
|
61
|
+
start = time.monotonic()
|
|
62
|
+
proc = subprocess.Popen(
|
|
63
|
+
["bash", "-c", wrapped],
|
|
64
|
+
cwd=cwd,
|
|
65
|
+
stdin=subprocess.DEVNULL, # commands that read input get EOF instead of hanging
|
|
66
|
+
stdout=subprocess.PIPE,
|
|
67
|
+
stderr=subprocess.STDOUT, # keep stdout and stderr in the order they happened
|
|
68
|
+
start_new_session=True, # own process group, so Ctrl+C can stop the whole command
|
|
69
|
+
env={**os.environ, "TERM": "dumb"},
|
|
70
|
+
)
|
|
71
|
+
if holder is not None:
|
|
72
|
+
holder.append(proc)
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
out, _ = proc.communicate(timeout=timeout)
|
|
76
|
+
except subprocess.TimeoutExpired:
|
|
77
|
+
_signal(proc, signal.SIGKILL)
|
|
78
|
+
proc.communicate()
|
|
79
|
+
return Result(f"Stopped after {timeout}s.", 124, time.monotonic() - start, cwd, cwd)
|
|
80
|
+
|
|
81
|
+
seconds = time.monotonic() - start
|
|
82
|
+
code = proc.returncode
|
|
83
|
+
if code < 0:
|
|
84
|
+
code = 128 + (-code)
|
|
85
|
+
|
|
86
|
+
text = out.decode("utf-8", errors="replace")
|
|
87
|
+
new_cwd = cwd
|
|
88
|
+
idx = text.rfind(MARK)
|
|
89
|
+
if idx != -1:
|
|
90
|
+
new_cwd = text[idx + len(MARK):].strip() or cwd
|
|
91
|
+
text = text[:idx]
|
|
92
|
+
|
|
93
|
+
text = ANSI.sub("", text).rstrip("\n")
|
|
94
|
+
return Result(text, code, seconds, new_cwd, cwd)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cancel(proc):
|
|
98
|
+
"""Send Ctrl+C to a running command's process group."""
|
|
99
|
+
_signal(proc, signal.SIGINT)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _signal(proc, sig):
|
|
103
|
+
try:
|
|
104
|
+
os.killpg(proc.pid, sig)
|
|
105
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
106
|
+
pass
|
mintterm/safety.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Decide which commands need a dry-run preview and confirmation before they run."""
|
|
2
|
+
|
|
3
|
+
import glob
|
|
4
|
+
import os
|
|
5
|
+
import shlex
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
PREVIEW_LIMIT = 40
|
|
9
|
+
DESTRUCTIVE_PROGRAMS = {"dd", "mkfs", "shred", "wipefs", "fdisk", "parted"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _words(command):
|
|
13
|
+
words = shlex.split(command)
|
|
14
|
+
if words and os.path.basename(words[0]) == "sudo":
|
|
15
|
+
words = words[1:]
|
|
16
|
+
return words
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def needs_confirmation(command):
|
|
20
|
+
"""True if the command can wipe, overwrite, or change permissions in bulk."""
|
|
21
|
+
try:
|
|
22
|
+
words = _words(command)
|
|
23
|
+
except ValueError:
|
|
24
|
+
return True # unreadable input is treated as risky
|
|
25
|
+
if not words:
|
|
26
|
+
return False
|
|
27
|
+
|
|
28
|
+
prog = os.path.basename(words[0])
|
|
29
|
+
args = words[1:]
|
|
30
|
+
short_flags = "".join(a[1:] for a in args if a.startswith("-") and not a.startswith("--"))
|
|
31
|
+
|
|
32
|
+
if prog == "rm":
|
|
33
|
+
return (
|
|
34
|
+
any(a in ("--recursive", "--force") for a in args)
|
|
35
|
+
or "r" in short_flags
|
|
36
|
+
or "R" in short_flags
|
|
37
|
+
or "f" in short_flags
|
|
38
|
+
)
|
|
39
|
+
if prog in DESTRUCTIVE_PROGRAMS:
|
|
40
|
+
return True
|
|
41
|
+
if prog in ("chmod", "chown"):
|
|
42
|
+
return any(a == "--recursive" for a in args) or "R" in short_flags
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def expand(args, base="."):
|
|
47
|
+
"""Turn command arguments into paths, expanding ~ and globs relative to base."""
|
|
48
|
+
paths = []
|
|
49
|
+
for arg in args:
|
|
50
|
+
if arg.startswith("-"):
|
|
51
|
+
continue
|
|
52
|
+
path = os.path.join(base, os.path.expanduser(arg))
|
|
53
|
+
if any(c in path for c in "*?["):
|
|
54
|
+
paths.extend(sorted(glob.glob(path)))
|
|
55
|
+
else:
|
|
56
|
+
paths.append(path)
|
|
57
|
+
return paths
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def preview(command, base="."):
|
|
61
|
+
"""Lines describing what the command would do, shown before the user confirms."""
|
|
62
|
+
try:
|
|
63
|
+
words = _words(command)
|
|
64
|
+
except ValueError:
|
|
65
|
+
return ["Could not parse this command. Type y to run it anyway, or anything else to cancel."]
|
|
66
|
+
if not words:
|
|
67
|
+
return []
|
|
68
|
+
if os.path.basename(words[0]) == "rm":
|
|
69
|
+
return _preview_rm(words[1:], base)
|
|
70
|
+
return ["This command changes files, disks, or permissions."]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _preview_rm(args, base):
|
|
74
|
+
targets = expand(args, base)
|
|
75
|
+
if not targets:
|
|
76
|
+
return ["rm with no targets. Nothing to preview."]
|
|
77
|
+
|
|
78
|
+
# find lists everything under each target, which is what rm -r would remove.
|
|
79
|
+
try:
|
|
80
|
+
result = subprocess.run(
|
|
81
|
+
["find", *targets],
|
|
82
|
+
capture_output=True,
|
|
83
|
+
text=True,
|
|
84
|
+
timeout=10,
|
|
85
|
+
errors="replace",
|
|
86
|
+
)
|
|
87
|
+
except subprocess.TimeoutExpired:
|
|
88
|
+
return ["Preview timed out. The target is very large. Type y to run it, or anything else to cancel."]
|
|
89
|
+
|
|
90
|
+
items = [line for line in result.stdout.splitlines() if line]
|
|
91
|
+
lines = [f"Would move {len(items)} item(s) to the mintterm trash:"]
|
|
92
|
+
lines += [" " + item for item in items[:PREVIEW_LIMIT]]
|
|
93
|
+
if len(items) > PREVIEW_LIMIT:
|
|
94
|
+
lines.append(f" ... and {len(items) - PREVIEW_LIMIT} more")
|
|
95
|
+
for err in result.stderr.splitlines()[:3]:
|
|
96
|
+
lines.append(" note: " + err)
|
|
97
|
+
return lines
|
mintterm/storage.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Where mintterm keeps its settings, command history, and trash."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
|
|
7
|
+
HOME = os.path.expanduser("~")
|
|
8
|
+
CONFIG_DIR = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(HOME, ".config"), "mintterm")
|
|
9
|
+
DATA_DIR = os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(HOME, ".local", "share"), "mintterm")
|
|
10
|
+
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
|
|
11
|
+
HISTORY_FILE = os.path.join(DATA_DIR, "history.txt")
|
|
12
|
+
TRASH_DIR = os.path.join(DATA_DIR, "trash")
|
|
13
|
+
|
|
14
|
+
SEGMENTS = ["time", "user", "host", "path", "git", "venv", "exit"]
|
|
15
|
+
|
|
16
|
+
PROFILES = {
|
|
17
|
+
"Dev": {"segments": ["user", "host", "path", "git", "venv", "exit"], "prod": False},
|
|
18
|
+
"Server": {"segments": ["time", "user", "host", "path", "exit"], "prod": True},
|
|
19
|
+
"Minimal": {"segments": ["path"], "prod": False},
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
DEFAULTS = {
|
|
23
|
+
"theme": "mint-dark",
|
|
24
|
+
"font_size": 16,
|
|
25
|
+
"profile": "Dev",
|
|
26
|
+
"segments": PROFILES["Dev"]["segments"],
|
|
27
|
+
"notify_after": 10,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_config():
|
|
32
|
+
"""Read settings from disk, falling back to defaults for anything missing or invalid."""
|
|
33
|
+
cfg = deepcopy(DEFAULTS)
|
|
34
|
+
try:
|
|
35
|
+
with open(CONFIG_FILE, encoding="utf-8") as f:
|
|
36
|
+
data = json.load(f)
|
|
37
|
+
except (OSError, ValueError):
|
|
38
|
+
data = {}
|
|
39
|
+
if isinstance(data, dict):
|
|
40
|
+
for key in DEFAULTS:
|
|
41
|
+
if key in data:
|
|
42
|
+
cfg[key] = data[key]
|
|
43
|
+
|
|
44
|
+
if not isinstance(cfg["segments"], list):
|
|
45
|
+
cfg["segments"] = list(PROFILES["Dev"]["segments"])
|
|
46
|
+
cfg["segments"] = [s for s in cfg["segments"] if s in SEGMENTS]
|
|
47
|
+
if not isinstance(cfg["font_size"], int) or not 10 <= cfg["font_size"] <= 28:
|
|
48
|
+
cfg["font_size"] = DEFAULTS["font_size"]
|
|
49
|
+
if cfg["profile"] not in PROFILES:
|
|
50
|
+
cfg["profile"] = DEFAULTS["profile"]
|
|
51
|
+
return cfg
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def save_config(cfg):
|
|
55
|
+
"""Write settings to disk. Returns False if the file could not be written."""
|
|
56
|
+
try:
|
|
57
|
+
os.makedirs(CONFIG_DIR, exist_ok=True)
|
|
58
|
+
tmp = CONFIG_FILE + ".tmp"
|
|
59
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
60
|
+
json.dump(cfg, f, indent=2)
|
|
61
|
+
os.replace(tmp, CONFIG_FILE)
|
|
62
|
+
return True
|
|
63
|
+
except OSError:
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def load_history(limit=5000):
|
|
68
|
+
try:
|
|
69
|
+
with open(HISTORY_FILE, encoding="utf-8") as f:
|
|
70
|
+
lines = [line.rstrip("\n") for line in f if line.strip()]
|
|
71
|
+
except OSError:
|
|
72
|
+
return []
|
|
73
|
+
return lines[-limit:]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def append_history(command):
|
|
77
|
+
try:
|
|
78
|
+
os.makedirs(DATA_DIR, exist_ok=True)
|
|
79
|
+
with open(HISTORY_FILE, "a", encoding="utf-8") as f:
|
|
80
|
+
f.write(command.replace("\n", " ") + "\n")
|
|
81
|
+
except OSError:
|
|
82
|
+
pass
|
mintterm/themes.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Color themes. Each value is an RGB tuple."""
|
|
2
|
+
|
|
3
|
+
THEMES = {
|
|
4
|
+
"mint-dark": {
|
|
5
|
+
"bg": (29, 33, 28),
|
|
6
|
+
"fg": (227, 232, 220),
|
|
7
|
+
"prompt": (135, 207, 62),
|
|
8
|
+
"muted": (141, 151, 134),
|
|
9
|
+
"accent": (135, 207, 62),
|
|
10
|
+
"warn": (240, 134, 108),
|
|
11
|
+
"bar_bg": (56, 64, 47),
|
|
12
|
+
"prod": (229, 83, 75),
|
|
13
|
+
},
|
|
14
|
+
"mint-light": {
|
|
15
|
+
"bg": (244, 246, 241),
|
|
16
|
+
"fg": (31, 42, 28),
|
|
17
|
+
"prompt": (79, 143, 36),
|
|
18
|
+
"muted": (102, 112, 95),
|
|
19
|
+
"accent": (79, 143, 36),
|
|
20
|
+
"warn": (184, 70, 47),
|
|
21
|
+
"bar_bg": (214, 220, 207),
|
|
22
|
+
"prod": (176, 40, 30),
|
|
23
|
+
},
|
|
24
|
+
"sunset": {
|
|
25
|
+
"bg": (34, 26, 31),
|
|
26
|
+
"fg": (241, 228, 224),
|
|
27
|
+
"prompt": (244, 162, 89),
|
|
28
|
+
"muted": (163, 141, 146),
|
|
29
|
+
"accent": (244, 162, 89),
|
|
30
|
+
"warn": (255, 123, 114),
|
|
31
|
+
"bar_bg": (66, 48, 58),
|
|
32
|
+
"prod": (255, 90, 80),
|
|
33
|
+
},
|
|
34
|
+
}
|