skratch/skratch.py

107 lines
2.1 KiB
Python
Raw Normal View History

2026-03-04 23:09:49 -08:00
#!/usr/bin/python3
import sys
import os
import random
import string
import argparse
def make_dir(d):
if not os.path.exists(d):
os.mkdir(d)
def delete_all(d):
if not os.path.exists(d):
print("Nothing to delete")
else:
2026-03-05 00:49:05 -08:00
list_all(d)
x = input("Delete the above files? y/N ")
if x.lower() == 'y':
for file in os.listdir(d):
f = os.path.join(d,file)
os.remove(f)
print(f"removing: {f}")
print("Done")
2026-03-04 23:09:49 -08:00
def list_all(d):
if not os.path.exists(d):
print("Nothing to list")
else:
for file in os.listdir(d):
print(file)
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
def mkstemp(fp):
if fp[-6:] == "XXXXXX":
for x in range(0,1000):
r = ''.join(random.choices(string.ascii_letters, k=6))
fp = fp[:-6] + r
if not os.path.exists(fp):
return fp
print("Error: Could not create new file, try running skratch -c and try again")
return None
else:
print(f'Error: mkstemp got filepath: {fp}')
return None
def run(editor, sk_path, filename=None):
if not filename:
filename = "skratch-XXXXXX"
2026-03-05 00:24:40 -08:00
fp = os.path.join(sk_path, filename)
2026-03-04 23:09:49 -08:00
fp = mkstemp(fp)
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-04 23:09:49 -08:00
make_dir(sk_path)
parser = argparse.ArgumentParser(
prog='skratch',
description='Creates a temp file and opens it in an editor',
epilog='Text at the bottom of help')
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-c",
help="delete all files",
action="store_true")
group.add_argument(
"-l",
help="list files",
action="store_true")
group.add_argument(
"-o",
help="open file",
action="store")
parser.add_argument(
"-v",
help="visual editor",
action="store_true")
args = parser.parse_args()
filename = "skratch-XXXXXX"
editor = get_editor(args.v)
2026-03-05 00:24:40 -08:00
if args.o: run(editor,sk_path,args.o)
2026-03-04 23:09:49 -08:00
elif args.c: delete_all(sk_path)
elif args.l: list_all(sk_path)
2026-03-05 00:24:40 -08:00
else: run(editor,sk_path)
2026-03-04 23:09:49 -08:00
main()