vietlen 0.4.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.
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vietlen
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Bộ lệnh dòng lệnh tiếng Việt — đọc tên là hiểu nó làm gì (Vietnamese command-line tools whose names say what they do)
|
|
5
|
+
Author: glm-bot
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/glm-bot/vietlen
|
|
8
|
+
Project-URL: Issues, https://github.com/glm-bot/vietlen/issues
|
|
9
|
+
Keywords: vietnamese,cli,command-line,file-tools,backup
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Topic :: Utilities
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
Ngôn ngữ: Tiếng Việt | [English](./README.en.md)
|
|
23
|
+
|
|
24
|
+
# Lệnh Việt (vietlen)
|
|
25
|
+
|
|
26
|
+
Bộ công cụ dòng lệnh mà **đọc tên là hiểu nó làm gì** — viết bằng Python, chỉ dùng thư viện chuẩn, không cần cài gì cả.
|
|
27
|
+
|
|
28
|
+
Dự án sinh ra từ một lời hứa trong [issue #1 của glm-bot](https://github.com/glm-bot/glm-bot/issues/1): làm công cụ cho người mới tập dùng máy tính, không bắt ai phải học tiếng Anh mới biết phím này để làm gì.
|
|
29
|
+
|
|
30
|
+
[](https://github.com/glm-bot/vietlen/actions/workflows/ci.yml)
|
|
31
|
+
|
|
32
|
+
## Các lệnh
|
|
33
|
+
|
|
34
|
+
| Lệnh | Nó làm gì | Ví dụ |
|
|
35
|
+
|---|---|---|
|
|
36
|
+
| `dem` | Đếm dòng, từ, ký tự của file | `python vietlen.py dem ghi-chu.txt` |
|
|
37
|
+
| `tim` | Tìm file/thư mục theo tên | `python vietlen.py tim bao-cao --trong ~/Documents` |
|
|
38
|
+
| `kich-thuoc` | Xem dung lượng thư mục theo loại file | `python vietlen.py kich-thuoc ~/Downloads` |
|
|
39
|
+
| `ngay` | Hôm nay thứ mấy, còn bao nhiêu ngày đến mốc | `python vietlen.py ngay --den 2027-02-06` |
|
|
40
|
+
| `tim-dong` | In các dòng chứa từ khóa, kèm số dòng | `python vietlen.py tim-dong quan-trong ghi-chu.txt` |
|
|
41
|
+
| `so-sanh` | So sánh hai file theo nội dung (SHA-256) | `python vietlen.py so-sanh ban-goc.txt ban-sua.txt` |
|
|
42
|
+
| `luu` | Sao lưu file, tên kèm dấu thời gian | `python vietlen.py luu ghi-chu.txt --vao ~/sao-luu` |
|
|
43
|
+
| `don-dep` | Tìm rác trong thư mục (`__pycache__`, `.DS_Store`, `*.pyc`...), `--xoa` để dọn thật | `python vietlen.py don-dep ~/Projects --xoa` |
|
|
44
|
+
| `doi-ten` | Đổi tên hàng loạt theo cặp `--cu`/`--moi`, mặc định chỉ xem trước | `python vietlen.py doi-ten ~/Pictures --cu IMG --moi anh --thuc-su` |
|
|
45
|
+
|
|
46
|
+
Ví dụ kết quả:
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
$ python vietlen.py ngay --den 2027-02-06
|
|
50
|
+
Còn 77 ngày nữa đến 06/02/2027
|
|
51
|
+
|
|
52
|
+
$ python vietlen.py so-sanh ban-goc.txt ban-sua.txt
|
|
53
|
+
KHÁC NHAU:
|
|
54
|
+
ban-goc.txt: 8 B — sha256 1a2b3c4d5e6f...
|
|
55
|
+
ban-sua.txt: 12 B — sha256 9f8e7d6c5b4a...
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Cách dùng
|
|
59
|
+
|
|
60
|
+
Cần Python 3.9 trở lên (code chỉ dùng thư viện chuẩn, không có cú pháp mới). CI kiểm tra trên 3.11, 3.12, 3.13. Không cần cài thêm gì:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
python vietlen.py <lệnh> <tham số>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Muốn chạy như một lệnh thật (Linux/macOS):
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
chmod +x vietlen.py
|
|
70
|
+
./vietlen.py ngay --den 2027-02-06
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Hoặc cài như một gói thật (từ v0.3.0):
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pip install .
|
|
77
|
+
vietlen ngay --den 2027-02-06
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Chạy test
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
python -m unittest discover -s tests -v
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Người em họ nói tiếng Halis
|
|
87
|
+
|
|
88
|
+
Các lệnh của Lệnh Việt cũng có phiên bản viết bằng Halis tại [halis-xin-chao/vietlen-halis](https://github.com/glm-bot/halis-xin-chao/tree/main/vietlen-halis) — một cách góp file `.hls` thật vào con số thống kê mà ngôn ngữ Halis cần để được GitHub Linguist ghi nhận.
|
|
89
|
+
|
|
90
|
+
## Lộ trình
|
|
91
|
+
|
|
92
|
+
- [x] v0.1.0 — 4 lệnh đầu tiên: `dem`, `tim`, `kich-thuoc`, `ngay`
|
|
93
|
+
- [x] v0.2.0 — thêm `tim-dong`, `so-sanh`, `luu`; CI chạy trên 3 phiên bản Python (3.9, 3.11, 3.12)
|
|
94
|
+
- [x] v0.3.0 — tài liệu song ngữ (`README.en.md`), đóng gói `pyproject.toml` — cài được bằng `pip install .`
|
|
95
|
+
- [x] v0.4.0 — thêm `don-dep`, `doi-ten` — nhà có đủ 9 lệnh
|
|
96
|
+
- [ ] Đăng lên PyPI thật để `pip install vietlen` chạy ở mọi nơi
|
|
97
|
+
|
|
98
|
+
## Giấy phép
|
|
99
|
+
|
|
100
|
+
MIT — xem [LICENSE](LICENSE).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
vietlen.py,sha256=6fX1qGVliMPvYzh8JS2-dHHi6lw5-nQhzY7wci4BedM,13156
|
|
2
|
+
vietlen-0.4.0.dist-info/licenses/LICENSE,sha256=ysEBKCHY0PLFAE9aJ5WHE9OhQWtLKZUSx3SPpztJzIY,1064
|
|
3
|
+
vietlen-0.4.0.dist-info/METADATA,sha256=WKDrEutMaFyxA6gCg2sYFVITCFPXrw-LtzEuxILoE24,4340
|
|
4
|
+
vietlen-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
vietlen-0.4.0.dist-info/entry_points.txt,sha256=06PY7l2Ur_8hyW_MIf7ykouUCJbRIqyxcjwlI7LKaCY,41
|
|
6
|
+
vietlen-0.4.0.dist-info/top_level.txt,sha256=dJXvrGEUE-6LiUSywIQaf0hX9491Xc2DMbiguMBzenY,8
|
|
7
|
+
vietlen-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 glm-bot
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vietlen
|
vietlen.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""vietlen — bộ lệnh dòng lệnh tiếng Việt: đọc tên là hiểu nó làm gì.
|
|
3
|
+
|
|
4
|
+
Chỉ dùng thư viện chuẩn của Python (3.9+). Gồm các lệnh:
|
|
5
|
+
dem đếm dòng, từ, ký tự của file
|
|
6
|
+
tim tìm file/thư mục theo tên
|
|
7
|
+
kich-thuoc xem dung lượng thư mục theo loại file
|
|
8
|
+
ngay hôm nay là thứ mấy, còn bao nhiêu ngày đến mốc
|
|
9
|
+
tim-dong in các dòng chứa từ khóa, kèm số dòng
|
|
10
|
+
so-sanh so sánh hai file theo nội dung (SHA-256)
|
|
11
|
+
luu sao lưu file, tên kèm dấu thời gian
|
|
12
|
+
don-dep tìm rác trong thư mục (__pycache__, .DS_Store, *.pyc...), --xoa để dọn thật
|
|
13
|
+
doi-ten đổi tên hàng loạt theo cặp --cu/--moi, mặc định chỉ xem trước
|
|
14
|
+
|
|
15
|
+
Ví dụ:
|
|
16
|
+
python vietlen.py dem ghi-chu.txt
|
|
17
|
+
python vietlen.py tim bao-cao --trong ~/Documents
|
|
18
|
+
python vietlen.py kich-thuoc ~/Downloads
|
|
19
|
+
python vietlen.py ngay --den 2027-02-06
|
|
20
|
+
python vietlen.py tim-dong quan-trong ghi-chu.txt
|
|
21
|
+
python vietlen.py so-sanh ban-goc.txt ban-sua.txt
|
|
22
|
+
python vietlen.py luu ghi-chu.txt --vao ~/sao-luu
|
|
23
|
+
python vietlen.py don-dep ~/Projects --xoa
|
|
24
|
+
python vietlen.py doi-ten ~/Pictures --cu IMG --moi anh --thuc-su
|
|
25
|
+
"""
|
|
26
|
+
import argparse
|
|
27
|
+
import datetime
|
|
28
|
+
import hashlib
|
|
29
|
+
import shutil
|
|
30
|
+
import sys
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
THU = ["Thứ Hai", "Thứ Ba", "Thứ Tư", "Thứ Năm", "Thứ Sáu", "Thứ Bảy", "Chủ Nhật"]
|
|
34
|
+
|
|
35
|
+
THU_MUC_RAC = {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"}
|
|
36
|
+
TEN_RAC = {".DS_Store", "Thumbs.db", "desktop.ini"}
|
|
37
|
+
DUOI_RAC = {".pyc", ".pyo", ".tmp", ".swp"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def la_rac(p: Path) -> bool:
|
|
41
|
+
"""Nhận diện mục rác: thư mục cache, file hệ điều hành bỏ đi, file tạm."""
|
|
42
|
+
if p.is_dir():
|
|
43
|
+
return p.name in THU_MUC_RAC
|
|
44
|
+
if p.name in TEN_RAC or p.name.endswith("~"):
|
|
45
|
+
return True
|
|
46
|
+
return p.suffix in DUOI_RAC
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def doc_dung_luong(n: int) -> str:
|
|
50
|
+
f = float(n)
|
|
51
|
+
for don_vi in ("B", "KB", "MB", "GB", "TB"):
|
|
52
|
+
if f < 1024 or don_vi == "TB":
|
|
53
|
+
return f"{f:.0f} {don_vi}" if don_vi == "B" else f"{f:.1f} {don_vi}"
|
|
54
|
+
f /= 1024
|
|
55
|
+
return f"{f:.1f} TB"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def cmd_dem(args) -> None:
|
|
59
|
+
"""Đếm dòng, từ, ký tự của một hoặc nhiều file."""
|
|
60
|
+
tong_dong = tong_tu = tong_ky_tu = da_dem = 0
|
|
61
|
+
for ten in args.file:
|
|
62
|
+
p = Path(ten).expanduser()
|
|
63
|
+
if not p.is_file():
|
|
64
|
+
print(f"dem: không tìm thấy file '{ten}'", file=sys.stderr)
|
|
65
|
+
continue
|
|
66
|
+
text = p.read_text(encoding="utf-8", errors="replace")
|
|
67
|
+
so_dong = text.count("\n") + (1 if text and not text.endswith("\n") else 0)
|
|
68
|
+
so_tu = len(text.split())
|
|
69
|
+
so_ky_tu = len(text)
|
|
70
|
+
print(f"{p.name}: {so_dong} dòng, {so_tu} từ, {so_ky_tu} ký tự")
|
|
71
|
+
tong_dong += so_dong
|
|
72
|
+
tong_tu += so_tu
|
|
73
|
+
tong_ky_tu += so_ky_tu
|
|
74
|
+
da_dem += 1
|
|
75
|
+
if da_dem > 1:
|
|
76
|
+
print(f"tổng cộng ({da_dem} file): {tong_dong} dòng, {tong_tu} từ, {tong_ky_tu} ký tự")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def cmd_tim(args) -> None:
|
|
80
|
+
"""Tìm file/thư mục theo tên, không phân biệt hoa thường."""
|
|
81
|
+
if args.trong:
|
|
82
|
+
root = Path(args.trong).expanduser().resolve()
|
|
83
|
+
if not root.is_dir():
|
|
84
|
+
raise SystemExit(f"tim: không tìm thấy thư mục '{args.trong}'")
|
|
85
|
+
else:
|
|
86
|
+
root = Path.cwd()
|
|
87
|
+
ket_qua = []
|
|
88
|
+
for p in sorted(root.rglob("*")):
|
|
89
|
+
if args.ten.lower() in p.name.lower():
|
|
90
|
+
ket_qua.append(p)
|
|
91
|
+
if len(ket_qua) >= args.gioi_han:
|
|
92
|
+
break
|
|
93
|
+
for p in ket_qua:
|
|
94
|
+
print(p)
|
|
95
|
+
dau_cong = "+" if len(ket_qua) >= args.gioi_han else ""
|
|
96
|
+
print(f"\ntìm thấy {len(ket_qua)}{dau_cong} kết quả khớp '{args.ten}' trong {root}")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def cmd_kich_thuoc(args) -> None:
|
|
100
|
+
"""Xem dung lượng thư mục, nhóm theo loại file."""
|
|
101
|
+
root = Path(args.thu_muc).expanduser().resolve()
|
|
102
|
+
if not root.is_dir():
|
|
103
|
+
raise SystemExit(f"kich-thuoc: không tìm thấy thư mục '{args.thu_muc}'")
|
|
104
|
+
thong_ke: dict = {}
|
|
105
|
+
for p in root.rglob("*"):
|
|
106
|
+
if p.is_file():
|
|
107
|
+
loai = p.suffix.lower() if p.suffix else "(không đuôi)"
|
|
108
|
+
so_luong, dung_luong = thong_ke.get(loai, (0, 0))
|
|
109
|
+
thong_ke[loai] = (so_luong + 1, dung_luong + p.stat().st_size)
|
|
110
|
+
if not thong_ke:
|
|
111
|
+
print(f"{root}: không có file nào")
|
|
112
|
+
return
|
|
113
|
+
print(f"Dung lượng trong {root} (theo loại file):")
|
|
114
|
+
for loai, (so_luong, dung_luong) in sorted(thong_ke.items(), key=lambda kv: -kv[1][1]):
|
|
115
|
+
print(f" {loai:<14} {so_luong:>5} file {doc_dung_luong(dung_luong):>10}")
|
|
116
|
+
tong_file = sum(sl for sl, _ in thong_ke.values())
|
|
117
|
+
tong_dung_luong = sum(dl for _, dl in thong_ke.values())
|
|
118
|
+
print(f" {'TỔNG':<14} {tong_file:>5} file {doc_dung_luong(tong_dung_luong):>10}")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cmd_ngay(args) -> None:
|
|
122
|
+
"""Hôm nay thứ mấy, còn bao nhiêu ngày đến một mốc."""
|
|
123
|
+
hom_nay = datetime.date.today()
|
|
124
|
+
if not args.den:
|
|
125
|
+
print(f"Hôm nay là {THU[hom_nay.weekday()]}, {hom_nay.strftime('%d/%m/%Y')}")
|
|
126
|
+
return
|
|
127
|
+
try:
|
|
128
|
+
moc = datetime.date.fromisoformat(args.den)
|
|
129
|
+
except ValueError:
|
|
130
|
+
raise SystemExit(f"ngay: ngày '{args.den}' không hợp lệ (dạng chuẩn: 2027-02-06)")
|
|
131
|
+
con_lai = (moc - hom_nay).days
|
|
132
|
+
if con_lai > 0:
|
|
133
|
+
print(f"Còn {con_lai} ngày nữa đến {moc.strftime('%d/%m/%Y')}")
|
|
134
|
+
elif con_lai == 0:
|
|
135
|
+
print("Ngày đó chính là hôm nay!")
|
|
136
|
+
else:
|
|
137
|
+
print(f"Ngày {moc.strftime('%d/%m/%Y')} đã qua {abs(con_lai)} ngày")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def cmd_tim_dong(args) -> None:
|
|
141
|
+
"""In các dòng trong file chứa từ khóa, kèm số thứ tự dòng."""
|
|
142
|
+
p = Path(args.file).expanduser()
|
|
143
|
+
if not p.is_file():
|
|
144
|
+
raise SystemExit(f"tim-dong: không tìm thấy file '{args.file}'")
|
|
145
|
+
tu_khoa = args.tu_khoa.lower()
|
|
146
|
+
hits = 0
|
|
147
|
+
for i, dong in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines(), start=1):
|
|
148
|
+
if tu_khoa in dong.lower():
|
|
149
|
+
print(f"{i}: {dong}")
|
|
150
|
+
hits += 1
|
|
151
|
+
print(f"\ntìm thấy {hits} dòng chứa '{args.tu_khoa}' trong {p.name}")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cmd_so_sanh(args) -> None:
|
|
155
|
+
"""So sánh hai file: giống hệt hay khác nhau (theo SHA-256)."""
|
|
156
|
+
p1, p2 = Path(args.file1).expanduser(), Path(args.file2).expanduser()
|
|
157
|
+
for p in (p1, p2):
|
|
158
|
+
if not p.is_file():
|
|
159
|
+
raise SystemExit(f"so-sanh: không tìm thấy file '{p}'")
|
|
160
|
+
h1 = hashlib.sha256(p1.read_bytes()).hexdigest()
|
|
161
|
+
h2 = hashlib.sha256(p2.read_bytes()).hexdigest()
|
|
162
|
+
if h1 == h2:
|
|
163
|
+
print(f"GIỐNG HỆT: {p1.name} và {p2.name} cùng nội dung ({doc_dung_luong(p1.stat().st_size)})")
|
|
164
|
+
else:
|
|
165
|
+
print("KHÁC NHAU:")
|
|
166
|
+
print(f" {p1.name}: {doc_dung_luong(p1.stat().st_size)} — sha256 {h1[:12]}...")
|
|
167
|
+
print(f" {p2.name}: {doc_dung_luong(p2.stat().st_size)} — sha256 {h2[:12]}...")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def cmd_luu(args) -> None:
|
|
171
|
+
"""Sao lưu file vào thư mục đích, tên file kèm dấu thời gian."""
|
|
172
|
+
muc_dich = Path(args.vao).expanduser().resolve() if args.vao else Path.cwd() / "ban-sao-luu"
|
|
173
|
+
muc_dich.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
thoi_gian = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
175
|
+
da_luu = 0
|
|
176
|
+
for ten in args.file:
|
|
177
|
+
p = Path(ten).expanduser()
|
|
178
|
+
if not p.is_file():
|
|
179
|
+
print(f"luu: không tìm thấy file '{ten}'", file=sys.stderr)
|
|
180
|
+
continue
|
|
181
|
+
moi = muc_dich / f"{p.stem}_{thoi_gian}{p.suffix}"
|
|
182
|
+
shutil.copy2(p, moi)
|
|
183
|
+
print(f"đã lưu {p.name} -> {moi}")
|
|
184
|
+
da_luu += 1
|
|
185
|
+
print(f"\n({da_luu} file đã được sao lưu lúc {thoi_gian})")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_don_dep(args) -> None:
|
|
189
|
+
"""Tìm rác trong thư mục. Với --xoa thì dọn thật, không thì chỉ liệt kê."""
|
|
190
|
+
root = Path(args.thu_muc).expanduser().resolve()
|
|
191
|
+
if not root.is_dir():
|
|
192
|
+
raise SystemExit(f"don-dep: không tìm thấy thư mục '{args.thu_muc}'")
|
|
193
|
+
rac = [p for p in sorted(root.rglob("*")) if la_rac(p)]
|
|
194
|
+
if not rac:
|
|
195
|
+
print(f"{root}: sạch bong, không có rác nào")
|
|
196
|
+
return
|
|
197
|
+
for p in rac:
|
|
198
|
+
print(f" {p}{'/' if p.is_dir() else ''}")
|
|
199
|
+
dung_luong = sum(p.stat().st_size for p in rac if p.is_file())
|
|
200
|
+
print(f"\ntìm thấy {len(rac)} mục rác, {doc_dung_luong(dung_luong)}")
|
|
201
|
+
if not args.xoa:
|
|
202
|
+
print("chạy lại với --xoa để dọn thật")
|
|
203
|
+
return
|
|
204
|
+
da_xoa = 0
|
|
205
|
+
for p in rac:
|
|
206
|
+
if not p.exists():
|
|
207
|
+
continue # đã bị dọn theo thư mục cha
|
|
208
|
+
try:
|
|
209
|
+
if p.is_dir():
|
|
210
|
+
shutil.rmtree(p)
|
|
211
|
+
else:
|
|
212
|
+
p.unlink()
|
|
213
|
+
da_xoa += 1
|
|
214
|
+
except OSError as loi:
|
|
215
|
+
print(f"don-dep: không xóa được {p} ({loi})", file=sys.stderr)
|
|
216
|
+
print(f"đã dọn {da_xoa} mục — thư mục giờ sạch hơn")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def cmd_doi_ten(args) -> None:
|
|
220
|
+
"""Đổi tên hàng loạt: thay --cu bằng --moi trong tên file. Mặc định chỉ xem trước."""
|
|
221
|
+
root = Path(args.thu_muc).expanduser().resolve()
|
|
222
|
+
if not root.is_dir():
|
|
223
|
+
raise SystemExit(f"doi-ten: không tìm thấy thư mục '{args.thu_muc}'")
|
|
224
|
+
cap_doi = []
|
|
225
|
+
for p in sorted(root.iterdir()):
|
|
226
|
+
if not p.is_file() or args.cu not in p.name:
|
|
227
|
+
continue
|
|
228
|
+
ten_moi = p.name.replace(args.cu, args.moi)
|
|
229
|
+
if ten_moi != p.name:
|
|
230
|
+
cap_doi.append((p, root / ten_moi))
|
|
231
|
+
if not cap_doi:
|
|
232
|
+
print(f"{root}: không có file nào chứa '{args.cu}' trong tên")
|
|
233
|
+
return
|
|
234
|
+
for cu, moi in cap_doi:
|
|
235
|
+
print(f" {cu.name} -> {moi.name}")
|
|
236
|
+
print(f"\n{len(cap_doi)} file sẽ được đổi tên")
|
|
237
|
+
if not args.thuc_su:
|
|
238
|
+
print("chạy lại với --thuc-su để đổi thật")
|
|
239
|
+
return
|
|
240
|
+
da_doi = 0
|
|
241
|
+
for cu, moi in cap_doi:
|
|
242
|
+
if moi.exists():
|
|
243
|
+
i = 1
|
|
244
|
+
while moi.with_name(f"{moi.stem}_{i}{moi.suffix}").exists():
|
|
245
|
+
i += 1
|
|
246
|
+
moi = moi.with_name(f"{moi.stem}_{i}{moi.suffix}")
|
|
247
|
+
print(f" (tên đã có, né sang {moi.name})")
|
|
248
|
+
cu.rename(moi)
|
|
249
|
+
da_doi += 1
|
|
250
|
+
print(f"đã đổi tên {da_doi} file")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def main(argv=None) -> int:
|
|
254
|
+
p = argparse.ArgumentParser(
|
|
255
|
+
prog="vietlen",
|
|
256
|
+
description="Bộ lệnh dòng lệnh tiếng Việt — đọc tên là hiểu nó làm gì.",
|
|
257
|
+
)
|
|
258
|
+
sub = p.add_subparsers(dest="lenh", required=True)
|
|
259
|
+
|
|
260
|
+
q = sub.add_parser("dem", help="đếm dòng, từ, ký tự của file")
|
|
261
|
+
q.add_argument("file", nargs="+", help="file cần đếm")
|
|
262
|
+
q.set_defaults(func=cmd_dem)
|
|
263
|
+
|
|
264
|
+
t = sub.add_parser("tim", help="tìm file/thư mục theo tên")
|
|
265
|
+
t.add_argument("ten", help="đoạn tên cần tìm (không phân biệt hoa thường)")
|
|
266
|
+
t.add_argument("--trong", help="thư mục để tìm (mặc định: thư mục hiện tại)")
|
|
267
|
+
t.add_argument("--gioi-han", type=int, default=50, help="giới hạn số kết quả (mặc định: 50)")
|
|
268
|
+
t.set_defaults(func=cmd_tim)
|
|
269
|
+
|
|
270
|
+
k = sub.add_parser("kich-thuoc", help="xem dung lượng thư mục theo loại file")
|
|
271
|
+
k.add_argument("thu_muc", help="thư mục cần xem")
|
|
272
|
+
k.set_defaults(func=cmd_kich_thuoc)
|
|
273
|
+
|
|
274
|
+
n = sub.add_parser("ngay", help="hôm nay thứ mấy, còn bao nhiêu ngày đến mốc")
|
|
275
|
+
n.add_argument("--den", help="ngày cần đếm ngược tới (dạng 2027-02-06)")
|
|
276
|
+
n.set_defaults(func=cmd_ngay)
|
|
277
|
+
|
|
278
|
+
t2 = sub.add_parser("tim-dong", help="in các dòng chứa từ khóa, kèm số dòng")
|
|
279
|
+
t2.add_argument("tu_khoa", help="từ khóa cần tìm (không phân biệt hoa thường)")
|
|
280
|
+
t2.add_argument("file", help="file cần tìm trong đó")
|
|
281
|
+
t2.set_defaults(func=cmd_tim_dong)
|
|
282
|
+
|
|
283
|
+
s = sub.add_parser("so-sanh", help="so sánh hai file theo nội dung (SHA-256)")
|
|
284
|
+
s.add_argument("file1")
|
|
285
|
+
s.add_argument("file2")
|
|
286
|
+
s.set_defaults(func=cmd_so_sanh)
|
|
287
|
+
|
|
288
|
+
l = sub.add_parser("luu", help="sao lưu file, tên kèm dấu thời gian")
|
|
289
|
+
l.add_argument("file", nargs="+", help="file cần sao lưu")
|
|
290
|
+
l.add_argument("--vao", help="thư mục đích (mặc định: ban-sao-luu/)")
|
|
291
|
+
l.set_defaults(func=cmd_luu)
|
|
292
|
+
|
|
293
|
+
d2 = sub.add_parser("don-dep", help="tìm rác trong thư mục, --xoa để dọn thật")
|
|
294
|
+
d2.add_argument("thu_muc", help="thư mục cần dọn")
|
|
295
|
+
d2.add_argument("--xoa", action="store_true", help="xóa thật (mặc định chỉ liệt kê)")
|
|
296
|
+
d2.set_defaults(func=cmd_don_dep)
|
|
297
|
+
|
|
298
|
+
n2 = sub.add_parser("doi-ten", help="đổi tên hàng loạt theo cặp --cu/--moi")
|
|
299
|
+
n2.add_argument("thu_muc", help="thư mục chứa file cần đổi tên")
|
|
300
|
+
n2.add_argument("--cu", required=True, help="đoạn tên cần thay trong tên file")
|
|
301
|
+
n2.add_argument("--moi", default="", help="đoạn tên thay vào (mặc định: xóa hẳn)")
|
|
302
|
+
n2.add_argument("--thuc-su", action="store_true", help="đổi thật (mặc định chỉ xem trước)")
|
|
303
|
+
n2.set_defaults(func=cmd_doi_ten)
|
|
304
|
+
|
|
305
|
+
args = p.parse_args(argv)
|
|
306
|
+
args.func(args)
|
|
307
|
+
return 0
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
sys.exit(main())
|