;;;; main.lisp -- oneliners.cli entrypoint (defpackage oneliners.cli (:use :cl) (:local-nicknames (#:api #:oneliners.api-client) (#:a #:alexandria))) (in-package :oneliners.cli) ;;; CONFIG AND RESULTS FILE LOCATIONS (defvar *config* nil "A configuration plist") (defun make-config (&key host api-token editor) (append (when host (list :host host)) (when api-token (list :api-token api-token)) (when editor (list :editor editor)))) (defun valid-config-p (config) (and (listp config) (evenp (length config)) (stringp (getf config :host)) t)) (defun write-default-config-to-disk () (let ((conf-file (config-file))) (ensure-directories-exist conf-file) (with-open-file (out conf-file :direction :output) (print (make-config :host "http://localhost:8888") out)))) (defun write-config-to-disk () (let ((conf-file (config-file))) (ensure-directories-exist conf-file) (with-open-file (out conf-file :direction :output :if-exists :supersede) (print *config* out)))) (defun fetch-config-from-disk () (let ((conf (uiop:with-safe-io-syntax () (uiop:read-file-form (config-file))))) (assert (valid-config-p conf) () "Invalid configuration file") (setf *config* conf))) (defun ensure-config () (unless (uiop:file-exists-p (config-file)) (write-default-config-to-disk)) (fetch-config-from-disk)) (defun host () (getf *config* :host)) (defun api-token () (getf *config* :api-token)) (defun (setf api-token) (newval) (setf (getf *config* :api-token) newval)) (defun get-shell () (getf *config* :shell)) (defun make-temp-file-name () (namestring (merge-pathnames (format nil "~a" (gensym "oneliners")) (uiop:temporary-directory)))) (defun string-from-editor () (let ((filename (make-temp-file-name))) (unwind-protect (magic-ed:magic-ed filename :eval nil :output :string) (uiop:delete-file-if-exists filename)))) (defun config-file () (merge-pathnames ".config/oneliners.config" (user-homedir-pathname))) (defun last-search-file () (merge-pathnames ".last_oneliners_search" (user-homedir-pathname))) (defun fetch-nth-oneliner (n) "Returns nil if there is no nth oneliner from the search history." (when (uiop:file-exists-p (last-search-file)) (nth n (uiop:read-file-form (last-search-file))))) (defun executable-on-system-p (name) "A hack that heuristically determins whether or not an executable with the provided name is on the system. It is not perfect. It consults the environment PATH, and looks for the command in any of the directories that appear in the value of that variable." #+unix (loop for path in (str:split ":" (uiop:getenv "PATH")) for directory = (cons :absolute (cdr (str:split "/" path))) thereis (uiop:file-exists-p (make-pathname :name name :directory directory)))) (defun tags-from-oneliner (oneliner) (remove-if-not #'executable-on-system-p (ppcre:split " +" oneliner))) (defun prompt (prompt &key (out-stream *standard-output*) (in-stream *standard-input*)) (princ prompt out-stream) (force-output out-stream) (read-line in-stream)) (defun cached-result (&optional n) (when (uiop:file-exists-p (last-search-file)) (let ((contents (with-open-file (input (last-search-file)) (read input)))) (if n (nth n contents) contents)))) (defmacro with-cached-result ((olvar n) &body body) (a:with-gensyms (nvar) `(let ((,nvar ,n)) (assert (plusp ,nvar) () "Item number must be 1 or greater") (a:if-let (,olvar (cached-result (1- ,nvar))) (progn ,@body) (format t "The last search was shorter than ~a" ,nvar))))) ;;; API REQUEST FUNCTIONS (defun flag-item (item-number) (with-cached-result (ol item-number) (ensure-config) (api:request-with (:host (host)) (api:put--oneliner-entry-flag (getf ol :id) :token (api-token) :value "true")))) (defun unflag-item (item-number) (with-cached-result (ol item-number) (ensure-config) (api:request-with (:host (host)) (api:put--oneliner-entry-flag (getf ol :id) :token (api-token) :value "false")))) (defun lock-item (item-number) (with-cached-result (ol item-number) (ensure-config) (api:request-with (:host (host)) (api:put--oneliner-oneliner-locked (getf ol :id) :token (api-token) :value "true")))) (defun unlock-item (item-number) (with-cached-result (ol item-number) (ensure-config) (api:request-with (:host (host)) (api:put--oneliner-oneliner-locked (getf ol :id) :token (api-token) :value "false")))) (defun collect-positional-arguments (oneliner) (remove-duplicates (sort (ppcre:all-matches-as-strings "\\$[1-9][0-9]*" oneliner) #'string<) :test #'equal)) (defun collect-named-arguments (oneliner) (remove-duplicates (ppcre:all-matches-as-strings "\\$[a-zA-Z_][a-zA-Z0-9_]*" oneliner) :test #'equal)) (defun handle-run-oneliner (ol &optional clip) (if clip (progn (trivial-clipboard:text ol) (format t "Copied oneliner to clipboard~%")) (progn (ensure-config) (format t "Attempting to run: ~%") (princ ol) (terpri) (run-with-shell ol :shell-name (or (get-shell) "bash"))))) (defun run-item (item-number args &optional force-clip) (with-cached-result (ol item-number) (let* ((oneliner (getf ol :oneliner)) (runstyle (getf ol :runstyle)) (pos-args (collect-positional-arguments oneliner)) (named-args (collect-named-arguments oneliner))) (when (or (not (getf ol :isflagged)) (y-or-n-p "This oneliner is flagged. Are you sure you want to run it?")) ;; substitute positional args (loop for param in pos-args for arg in args do (setf oneliner (str:replace-all param arg oneliner))) ;; substitute named args (setf args (mapcar (lambda (s) (str:split "=" s)) (nthcdr (length pos-args) args))) (loop for var in named-args for bound = (assoc (subseq var 1) args :test #'equal) when bound do (setf oneliner (str:replace-all var (second bound) oneliner))) (handle-run-oneliner oneliner (or force-clip (equalp runstyle "manual"))))))) (defun add-new-oneliner () (ensure-config) (assert (api-token) () "Cannot add a oneliner without an api token.") (let* ((oneliner (prompt "Oneliner: ")) (init-tags (tags-from-oneliner oneliner)) (brief (prompt "Brief Description: ")) (tags (append init-tags (ppcre:split " +" (prompt (format nil "Tags in addition to ~{~a ~} ?" init-tags))))) (explanation (when (y-or-n-p "Provide an explanation?") (string-from-editor))) (runstyle (if (y-or-n-p "Does this oneliner invoke a GUI, a TUI, or will it require user input?") "MANUAL" "AUTO"))) (api:request-with (:host (host) :body (jonathan:to-json (list :oneliner oneliner :tags tags :brief brief :explanation explanation :runstyle runstyle)) :content-type "application/json") (api:post--oneliner :token (api-token)) (format t "Added~%")))) (defun request-invite-code () (ensure-config) (api:request-with (:host (host)) (let ((invite (jonathan:parse (api:post--invite :token (api-token))))) (format t "Invite Code: ~a~%Expires: ~a~%" (getf invite :code) (getf invite :expires))))) (defun login (user pass) (ensure-config) (a:when-let (response (jonathan:parse (api:request-with (:host (host) :body (jonathan:to-json (list :password pass :handle user)) :content-type "application/json") (api:post--access)))) (setf (api-token) (getf response :token)) (write-config-to-disk) (format t "Access token written to ~a~%" (config-file)))) (defun redeem-invite (token name pass) (ensure-config ) (api:request-with (:host (host) :body (jonathan:to-json (list :handle name :password1 pass :password2 pass)) :content-type "application/json") (api:post--invite-redeem-code token) (format t "Account made for ~a. You may log in now~%" name))) (defun revoke-access () (ensure-config) (api:request-with (:host (host)) (api:delete--access-access (api-token) :token (api-token)))) (defun cache-search-results-to-last-search-file (results) (with-open-file (output (last-search-file) :direction :output :if-exists :supersede) (print results output))) (defun print-oneliner-result-for-user (number oneliner) (dotimes (n 80) (princ #\_)) (terpri) (format t "~3a~a~a~a ~a" number (if (getf oneliner :isflagged) "⚠" " ") (if (getf oneliner :islocked) "🔒" " ") (if (equalp "manual" (getf oneliner :runstyle)) "📋" " ") (getf oneliner :brief)) (format t "~% by: ~12a tags: ~{~a~^ ~}" (getf oneliner :createdby) (getf oneliner :tags)) (format t "~%~% ~a~%~%" (getf oneliner :oneliner))) (defun search-for-oneliners (terms limit not-flagged-p) (assert (loop for term in terms never (find #\, term) )) (ensure-config) (let ((response (api:request-with (:host (host)) (api:get--oneliners :tags (str:join "," terms) :limit limit :notflagged (if not-flagged-p "true" "false"))))) (handler-case (a:when-let (oneliners (getf (jonathan:parse response) :oneliners)) (cache-search-results-to-last-search-file (loop for number from 1 for oneliner in oneliners collect (list* :result-number number oneliner) do (print-oneliner-result-for-user number oneliner))) (format t "Run a command with: ol NUMBER [ARGS...]~%"))))) ;;; RUNNING COMMANDS (defun parent-process-name () "Prints the name of the parent process of the current process." (let ((ppidfile (format nil "/proc/~a/status" (osicat-posix:getppid)))) (first (last (ppcre:split "\\s" (with-open-file (input ppidfile) (read-line input))))))) (defmacro wait-until ((&key (timeout 1) (poll-every 0.01)) &body check) "Run CHECK every POLL-EVERY seconds until either TIMEOUT seconds have passed or CHECK returns non-nil." (let ((clockvar (gensym)) (var (gensym))) `(loop for ,clockvar from 0 by ,poll-every to ,timeout for ,var = (progn ,@check) when ,var return ,var do (sleep ,poll-every)))) (defun run-with-shell (command &key (shell-name (parent-process-name)) (await-output-p 0.8) (output-stream *standard-output*)) "run COMMAND, a string, in a fresh shell environment, initialized with SHELL-NAME. The output from the command read line by line and is printed to OUTPUT-STREAM. " (let ((shell (uiop:launch-program shell-name :input :stream :output :stream))) (symbol-macrolet ((shell-input (uiop:process-info-input shell)) (shell-output (uiop:process-info-output shell))) (write-line command shell-input) (finish-output shell-input) (when await-output-p (wait-until (:timeout await-output-p :poll-every 0.005) (listen shell-output)) (loop while (listen shell-output) do (princ (read-line shell-output) output-stream) (terpri output-stream))))))