Skip to content

Commit

Permalink
make ipse implicitly access ~/.ipse
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattscarpenter committed Oct 30, 2024
1 parent 6200a94 commit 22a62ca
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions ipse
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,38 @@
import sys
import os
import random
from typing import TextIO
from typing import TextIO, NoReturn

if len(sys.argv) < 2 and sys.stdin.isatty():
print(f"Usage: {sys.argv[0]} ipse-files-and-or-dirs-required-if-no-pipe-to-stdin...")
print("Reads files (stdin counts as a file if the script is used in a pipeline), splits on \\n\\n, replaces backslash-only lines with blank lines, and picks one part randomly. If directories are passed in as arguments, all files (and directories) within those dirs will be recursively included.")
def help() -> NoReturn:
print(f"Usage: {sys.argv[0]} [ipse-files-and/or-dirs...]")
print(""" Ipse reads files, splits on \\n\\n, replaces backslash-only lines with blank lines, and picks one part randomly.
Stdin counts as a file if the script is used in a pipeline.
If no arguments are given (and the script is being used interactively (not in a pipeline)), ~/.ipse is used implicitly.
If directories are passed in as arguments, all files (and directories) within those dirs will be recursively included.""")
sys.exit(22)

if any(x in sys.argv for x in ["-help", "--help", "-h", "--h"]):
help()

def process_file(filelike: TextIO):
return [ part.replace('\n\\\n', '\n\n') for part in filelike.read().split('\n\n') ]

parts: list[str] = []
if not sys.stdin.isatty():
parts.extend(process_file(sys.stdin))
args: list[str] = sys.argv[1:]
if sys.stdin.isatty() and len(args) == 0:
args = ["~/.ipse"]
#print(args)
for arg in args:
arg = os.path.expanduser(arg)
if os.path.isdir(arg):
args += [ os.path.join(arg, entry) for entry in os.listdir(arg) ]
else:
with open(arg) as f:
parts.extend(process_file(f))

if len(parts) == 0:
help()

print(random.choice(parts))

0 comments on commit 22a62ca

Please sign in to comment.