97 lines
1.9 KiB
Python
Executable file
97 lines
1.9 KiB
Python
Executable file
#!/usr/bin/python3
|
|
import sys
|
|
import os
|
|
import argparse
|
|
import time
|
|
import tempfile
|
|
|
|
def delete_all(d):
|
|
files = list_all(d)
|
|
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)
|
|
print(f"Removing: {f}")
|
|
print("Done")
|
|
|
|
def list_all(d):
|
|
if not os.path.exists(d):
|
|
print("Skratch path doesn't exist")
|
|
return []
|
|
files = os.listdir(d)
|
|
if files == []:
|
|
print("No skratch files exist")
|
|
else:
|
|
for file in files:
|
|
print(file)
|
|
return files
|
|
|
|
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 run(editor, sk_path, filename=None, f_suffix=""):
|
|
if not filename:
|
|
t = time.localtime()
|
|
filename = f"skratch-{t.tm_year}-{t.tm_mon}-{t.tm_mday}-"
|
|
fd, fp = tempfile.mkstemp(prefix=filename, dir=sk_path, suffix=f_suffix)
|
|
os.close(fd)
|
|
else:
|
|
fp = os.path.join(sk_path, filename)
|
|
if fp != None:
|
|
os.execvp(editor, [editor,fp])
|
|
|
|
def main():
|
|
home_path = os.getenv("HOME")
|
|
sk_path = os.path.join(home_path, ".skratch")
|
|
os.makedirs(sk_path, exist_ok=True)
|
|
|
|
parser = argparse.ArgumentParser(
|
|
prog='skratch',
|
|
description='Creates a temp file and opens it in an editor')
|
|
|
|
group = parser.add_mutually_exclusive_group()
|
|
|
|
group.add_argument(
|
|
"filename",
|
|
nargs="?",
|
|
help="open file in ~/.skratch",
|
|
default=None)
|
|
|
|
group.add_argument(
|
|
"-c",
|
|
help="delete all files",
|
|
action="store_true")
|
|
|
|
group.add_argument(
|
|
"-l",
|
|
help="list files",
|
|
action="store_true")
|
|
|
|
group.add_argument(
|
|
"-s",
|
|
help="add suffix",
|
|
action="store")
|
|
|
|
parser.add_argument(
|
|
"-v",
|
|
help="visual editor",
|
|
action="store_true")
|
|
|
|
args = parser.parse_args()
|
|
|
|
editor = get_editor(args.v)
|
|
if args.c: delete_all(sk_path)
|
|
elif args.l: list_all(sk_path)
|
|
else: run(editor,sk_path, args.filename, args.s)
|
|
|
|
main()
|