forked from cmccabe/linkulator2
90 lines
2.0 KiB
Python
90 lines
2.0 KiB
Python
"""handle the linkulator post process"""
|
|
|
|
import getpass
|
|
import os
|
|
import readline
|
|
import sys
|
|
import time
|
|
|
|
from config import CONFIG as config
|
|
|
|
USERNAME = getpass.getuser()
|
|
|
|
|
|
class Link:
|
|
"""represents a single link's data"""
|
|
|
|
url: str
|
|
category: str
|
|
title: str
|
|
timestamp: str
|
|
|
|
|
|
def rlinput(prompt, prefill="") -> str:
|
|
"""Creates an input prompt with a prefilled entry, using the specified
|
|
prompt text and prefill text"""
|
|
readline.set_startup_hook(lambda: readline.insert_text(prefill))
|
|
try:
|
|
return input(prompt)
|
|
finally:
|
|
readline.set_startup_hook()
|
|
|
|
|
|
def is_valid(entry: str) -> bool:
|
|
"""Determine validity of an input string
|
|
|
|
>>> is_valid("valid")
|
|
True
|
|
>>> is_valid("Not|valid")
|
|
False
|
|
"""
|
|
if "|" in entry:
|
|
return False
|
|
return True
|
|
|
|
|
|
def get_input(item: str, prefill) -> str:
|
|
"""Get user input with the specified prompt, validate and return it or exit"""
|
|
while True:
|
|
i: str = rlinput(item + ": ", prefill)
|
|
if i == "":
|
|
sys.exit(0)
|
|
if is_valid(i):
|
|
return i
|
|
|
|
print('Pipes, "|", are illegal characters in Linkulator. Please try again.')
|
|
|
|
|
|
def save_link(link) -> None:
|
|
"""Saves the specified link data to the user's data file"""
|
|
if os.path.exists(config.my_datafile):
|
|
append_write = "a" # append if already exists
|
|
else:
|
|
append_write = "w+" # make a new file if not
|
|
with open(config.my_datafile, append_write) as file:
|
|
file.write(
|
|
link.timestamp
|
|
+ "||"
|
|
+ link.category
|
|
+ "|"
|
|
+ link.url
|
|
+ "|"
|
|
+ link.title
|
|
+ "\n"
|
|
)
|
|
print("Link added!")
|
|
|
|
|
|
def post_link(prefill: str = "") -> None:
|
|
"""High-level """
|
|
print("Enter link information here. Leaving any field blank aborts post.")
|
|
|
|
link = Link()
|
|
|
|
link.url = get_input("URL", prefill)
|
|
link.category = get_input("Category", "")
|
|
link.title = get_input("Title", "")
|
|
link.timestamp = str(time.time())
|
|
|
|
save_link(link)
|