skratch/skratch.py

98 lines
1.9 KiB
Python
Raw Normal View History

2026-03-04 23:09:49 -08:00
#!/usr/bin/python3
import sys
import os
import argparse
2026-03-05 02:00:39 -08:00
import time
import tempfile
2026-03-05 14:38:59 -08:00
2026-03-04 23:09:49 -08:00
def delete_all(d):
2026-03-05 01:30:21 -08:00
files = list_all(d)
2026-03-05 01:32:04 -08:00
if not files:
return
x = input("Delete the above files? y/N ")
if x.lower() != 'y':
return
for file in files:
f = os.path.join(d,file)
os.remove(f)
2026-03-05 14:30:31 -08:00
print(f"Removing: {f}")
2026-03-05 01:32:04 -08:00
print("Done")
2026-03-04 23:09:49 -08:00
def list_all(d):
if not os.path.exists(d):
2026-03-05 00:52:46 -08:00
print("Skratch path doesn't exist")
return []
2026-03-05 01:07:55 -08:00
files = os.listdir(d)
if files == []:
2026-03-05 00:52:46 -08:00
print("No skratch files exist")
2026-03-04 23:09:49 -08:00
else:
2026-03-05 01:07:55 -08:00
for file in files:
2026-03-04 23:09:49 -08:00
print(file)
2026-03-05 01:30:21 -08:00
return files
2026-03-04 23:09:49 -08:00
def get_editor(use_v):
v = os.getenv("VISUAL")
e = os.getenv("EDITOR")
if (not v and not e):
e = "nano"
if use_v and v:
return v
return e
2026-03-05 14:55:45 -08:00
def run(editor, sk_path, filename=None, f_suffix=""):
2026-03-04 23:09:49 -08:00
if not filename:
2026-03-05 02:00:39 -08:00
t = time.localtime()
filename = f"skratch-{t.tm_year}-{t.tm_mon}-{t.tm_mday}-"
2026-03-05 14:55:45 -08:00
fd, fp = tempfile.mkstemp(prefix=filename, dir=sk_path, suffix=f_suffix)
os.close(fd)
2026-03-04 23:09:49 -08:00
else:
2026-03-05 00:24:40 -08:00
fp = os.path.join(sk_path, filename)
2026-03-04 23:09:49 -08:00
if fp != None:
os.execvp(editor, [editor,fp])
def main():
home_path = os.getenv("HOME")
2026-03-05 00:24:40 -08:00
sk_path = os.path.join(home_path, ".skratch")
2026-03-05 14:38:59 -08:00
os.makedirs(sk_path, exist_ok=True)
2026-03-04 23:09:49 -08:00
parser = argparse.ArgumentParser(
prog='skratch',
2026-03-05 14:30:31 -08:00
description='Creates a temp file and opens it in an editor')
2026-03-05 14:28:22 -08:00
2026-03-04 23:09:49 -08:00
group = parser.add_mutually_exclusive_group()
2026-03-05 14:28:22 -08:00
group.add_argument(
"filename",
nargs="?",
help="open file in ~/.skratch",
default=None)
2026-03-04 23:09:49 -08:00
group.add_argument(
"-c",
help="delete all files",
action="store_true")
group.add_argument(
"-l",
help="list files",
action="store_true")
2026-03-05 14:55:45 -08:00
group.add_argument(
"-s",
help="add suffix",
action="store")
2026-03-04 23:09:49 -08:00
parser.add_argument(
"-v",
help="visual editor",
action="store_true")
args = parser.parse_args()
editor = get_editor(args.v)
2026-03-05 14:28:22 -08:00
if args.c: delete_all(sk_path)
2026-03-04 23:09:49 -08:00
elif args.l: list_all(sk_path)
2026-03-05 14:55:45 -08:00
else: run(editor,sk_path, args.filename, args.s)
2026-03-04 23:09:49 -08:00
main()