;;;; Lisplings: small exercises to get you used to reading and ;;;; writing Common Lisp code. ;;;; ;;;; core.lisp: exercise catalogue, progress state, and all commands. (defpackage #:lisplings (:use #:common-lisp) (:export #:main)) (in-package #:lisplings) ;;; --------------------------------------------------------------------- ;;; Globals and pathnames (defparameter *sbcl-bin* (or (sb-ext:posix-getenv "LISPLINGS_SBCL") (ignore-errors (namestring (truename sb-ext:*runtime-pathname*))) "sbcl")) (defparameter *source-root* ;; The lisplings source checkout: the parent directory of src/. (make-pathname :directory (butlast (pathname-directory (truename *load-truename*))))) (defparameter *project* nil) ; directory to operate on (defparameter *info* nil) ; parsed info.sexp (defparameter *exercises* nil) ; list of exercise structs (defparameter *state* nil) ; (:done ("name" ...) :current "name") (defstruct exercise name dir hint done path solution-path) (defun info-field (key) (second (assoc key *info*))) (defun cwd-directory () (let ((cwd (ignore-errors (sb-posix:getcwd)))) (if (and cwd (plusp (length cwd))) (pathname (if (char= #\/ (char cwd (1- (length cwd)))) cwd (concatenate 'string cwd "/"))) *default-pathname-defaults*))) (defun project-p (dir) (and dir (probe-file (merge-pathnames "info.sexp" dir)) (probe-file (merge-pathnames "exercises/" dir)) dir)) (defun detect-project () (or (project-p (cwd-directory)) (project-p *source-root*) (error "This is not a lisplings project.~%Run lisplings inside a lisplings checkout, or create one first:~% lisplings init my-lisplings~%then start it from inside that directory."))) (defun setup () (setf *project* (detect-project) *info* (with-open-file (in (merge-pathnames "info.sexp" *project*)) (read in)) *state* (load-state) *exercises* (make-exercises)) (unless (plusp (length *exercises*)) (error "The exercise catalogue (info.sexp) is empty."))) (defun make-exercises () (mapcar (lambda (spec) (let ((name (getf spec :name)) (dir (getf spec :dir))) (make-exercise :name name :dir dir :hint (getf spec :hint) :done (and (member name (getf *state* :done) :test #'string=) t) :path (merge-pathnames (format nil "exercises/~a/~a.lisp" dir name) *project*) :solution-path (merge-pathnames (format nil "solutions/~a/~a.lisp" dir name) *project*)))) (info-field :exercises))) (defun find-exercise (name) (or (find name *exercises* :key #'exercise-name :test #'string=) (error "No exercise named ~s. Try `lisplings list'." name))) ;;; --------------------------------------------------------------------- ;;; Progress state (defun state-path () (merge-pathnames ".lisplings-state.sexp" *project*)) (defun load-state () (or (ignore-errors (with-open-file (in (state-path)) (let ((state (read in))) (when (listp state) state)))) '(:done nil :current nil))) (defun save-state () (with-open-file (out (state-path) :direction :output :if-exists :supersede :if-does-not-exist :create) (with-standard-io-syntax (format out "~s~%" *state*)))) (defun mark-done (ex) (setf (exercise-done ex) t) (pushnew (exercise-name ex) (getf *state* :done) :test #'string=) (save-state)) (defun unmark-done (ex) (setf (exercise-done ex) nil) (setf (getf *state* :done) (remove (exercise-name ex) (getf *state* :done) :test #'string=)) (save-state)) (defun set-current-name (name) (setf (getf *state* :current) name) (save-state)) ;;; --------------------------------------------------------------------- ;;; Pristine copies, so `reset' can undo any experiment (defun copy-file (from to) (ensure-directories-exist to) (with-open-file (in from :element-type '(unsigned-byte 8)) (with-open-file (out to :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (loop for n = (read-sequence buffer in) until (zerop n) do (write-sequence buffer out :end n)))))) (defun orig-root () (merge-pathnames ".lisplings-orig/" *project*)) (defun orig-path (ex) (merge-pathnames (format nil "~a/~a.lisp" (exercise-dir ex) (exercise-name ex)) (orig-root))) (defun ensure-orig-snapshot () "Snapshot the pristine exercises the first time lisplings runs here, so `reset' can restore them. Start lisplings before editing anything!" (let ((orig (orig-root))) (unless (probe-file orig) (dolist (ex *exercises*) (copy-file (exercise-path ex) (orig-path ex))) (format *error-output* "~&Snapshotted pristine exercises to .lisplings-orig/ (this is what `reset' restores).~%")))) ;;; --------------------------------------------------------------------- ;;; Terminal helpers (defparameter *use-color* (and (not (or (sb-ext:posix-getenv "NO_COLOR") (sb-ext:posix-getenv "LISPLINGS_NO_COLOR"))) (sb-ext:posix-getenv "TERM") (not (string= "dumb" (sb-ext:posix-getenv "TERM"))))) (defun ansi (code string) (if *use-color* (format nil "~c[~dm~a~c[0m" #\escape code string #\escape) string)) (defun red (s) (ansi 31 s)) (defun green (s) (ansi 32 s)) (defun yellow (s) (ansi 33 s)) (defun bold (s) (ansi 1 s)) (defun stdout-is-tty-p () (ignore-errors (plusp (sb-unix:unix-isatty 1)))) (defun clear-screen () (when (stdout-is-tty-p) (format t "~c[H~c[2J~c[3J" #\escape #\escape #\escape) (finish-output))) (defun progress-bar () (let* ((total (length *exercises*)) (done (count-if #'exercise-done *exercises*)) (width 28) (filled (if (zerop total) 0 (floor (* width done) total)))) (format nil "[~a~a] ~d% (~d/~d done)" (make-string filled :initial-element #\#) (make-string (- width filled) :initial-element #\-) (floor (* 100 done) (max 1 total)) done total))) ;;; --------------------------------------------------------------------- ;;; Running exercises (defun exercise-mtime (ex) (ignore-errors (file-write-date (exercise-path ex)))) (defun run-exercise-file (path &key (timeout 60)) "Run the exercise at PATH in a fresh SBCL subprocess. Returns (values output-string exit-code timed-out-p)." (let* ((runner (merge-pathnames "src/exercise-runner.lisp" *source-root*)) (proc (sb-ext:run-program *sbcl-bin* (list "--noinform" "--no-sysinit" "--no-userinit" "--disable-debugger" "--script" (namestring runner) (namestring path)) :wait nil :input nil :search t :output :stream :error :output)) (timed-out nil) (killer (sb-thread:make-thread (lambda () (do ((i 0 (+ i 1))) ((or (>= i (* 10 (max 1 timeout))) (not (eq :running (sb-ext:process-status proc))))) (sleep 0.1)) (when (eq :running (sb-ext:process-status proc)) (setf timed-out t) (ignore-errors (sb-ext:process-kill proc 9)))) :name "lisplings-killer")) (output (with-output-to-string (out) (let ((stream (sb-ext:process-output proc))) (handler-case (loop for line = (read-line stream nil :eof) until (eq line :eof) do (write-line line out)) (error () nil)))))) (sb-ext:process-wait proc) (sb-thread:join-thread killer) (values output (sb-ext:process-exit-code proc) timed-out))) (defun run-and-show (ex) (clear-screen) (format t "~&~a~%" (bold (format nil "Lisplings · ~a" (exercise-name ex)))) (format t "~&Editing: ~a~%~%" (namestring (exercise-path ex))) (finish-output) (multiple-value-bind (output code timed-out-p) (run-exercise-file (exercise-path ex)) (format t "~a~%" output) (cond (timed-out-p (format t "~&~a~%~%" (red "Timed out after 60 seconds. Infinite loop? Check the base case, or type r to rerun."))) ((zerop code) (mark-done ex) (format t "~&~a~%~%" (green "Solved! Press n for the next exercise."))) (t (format t "~&~a~%~%" (red "Keep working; the checks rerun every time you save.")))) (format t "~&~a~%~%" (progress-bar)) (format t "n next · h hint · r rerun · l list · q quit~%") (finish-output))) ;;; --------------------------------------------------------------------- ;;; Watch mode (defun show-welcome () (clear-screen) (format t "~a~%~%" (info-field :welcome)) (format t "Press ENTER to start ") (finish-output) (read-line *standard-input* nil nil) (clear-screen)) (defun show-hint (ex) (format t "~&~a~%" (yellow (format nil "Hint for ~a:" (exercise-name ex)))) (format t "~&~a~%~%" (or (exercise-hint ex) "No hint for this one. You're on your own!")) (finish-output)) (defun list-exercises (filter) (format t "~&~a~%" (bold "Lisplings exercises:")) (dolist (ex *exercises*) (when (ecase filter (:all t) (:pending (not (exercise-done ex))) (:done (exercise-done ex))) (format t " ~a ~a~%" (if (exercise-done ex) (green "✓ ") (yellow ". ")) (format nil "~a/~a" (exercise-dir ex) (exercise-name ex))))) (format t "~&~%Pending: ~d of ~d. Progress: ~a~%~%" (count-if (complement #'exercise-done) *exercises*) (length *exercises*) (progress-bar)) (finish-output)) (defun initial-index () (or (let ((name (getf *state* :current))) (and name (position-if (lambda (ex) (string= name (exercise-name ex))) *exercises*))) (position-if (complement #'exercise-done) *exercises*) (1- (length *exercises*)))) (defun next-pending-index (from) (position-if (complement #'exercise-done) *exercises* :start (1+ from))) (defun pop-command (queue lock) (sb-thread:with-mutex (lock) (pop (car queue)))) (defun watch () (ensure-orig-snapshot) (unless (probe-file (state-path)) (show-welcome)) (let* ((queue (list nil)) (lock (sb-thread:make-mutex)) (stdin *standard-input*) (reader (sb-thread:make-thread (lambda () (ignore-errors (loop for line = (read-line stdin nil :eof) until (eq line :eof) do (sb-thread:with-mutex (lock) (setf (car queue) (append (car queue) (list (string-trim " " line)))))))) :name "lisplings-input"))) (declare (ignore reader)) (let ((index (initial-index))) (set-current-name (exercise-name (nth index *exercises*))) (run-and-show (nth index *exercises*)) (block watch-loop (loop (loop for cmd = (pop-command queue lock) while cmd do (cond ((string-equal cmd "n") (let ((current (nth index *exercises*))) (cond ((not (exercise-done current)) (format t "~&~a~%" (yellow "This exercise hasn't passed its checks yet. h for a hint, r to rerun."))) (t (let ((next (or (next-pending-index index) (next-pending-index -1)))) (cond (next (setf index next) (set-current-name (exercise-name (nth index *exercises*))) (run-and-show (nth index *exercises*))) (t (clear-screen) (format t "~&~a~%~%" (green "All exercises done!")) (format t "~a~%~%" (info-field :final)) (format t "r rerun · l list · q quit~%~%")))))))) ((string-equal cmd "h") (show-hint (nth index *exercises*))) ((or (string-equal cmd "r") (string= cmd "")) (run-and-show (nth index *exercises*))) ((string-equal cmd "l") (list-exercises :all)) ((string-equal cmd "q") (return-from watch-loop)) (t (format t "~&Unknown command: ~a~%" cmd) (format t "~&n next · h hint · r rerun · l list · q quit~%~%")))) (let ((was (exercise-mtime (nth index *exercises*)))) (sleep 0.2) (let ((now (exercise-mtime (nth index *exercises*)))) (unless (eql now was) (run-and-show (nth index *exercises*))))))) (save-state) (format t "~&Bye! Progress saved.~%")))) ;;; --------------------------------------------------------------------- ;;; One-shot commands (defun resolve-exercise (name) (cond (name (find-exercise name)) (t (nth (initial-index) *exercises*)))) (defun run-command (name) (let ((ex (resolve-exercise name))) (set-current-name (exercise-name ex)) (ensure-orig-snapshot) (multiple-value-bind (output code timed-out-p) (run-exercise-file (exercise-path ex)) (format t "~a~%" output) (cond (timed-out-p (format t "~&~a~%" (red "Timed out.")) (sb-ext:exit :code 1)) ((zerop code) (mark-done ex) (format t "~&~a~%" (green (format nil "~a passed!" (exercise-name ex)))) (sb-ext:exit :code 0)) (t (format t "~&~a~%" (red (format nil "~a failed." (exercise-name ex)))) (sb-ext:exit :code 1)))))) (defun hint-command (name) (show-hint (resolve-exercise name)) (sb-ext:exit :code 0)) (defun list-command (arg) (let ((filter (cond ((null arg) :all) ((string-equal arg "pending") :pending) ((string-equal arg "done") :done) ((string-equal arg "all") :all) (t (error "Unknown filter ~s. Use all, pending or done." arg))))) (list-exercises filter) (sb-ext:exit :code 0))) (defun reset-command (name) (let ((ex (resolve-exercise name))) (ensure-orig-snapshot) (copy-file (orig-path ex) (exercise-path ex)) (unmark-done ex) (format t "~&The exercise ~a has been reset.~%" (exercise-name ex)) (format t "~&(It now matches the pristine copy from when lisplings first ran here.)~%") (sb-ext:exit :code 0))) (defun check-all-command () (ensure-orig-snapshot) (let ((passing '())) (dolist (ex *exercises*) (format t "~&Checking ~a/~a ... " (exercise-dir ex) (exercise-name ex)) (finish-output) (multiple-value-bind (output code timed-out-p) (run-exercise-file (exercise-path ex) :timeout 30) (declare (ignore output)) (let ((ok (and (not timed-out-p) (zerop code)))) (when ok (push (exercise-name ex) passing)) (setf (exercise-done ex) ok) (format t "~a~%" (if ok (green "ok") (red "FAILED")))))) (setf (getf *state* :done) passing) (let ((first-pending (find-if (complement #'exercise-done) *exercises*))) (save-state) (format t "~&~%Progress: ~a~%~%" (progress-bar)) (cond (first-pending (format t "First pending exercise: ~a~%" (namestring (exercise-path first-pending))) (sb-ext:exit :code 1)) (t (format t "All exercises pass!~%~%") (format t "~a~%" (info-field :final)) (sb-ext:exit :code 0)))))) (defun init-command (dir) (let* ((target (pathname (if (char= #\/ (char dir (1- (length dir)))) dir (concatenate 'string dir "/")))) (info (with-open-file (in (merge-pathnames "info.sexp" *source-root*)) (read in))) (specs (second (assoc :exercises info)))) (ensure-directories-exist target) (copy-file (merge-pathnames "info.sexp" *source-root*) (merge-pathnames "info.sexp" target)) (dolist (spec specs) (let ((name (getf spec :name)) (chapter (getf spec :dir))) (dolist (kind '("exercises" "solutions")) (copy-file (merge-pathnames (format nil "~a/~a/~a.lisp" kind chapter name) *source-root*) (merge-pathnames (format nil "~a/~a/~a.lisp" kind chapter name) target))) (let ((readme (merge-pathnames (format nil "exercises/~a/README.md" chapter) *source-root*))) (when (probe-file readme) (copy-file readme (merge-pathnames (format nil "exercises/~a/README.md" chapter) target)))))) (format t "~&Created a lisplings project in ~a~%~%" dir) (format t "Next steps:~% cd ~a~% lisplings~%" dir) (sb-ext:exit :code 0))) ;;; --------------------------------------------------------------------- ;;; Entry point (defun usage () (format t "Lisplings: small exercises to get you used to reading and~%") (format t "writing Common Lisp code.~%~%") (format t "Usage: lisplings [command]~%~%") (format t "Running lisplings with no command starts the watcher: it runs~%") (format t "the current exercise and reruns it whenever you save the file.~%~%") (format t "Commands:~%") (format t " run [name] run one exercise and print its output~%") (format t " hint [name] print the hint for an exercise~%") (format t " list [pending|done|all] list exercises with their status~%") (format t " reset restore an exercise to its pristine state~%") (format t " check-all run every exercise and resync progress~%") (format t " init [dir] create a lisplings project in dir (default: ./lisplings)~%") (format t " help show this message~%")) (defun main (argv) (handler-case (let ((command (first argv))) (cond ((null command) (setup) (watch) (sb-ext:exit :code 0)) ((string-equal command "init") (init-command (or (second argv) "lisplings"))) ((string-equal command "help") (usage) (sb-ext:exit :code 0)) (t (setup) (cond ((string-equal command "run") (run-command (second argv))) ((string-equal command "hint") (hint-command (second argv))) ((string-equal command "list") (list-command (second argv))) ((string-equal command "reset") (reset-command (second argv))) ((string-equal command "check-all") (check-all-command)) (t (format t "~&Unknown command: ~a~%~%" command) (usage) (sb-ext:exit :code 1)))))) (error (e) (format *error-output* "~&lisplings: ~a~%" e) (sb-ext:exit :code 1))))