id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
listlengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,562 | management.lisp | OpenBookStore_openbookstore/src/management/management.lisp | (defpackage bookshops.management
(:use :cl
:mito)
(:import-from :openbookstore.models
:find-book
:price
:ensure-integer)
(:import-from :bookshops.utils)
(:export :parse-prices)
(:local-nicknames (:models :openbookstore.models)
(:utils :bookshops.utils))
(:documentation "Commands to work on the database (clean-up,...). Depends on models and needs cl-ppcre.
- parse-prices
If some prices were saved as a string, turn them into numbers.
NB: might need an upgrade to save them as integers.
- cleanup-prices
- total-price
Compute the sum of all prices.
- create-ascii-slots
- cards-prices-to-integers
For all books, ensure their price is an integer (the price as cents).
Required on Oct, 22, when we changed the DB model to only accept prices as integers.
"))
(in-package :bookshops.management)
(defun parse-prices (&key dry-run)
"For all books, if its price is a string, extract a number from it
and set the price.
If :dry-run is true, don't make changes and only print output."
(let ((books (find-book)))
(dolist (bk books)
(format t "price of ~a: ~a~&" bk (price bk))
(if (numberp (price bk))
(format t "price is a number: ~a~&" (price bk))
(progn
(let ((new-price (utils:extract-float (price bk))))
(format t "scan: ~a~&" new-price)
(unless dry-run
(setf (price bk) new-price)
(save-dao bk))))))))
(defun total-price ()
"Sum the prices of all books in the DB."
(format t "summing prices… supposing the data scrapers return a number.~&")
;; SQL query ?
(reduce #'+ (find-book) :key #'price))
(defun create-ascii-slots ()
"For all cards, create and save the ascii representations of: title, authors, publisher.
(needs to migrate the table).
To use manually when necessary."
(time
(loop for card in (models::find-book)
for i from 0
for title-ascii = (utils:asciify (models::title card))
for authors-ascii = (utils:asciify (models::authors card))
for publisher-ascii = (utils:asciify (models::publisher card))
do (format t "- ~a asciify card ~a, \"~a\"~&"
i (object-id card) (str:shorten 40 (models::title card)))
do (setf (models::title-ascii card) title-ascii)
do (setf (models::authors-ascii card) authors-ascii)
do (setf (models::publisher-ascii card) publisher-ascii)
do (save-dao card))))
(defun cleanup-prices ()
"When the currency symbol appears in the price (currently only €), remove it.
This should be useful during development of the datasources."
(loop for card in (select-dao 'book
(sxql:where (:like :price "%€%")))
;; XXX: we should run 1 SQL query to update all fields.
do (setf (price card)
(str:trim (str:replace-all "€" "" (price card))))
do (save-dao card)))
(defun cards-prices-to-integers ()
"If the price of a book is a float, transform it to an integer.
This can create rounding errors: if our price was badly saved as a float,
it could get rounding errors: 14.9499998092651 instead of 14.95,
and we will save 14.94 instead of 14.95.
That's OK for now (Oct, 2022), the only users are developers."
(let ((books (select-dao 'models::book
(sxql:where (:not-null :price)))))
(loop for card in books
for price = (price card)
for new = (ensure-integer (* 100 price))
do (format t "~&~a results." (length books))
do (format t "~&converting price of ~a (~a): ~a -> ~a" (models::title card) (models::isbn card) price new)
do (setf (price card) new)
do (save-dao card)
do (format t " OK~&"))))
| 3,775 | Common Lisp | .lisp | 85 | 37.894118 | 113 | 0.640207 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 8ee4d63cf661c43cf78654725aa22e5555ecd59c3017ab51249d400bdcf24694 | 4,562 | [
-1
] |
4,563 | manager.lisp | OpenBookStore_openbookstore/src/terminal/manager.lisp | #|
A way to create custom commands
Just add a function like ADD-SUPERUSER (after MANAGE function definition) and add its string name
to the replic call
For example
'''
...
(defun foo () ;; your function/command
(print 'FOO))
....
(defun manage (...)) ;; MANAGE definition
(replic.completion:add-completion "manage" '("add-superuser" "foo"))
'''
Then, it can be invoked from the binary application:
$ ./bookshops -i
(home) bookshops > manage foo
|#
(defpackage bookshops.manager
(:use :cl)
(:import-from :openbookstore.models
:create-superuser
:create-role
:search-user
:list-admin-users
:is-superuser
:remove-user
:user)
(:export :manage))
(in-package :bookshops.manager)
(defun %add-superuser% (name email password)
(create-role :admin)
(create-superuser name email password))
(defun add-superuser (&optional name-input email-input password-input)
"Command for create a custom superuser"
(let ((name name-input)
(email email-input)
(password password-input))
(if (not name)
;; this %readline works on readline and Slime too.
(setf name (bookshops.commands::%readline :prompt
(format nil (str:concat "Enter username"
(cl-ansi-text:red "*")
" ? ")))))
(cond ((str:blank? name)
(error "The username field is mandatory, please try again."))
((search-user :name name)
(error "Username ~a already exists" name))
(t nil))
(if (not email)
(setf email (bookshops.commands::%readline :prompt
(format nil (str:concat "Enter email"
(cl-ansi-text:red "*")
" ? ")))))
(cond ((str:blank? email)
(error "The email field is mandatory, please try again."))
((search-user :email email)
(error "User with email ~a already exists" email))
(t nil))
(if (not password)
(setf password (bookshops.commands::%readline :prompt
(format nil (str:concat "Enter password"
(cl-ansi-text:red "*")
" ? ")))))
(cond ((str:blank? password)
(error "The password field is mandatory, please try again."))
(t nil))
(%add-superuser% name email password)
(format t "User ~a was created successfully~%" name)))
(defun list-superusers ()
"Command for list all superusers in the system"
(dolist (admin (list-admin-users :pprint-result t))
(format t "~a ~%" admin)))
(defun remove-superuser (&optional name-or-email-input)
"Command for remove a superuser for its name or email"
(let ((name-or-email name-or-email-input)
user)
(if (not name-or-email)
(setf name-or-email
(rl:readline :prompt
(format nil (str:concat "Enter username or email"
(cl-ansi-text:red "*")
" ? ")))))
(setf user (or (search-user :name name-or-email)
(search-user :email name-or-email)))
(cond ((str:blank? name-or-email)
(error "The field is mandatory, please try again."))
((not user)
(error "The user not exists"))
((not (is-superuser user))
(error "The user is not a superuser"))
(t nil))
(remove-user user)
(format t "User was deleted successfully ~%")))
(defun manage (&optional what &rest params)
(apply (symbol-function (read-from-string (format nil "bookshops.manager::~a" what))) params))
(replic.completion:add-completion "manage" '("add-superuser" "list-superusers" "remove-superuser"))
| 4,088 | Common Lisp | .lisp | 96 | 30.614583 | 99 | 0.543917 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | c4349f745264642bf3efcd07570d5e5b9a1f726a4a241a5d74e64b23ee88e1d2 | 4,563 | [
-1
] |
4,564 | api.lisp | OpenBookStore_openbookstore/src/web/api.lisp | (in-package :openbookstore/web)
#+nil
(log:config :debug)
(defroute api-card-add-one ("/api/card/add" :method :post)
(&post (id :parameter-type 'integer))
(log:debug "Requested id: ~a.~&" id)
(let ((card (models:find-by :id id)))
(assert card)
(princ-to-string
(models:add-to (models:default-place) card))))
(defroute api-card-remove-one ("/api/card/remove" :method :post)
(&post (id :parameter-type 'integer))
(let ((card (models:find-by :id id)))
(assert card)
(princ-to-string
(models:add-to (models:default-place)
card
:quantity -1))))
(defroute api-receive-card ("/api/receive" :method :post)
(&post (counter :parameter-type 'integer)
(shelf-id :parameter-type 'integer :real-name "shelf_id")
q)
"Receive a query (ISBN so far), look for it and return the full data.
The counter is used on the client side to update the corresponding node."
;;Changes:
;; - Should add a card for new ISBNs automatically
;; - Check-in-stock is not done by search anymore. Done here.
;; - Adding keyword search should be easy: just remove :remote-key and
;; :local-key parameters below.
(setf (hunchentoot:content-type*) "application/json")
;; (sleep 2) ;debug
(log:debug shelf-id)
(cl-json:encode-json-plist-to-string
(print (if (and q
(not (str:blankp q))
(<= 3 (length q)))
(list :counter counter
:card
(first ; get-or-search-single = 1 result please.
(models::check-in-stock ; gives back a list :/
(get-or-search-single q :remote-key nil :local-key nil
:save t )
:shelf-id shelf-id)))
(list :counter counter
:card "bad query")))))
(models:define-role-access route-api-card-update :view :editor)
(defroute route-api-card-update ("/api/card/update" :method :POST
:decorators ((easy-routes:@json)))
((card-id :real-name "cardId" :parameter-type 'integer)
(shelf-id :real-name "shelfId" :parameter-type 'integer))
"Update a Card.
Args:
- card-id: necessary (GET parameter on the URL)
- shelf-id (GET parameter)
- review (request body)
Called from card.js to update the shelf and the review.
The complete card update form, used from the edit page, is in card-update/post-route.
Changing the shelf works when we choose the blank option from the HTML select too:
FIND-SHELF-BY :id NIL returns NIL, and it works. Handy."
(let* ((data (hunchentoot:raw-post-data :force-text t))
(card (models:find-by :id card-id))
(shelf (when shelf-id
(models::find-shelf-by :id shelf-id)))
;; review is given only in the request body.
(review (when data
data))
(update-p nil))
(when (and card shelf)
(setf (models::shelf card) shelf)
(setf update-p t))
(when (and card review)
(setf (models::review card) (str:trim review))
(setf update-p t))
(cond
(card
(when update-p
(mito:save-dao card))
(cl-json:encode-json-to-string (dict "status" 200)))
(t
(cl-json:encode-json-to-string (dict "status" 400 "message" "no card to save"))))
))
(models:define-role-access api-quick-search :view :editor)
(defroute api-quick-search
("/api/quick-search" :decorators ((@check-roles stock-route) (easy-routes:@json))) (&get q)
(cl-json:encode-json-plist-to-string (quick-search q)))
;;(models:define-role-access api-sell-search :view :editor)
(defroute api-sell-search
("/api/sell-search" :decorators ((@check-roles stock-route) (easy-routes:@json))) (&get q)
(cl-json:encode-json-plist-to-string (sell-search q)))
(defun split-post-var (pvar)
(str:split #\] (substitute #\] #\[ pvar) :omit-nulls t))
(defun extract-array (name params)
"Elements of an array of objects sent in a POST request arrive with keys like: 'arrayname[0][key]'. This function joins all of the elements into a list of alists."
(let* ((params (remove-if-not (lambda (itm) (str:starts-with? name (car itm))) params))
(params (sort params #'string< :key #'car))
(last nil)
(accum nil)
(res nil))
(dolist (p params)
(destructuring-bind (_ index key) (split-post-var (car p))
(declare (ignore _))
(unless (string-equal index last)
(when last
(push (nreverse accum) res)
(setf accum nil))
(setf last index))
(push (cons (alexandria:make-keyword (string-upcase key)) (cdr p)) accum)))
(when accum (push (nreverse accum) res))
(nreverse res)))
(defvar *sell-data* nil)
(defun sell-complete (&key books client sell-date
payment-method-id payment-method-name)
(models:make-sale
:payment-method-id (parse-number payment-method-id)
:payment-method-name payment-method-name
:client client
:date sell-date
:books
(mapcar (lambda (book)
(list (cons :id (parse-number (access book :id)))
(cons :quantity (parse-number (access book :quantity)))
(cons :price (if (str:empty? (access book :price))
""
(parse-number:parse-number (access book :price))))))
books))
(list :success t))
(models:define-role-access api-sell-complete :view :editor)
(defroute api-sell-complete
("/api/sell-complete/" :method :post :decorators ((@check-roles stock-route) (easy-routes:@json)))
(&post (payment-method-id :real-name "paymentMethodId")
(payment-method-name :real-name "paymentMethodName")
client
(sell-date :real-name "sellDate"))
(let ((params
(list :books (extract-array "books" (hunchentoot:post-parameters*))
:payment-method-id payment-method-id
:payment-method-name payment-method-name
:client client
:sell-date (utils:parse-iso-date sell-date))))
(setf *sell-data* params)
(cl-json:encode-json-plist-to-string
(apply #'sell-complete params))))
| 6,390 | Common Lisp | .lisp | 142 | 36.246479 | 165 | 0.602441 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | b29f4a17185802c4ceb0f3c2d56db45a72cd5541542365aff92250cb5db6de11 | 4,564 | [
-1
] |
4,565 | package.lisp | OpenBookStore_openbookstore/src/web/package.lisp |
;; the package is defined at the application root,
;; so than every file can refer to its symbol.
(in-package #:openbookstore/web)
(djula:add-template-directory
(asdf:system-relative-pathname "openbookstore" "src/web/templates/"))
| 233 | Common Lisp | .lisp | 5 | 45.2 | 70 | 0.779736 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 5a83adc8ac7a26dc52fd9dab9dc04170e34b34ce615fbf9b30c8f60ff349d989 | 4,565 | [
-1
] |
4,566 | pre-web.lisp | OpenBookStore_openbookstore/src/web/pre-web.lisp | (in-package :openbookstore/web)
;;; Parameters and functions required before loading web.lisp
;;;
;;; We read the content of our static files and put into variables, so that they can be saved in the Lisp image.
;;; We define %serve-static-file to simply return their content (as string),
;;; and because we use with the #. reader macro, we need to put these in another file than web.lisp.
(defparameter *default-static-directory* "src/static/"
"The directory where to serve static assets from (STRING). If it starts with a slash, it is an absolute directory. Otherwise, it will be a subdirectory of where the system :abstock is installed.
Static assets are reachable under the /static/ prefix.")
(defparameter *static-files-content* (dict)
"Content of our JS and CSS files.
Hash-table with file name => content (string).")
(defun %read-static-files-in-memory ()
"Save the JS and CSS files in a variable in memory, so they can be saved at compile time."
(loop for file in (list "openbookstore.js"
"card-page.js")
with static-directory = (merge-pathnames *default-static-directory*
(asdf:system-source-directory :openbookstore))
for content = (uiop:read-file-string (merge-pathnames file static-directory))
do (setf (gethash file *static-files-content*) content)
finally (return *static-files-content*)))
;; At compile time, read the content of our static files.
;; XXX: feature flag to know when we are building a binary?
(%read-static-files-in-memory)
(defun %serve-static-file (path)
"Return the content as a string of this static file.
For standalone binaries delivery."
;; "alert('yes');" ;; witness to check this dispatcher works.
(gethash path *static-files-content*)) ;; this would not work without the #. reader macro.
| 1,846 | Common Lisp | .lisp | 29 | 58.586207 | 196 | 0.717283 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 1f3e63b8d208bfdda3db98655a921ad755659fb76b21627046c5dd85b910a610 | 4,566 | [
-1
] |
4,567 | web.lisp | OpenBookStore_openbookstore/src/web/web.lisp | (in-package :openbookstore/web)
#|
Show the stock on a web page.
(in construction)
(start-app)
and go to localhost:4242/stock/
In this file:
- custom Djula filters
- templates loading
- routes
- server start/stop
Dev helpers:
- adding ?raw=t on a URL (on a card page)
Slime reminders:
- use `C-u M-.` (`slime-edit-definition` with a prefix argument, also available as `M-- M-.`) to autocomplete the symbol and navigate to it. This command always asks for a symbol even if the cursor is on one. It works with any loaded definition. Here's a little [demonstration video](https://www.youtube.com/watch?v=ZAEt73JHup8).
|#
(defvar *server* nil
"Current instance of easy-acceptor.
Create with make-instance 'acceptor (that uses easy-routes and hunchentoot-errors).")
(defclass acceptor (easy-routes:easy-routes-acceptor hunchentoot-errors:errors-acceptor)
()
(:documentation "Our Hunchentoot acceptor that uses easy-routes and hunchentoot-errors."))
(defparameter *port* 4242)
(setf djula::*gettext-domain* (gettext:textdomain))
(setf djula::*translation-backend* :gettext)
(setf djula:*current-language* :en)
;;; Djula filters.
(djula:def-filter :price (val)
"Price is an integer, divide by 100 to get its value.
Return as a string, number printed with 2 decimals."
(if (str:non-blank-string-p val)
(format nil "~,2F" (/ val 100))
""))
(defun card-url (card)
"Create a full URL to uniquely identify this card."
(declare (type models:book card))
(format nil "/~a/~a-~a"
"card" ; this can be translated
(mito:object-id card)
;; the slug won't actually be read back, only the id.
(slug:slugify (models:title card))))
(djula:def-filter :url (card)
(card-url card))
(djula:def-filter :slugify (s)
(slug:slugify s))
(djula:def-filter :quantity (card)
(typecase card
(models:book (models:quantity card))
(models:place-copies (models:place-copy-quantity card))
(t (or (access:access card :in-stock) 0))))
(djula:def-filter :name (obj)
(format nil "~a" (models:name obj)))
(djula:def-filter :describe (card)
(with-output-to-string (s)
(describe card s)))
;;; stolen options read-from-string idea from the djula time filter
(djula:def-filter :quantity-style (quantity raw-options)
(let ((options (read-from-string raw-options)))
(cond ((= 0 quantity) (access:access options :zero))
((plusp quantity) (access:access options :positive))
(t (access:access options :negative)))))
(djula:def-filter :contact-name (contact-copy)
;; see why in loans.html. Mito limitation or me? Dec 2021.
(if (and contact-copy
(models::contact contact-copy))
(format nil "~a" (models::name (models::contact contact-copy)))
"?"))
(djula:def-filter :date-hour-minute (date)
"Print this date as YYY/MM/DD HH:MM."
(local-time:format-timestring nil date
:format '(:year "/" (:month 2) "/" (:day 2) " " (:hour 2) ":" (:min 2))))
;; If a load is outdated, show the due date in red.
(djula:def-filter :date-style (date raw-options)
(let ((options (read-from-string raw-options)))
(cond ((models::loan-too-long-p date) (access:access options :negative))
(t (access:access options :positive)))))
;; Two filters necessary because buggy Mito which doesn't show the book
;; even though book-id is set (early 2021).
(djula:def-filter :print-contact (contact-id)
(let ((contact (mito:find-dao 'models::contact :id contact-id)))
(format nil "~a" (models::name contact))))
(djula:def-filter :print-book (book-id)
(let ((obj (mito:find-dao 'models::book :id book-id)))
(format nil "~a" (models::title obj))))
(djula:def-filter :background-color (loop-index)
"Alternate between white and grey color background in a Djula loop.
For list of shelves."
(if (zerop (mod loop-index 2))
"white"
"#eee9e9"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Templates.
;;
;; Before compiling them with Djula, we tell Djula to compile them in-memory.
;; This is for binary releases.
;;
;; But for development, we like them to be on filesystem and to be re-read on change.
;; See SET-DEVEL-PROFILE.
;;
;; So, we grab all our templates defined in the .asd and compile them in-memory.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(setf djula:*current-store*
(let ((search-path (list (asdf:system-relative-pathname "openbookstore"
"src/web/templates/"))))
;; Possible issue: when I quickload this, I have a MEMORY store O_o
;; Once I C-c C-c the file, the file system store is correctly created.
#-djula-binary
(progn
(uiop:format! t "~&Openbookstore: compiling templates in file system store.~&")
;; By default, use a file-system store,
;; reload templates during development.
(setf djula:*recompile-templates-on-change* t)
(make-instance 'djula:filesystem-template-store
:search-path search-path))
;; But, if this setting is set to NIL at load time, from the Makefile,
;; we are building a standalone binary: use an in-memory template store.
;;
;; We also need to NOT re-compile templates on change.
#+djula-binary
(progn
(uiop:format! t "~&Openbookstore: compiling templates in MEMORY store.~&")
(uiop:format! t "~&NOTE: preventing Djula to recompile templates on change… set djula:*recompile-templates-on-change* to T for development (see SET-DEVEL-PROFILE).~&")
(setf djula:*recompile-templates-on-change* nil)
(make-instance 'djula:memory-template-store
:search-path search-path))))
(let ((paths (djula:list-asdf-system-templates "openbookstore" "src/web/templates")))
(loop for path in paths
do (uiop:format! t "~&Compiling template file: ~a…~&" path)
(djula:compile-template* path))
(values t :all-done))
(uiop:format! t "~&Openbookstore: all templates compiled.~&")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Compile and load templates (as usual).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter +base.html+ (djula:compile-template* "base.html"))
(defparameter +dashboard.html+ (djula:compile-template* "dashboard.html"))
(defparameter +search.html+ (djula:compile-template* "search.html"))
(defparameter +stock.html+ (djula:compile-template* "stock.html"))
(defparameter +card-page.html+ (djula:compile-template* "card-page.html"))
(defparameter +card-stock.html+ (djula:compile-template* "card-stock.html"))
(defparameter +card-create.html+ (djula:compile-template* "card-create.html"))
(defparameter +card-update.html+ (djula:compile-template* "card-edit.html"))
(defparameter +receive.html+ (djula:compile-template* "receive.html"))
;; from authentication.lisp
(defparameter +no-nav-base.html+ (djula:compile-template* "no-nav-base.html"))
(defparameter +permission-denied.html+ (djula:compile-template* "permission-denied.html"))
(defparameter +login.html+ (djula:compile-template* "login.html"))
;; Testing the UI with HTMX websockets
(defparameter +receive-ws.html+ (djula:compile-template* "receive-ws.html"))
(defparameter +sell.html+ (djula:compile-template* "sell.html"))
(defparameter +history.html+ (djula:compile-template* "history.html"))
(defparameter +loans.html+ (djula:compile-template* "loans.html"))
(defparameter +404.html+ (djula:compile-template* "404.html"))
;;;
;;; Serve static assets
;;;
;;; Two possibilities:
;;; - the app is run from source: use the usual create-folder-dispatcher-and-handler
;;; - the app is built for a standalone binary: we must get the static files content at compilation and serve them later. Hunchentoot must not access the file system, it won't find the files anymore.
;;
;; 1) The app is run from sources.
;;
;; *default-static-directory* is defined earlier in pre-web.lisp
(defun serve-static-assets ()
"Serve static assets under the /src/static/ directory when called with the /static/ URL root.
See serve-static-assets-for-release to use in a binary release."
(push (hunchentoot:create-folder-dispatcher-and-handler
"/static/" (merge-pathnames *default-static-directory*
(asdf:system-source-directory :openbookstore) ;; => NOT src/
))
hunchentoot:*dispatch-table*))
;;
;; 2) We build a binary and we want to include static files.
;;
;; see pre-web.lisp
;; Because we use the #. reader macro, we need to define some things in another file,
;; that is loaded when this one is loaded.
(defun serve-static-assets-for-release ()
"In a binary release, Hunchentoot can not serve files under the file system: we are on another machine and the files are not there.
Hence we need to get the content of our static files into memory and give them to Hunchentoot."
(push
(hunchentoot:create-regex-dispatcher "/static/openbookstore\.js"
(lambda ()
;; Returning the result of the function calls silently fails. We need to return a string.
;; Here's the string, read at compile time.
#.(%serve-static-file "openbookstore.js")))
hunchentoot:*dispatch-table*)
(push
(hunchentoot:create-regex-dispatcher "/static/card-page\.js"
(lambda ()
#.(%serve-static-file "card-page.js")))
hunchentoot:*dispatch-table*))
#+#:only-for-devel
(setf hunchentoot:*dispatch-table* nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Some web utils.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun truthy-p (val)
"Return t if VAL is truthy: it is t, 1, \"true\"…"
(when (member val '(1 t "1" "t" "true" "yes") :test #'equal)
t))
#+(or)
(assert
(and (every #'truthy-p '(t "t" "1" 1 "true"))
(not (every #'truthy-p '(t "f" "false")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Routes.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(openbookstore.models:define-role-access home-route :view :visitor)
(defroute home-route ("/" :decorators ((@check-roles home-route))) ()
;; aka dashboard-route
(render-template* +dashboard.html+ nil
:route "/"
:current-user (current-user)
:data (list :nb-titles (models:count-book)
:nb-books (models::total-quantities)
:nb-titles-negative (length
(models::negative-quantities))
:outdated-loans
(models::outdated-loans :limit 20 :order :asc)
:nb-outdated-loans
(models::count-outdated-loans)
)))
;XXX: we don't need a similar define-role-access for each route.
(openbookstore.models:define-role-access stock-route :view :visitor)
(defroute stock-route ("/stock" :decorators ((@check-roles stock-route)))
(&get q
(shelf-name-ascii-or-id :real-name "shelf"))
(let* ((shelf (cond
;; We preferably create links with shelf ascii names.
;; but in the card page JS, we edit the link with the id… simpler for JS side.
((integerp
(ignore-errors (parse-integer shelf-name-ascii-or-id)))
(models::find-shelf-by :id shelf-name-ascii-or-id))
(t
(log:info shelf-name-ascii-or-id)
(models::find-shelf-by :name-ascii shelf-name-ascii-or-id))))
;; Had a doubt if the search returned a list…
;; (shelf (if (and shelves (listp shelves)) ;; unsure… see find-by (for books) and this.
;; (first shelves)
;; shelves))
(cards (cond
((utils:isbn-p q)
(list (models:find-by :isbn q)))
(q
(models:find-book :query (bookshops.utils::asciify q)
:shelf shelf))
(t
;; XXX: pagination
(alexandria-2:subseq* (models:find-book :shelf shelf) 0 50)))))
(render-template* +stock.html+ nil
:route "/stock"
:title (format nil "Stock ~a~a ~a - OpenBookstore"
(if q q "")
(if shelf ", " "")
(if shelf (models::name shelf) ""))
:cards cards
:shelves (models::find-shelf)
:form-shelf shelf
:nb-results (length cards)
:q q
:data (list :nb-titles (openbookstore.models:count-book)
:nb-books (openbookstore.models::total-quantities)
:nb-titles-negative (length
(openbookstore.models::negative-quantities))))))
(openbookstore.models:define-role-access search-route :view :visitor)
(defroute search-route ("/search" :decorators ((@check-roles search-route))) (&get q datasource)
(let* ((datasource (str:trim datasource))
(cards (and q (search-datasources q
:datasource (str:downcase datasource)))))
(if cards
(render-template* +search.html+ nil
:route "/search"
:title "Search - OpenBookstore"
:q q
:cards cards
:datasource datasource
:nb-results (length cards)
:title (format nil "OpenBookstore - search: ~a" q))
(render-template* +search.html+ nil
:route "/search"
:title "Search - OpenBookstore"
:datasource datasource
:q q))))
;; (defroute search-route/post ("/search" :method :POST) (&post q) nil)
(openbookstore.models:define-role-access add-or-create-route :view :editor)
(defroute add-or-create-route ("/card/add-or-create/" :method :post
:decorators ((@check-roles add-or-create-route)))
(q title isbn price authors cover-url publisher (updatep :parameter-type 'boolean
:init-form t)
(book-id :parameter-type 'string :init-form "")
(referer-route :parameter-type 'string :init-form "/search"))
(let* ((book
(if (str:blank? book-id)
(models:find-existing
(models:make-book :title title :isbn isbn :cover-url cover-url
:price price
:authors (str:trim authors)
:publisher publisher)
:update updatep)
(models:find-by :id book-id))))
(models:save-book book)
(render-template* +card-page.html+ nil
:q q
:card book
:referer-route referer-route
:places-copies
(openbookstore.models::book-places-quantities book)
:places (openbookstore.models:find-places))))
(defun redirect-to-search-result (route query book)
(hunchentoot:redirect
(format nil "~a~@[?q=~a~]#card~a" route
(and (str:non-empty-string-p query) query)
(mito:object-id book))))
(openbookstore.models:define-role-access add-or-create-route :view :editor)
(defroute card-add-stock-route ("/card/add-stock/" :method :post
:decorators ((@check-roles add-or-create-route)))
(q place-id (quantity :parameter-type 'integer :init-form 0) isbn
(referer-route :parameter-type 'string :init-form "/search"))
(let ((card (models:find-by :isbn isbn))
(place (models:find-place-by :id place-id)))
(openbookstore.models:add-to place card :quantity quantity)
(redirect-to-search-result referer-route q card)))
(openbookstore.models:define-role-access add-or-create-route :view :editor)
;; Create a book in DB given the URL parameters and go back to the search results.
;; In search.html, the form has hidden fields to pass along the title, the ISBN, the price…
;; Redirect to the original route.
(defroute card-quick-add-route ("/card/quick-add-stock/" :method :post
:decorators ((@check-roles add-or-create-route)))
(q (quantity :parameter-type 'integer :init-form 1)
title isbn price authors cover-url publisher
(updatep :parameter-type 'boolean :init-form t)
(book-id :parameter-type 'string :init-form "")
(referer-route :parameter-type 'string :init-form "/search"))
(let ((book
(if (str:blank? book-id)
(models:find-existing
(models:make-book :title title :isbn isbn :cover-url cover-url
:price price
:authors (str:trim authors)
:publisher publisher)
:update updatep)
(models:find-by :id book-id))))
(models:save-book book)
(openbookstore.models:add-to (models:default-place) book :quantity quantity)
(redirect-to-search-result referer-route q book)))
;; Card view.
(openbookstore.models:define-role-access add-or-create-route :view :visitor)
(defroute route-card-page ("/card/:slug" :method :GET :decorators ((@check-roles add-or-create-route)))
(&get raw)
"Show a card.
If the URL parameter RAW is \"t\" (the string), then display the card object literally (with describe)."
(let* ((card-id (ignore-errors
(parse-integer (first (str:split "-" slug)))))
(card (when card-id
(models:find-by :id card-id)))
(shelves (models::find-shelf)))
(cond
((null card-id)
(render-template* +404.html+ nil))
(card
(render-template* +card-stock.html+ nil
:messages nil
:card card
:places-copies (models::book-places-quantities card)
:shelves shelves
:borrowed-books (models::find-book-loans card)
:raw raw))
(t
(render-template* +404.html+ nil)))))
;; Carde create: GET.
(models:define-role-access card-create-route :view :editor)
(defroute card-create-route ("/card/create" :method :get
:decorators ((@check-roles card-create-route)))
(title isbn price authors shelf-id new-shelf-name)
;; see also: the API for POST updates.
;; (describe (hunchentoot:start-session) t)
;; (log:info (bookshops.messages::add-message "Hello message :)"))
;;
;; If we have URL params, that means we tried to submit a form,
;; and got a validation error, so we want to re-show the data submitted.
;; Like a form does.
;; But… we don't show erroneous fields in red and we do very little client side validation…
(let ((card (models:make-book :title title
:isbn isbn
:price price
:authors (str:trim authors)
:shelf-id shelf-id))
;; More data we want to pass along to the form.
;; so actually… we don't really need the card object, only
;; a big form-data.
(more-form-data (dict :new-shelf-name new-shelf-name)))
(render-template* +card-create.html+ nil
:shelves (models::find-shelf)
:title "New book - OpenBookstore"
:card card
:more-form-data more-form-data
:messages/status (bookshops.messages:get-message/status))))
;; Carde create: POST.
(models:define-role-access card-create/post-route :view :editor)
(defroute card-create/post-route ("/card/create" :method :post
:decorators ((@check-roles card-create-route)))
;; title is mandatory, the rest is optional.
(title isbn price authors shelf-id new_shelf_name)
(when (str:blankp title)
(bookshops.messages::add-message "Please enter a title" :status :warning)
(hunchentoot:redirect "/card/create"))
;; XXX: handle more than one validation message.
(when (and (str:non-blank-string-p isbn)
(not (bookshops.utils:isbn-p isbn)))
(bookshops.messages::add-message (format nil "This doesn't look like an ISBN: ~a" isbn) :status :warning)
(hunchentoot:redirect
;; Redirect to the create page, give the pre-entered data as URL params.
;; We could also use session data.
(easy-routes:genurl 'card-create/post-route
:title title
:isbn isbn
:price price
:authors (str:trim authors)
:shelf-id shelf-id
:new-shelf-name new_shelf_name)))
(handler-case
(let ((book (models:make-book :title title
:isbn (bookshops.utils:clean-isbn isbn)
:authors (str:trim authors)
:shelf-id shelf-id
:new-shelf-name new_shelf_name
:price (utils:ensure-float price))))
(mito:save-dao book)
(bookshops.messages:add-message "The book was created successfully.")
(hunchentoot:redirect "/card/create"))
(error (c)
;; XXX: 404 handled by hunchentoot
(format *error-output* "An unexpected error happened: ~a" c)
(error c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Edit/update an existing card.
;;; Similar from create.
(defroute card-update-route ("/card/update/:id" :method :get
:decorators ((@check-roles card-create-route)))
()
;; see also: the API for POST updates.
;; (describe (hunchentoot:start-session) t)
;; (log:info (bookshops.messages::add-message "Hello message :)"))
(let ((card (models::find-by :id id)))
(render-template* +card-update.html+ nil
:card card
:shelves (models::find-shelf)
:title (format nil "Edit: ~a - OpenBookstore" (str:shorten 40 (models:title card) :ellipsis "…"))
:messages/status (bookshops.messages:get-message/status))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; card update POST
(models:define-role-access card-update/post-route :view :editor)
(defroute card-update/post-route ("/card/update/:id" :method :post
:decorators ((@check-roles card-create-route)))
;; title is mandatory, the rest is optional.
(title isbn price authors shelf-id)
(log:info "updating card: " title price authors)
;;
;; Begin form validation.
;; XXX: handle more than one validation message at the same time.
;;
;; Do we have a title?
;; (shouldn't happen client side, it is a required field)
(when (str:blankp title)
(bookshops.messages::add-message "Please enter a title" :status :warning)
;; ;XXX: redirect to update form.
(hunchentoot:redirect "/card/create"))
;; Is it a valid ISBN, if any?
(when (and (str:non-blank-string-p isbn)
(not (bookshops.utils:isbn-p isbn)))
(bookshops.messages::add-message (format nil "This doesn't look like an ISBN: ~a" isbn) :status :warning)
;; Update our current card object (don't save it),
;; so we show the user data in the form.
;; See also what I did slightly differently for the creation form.
(let ((card (models::find-by :id id)))
;; Convert the float price back to the integer, price in cents.
(setf price (utils:price-float-to-integer price))
(setf authors (str:trim authors))
(log:info "new price: " price)
(setf card (models::update-book-with card
`((:title ,title)
(:isbn ,isbn)
(:price ,price)
(:authors ,authors))))
(return-from card-update/post-route
(render-template* +card-update.html+ nil
:card card
:shelves (models::find-shelf)
:title (format nil "Edit: ~a - OpenBookstore" (str:shorten 40 (models:title card) :ellipsis "…"))
:messages/status (bookshops.messages:get-message/status)))))
;;
;; XXX: validate other fields, even if they have a little client-side validation:
;; - price
;;
;; Form validation OK.
;;
(handler-case
(let ((book (models:find-by :id id))
(shelf (models::find-shelf-by :id shelf-id)))
;; Update fields.
;; Convert the float price back to the integer, price in cents.
(setf price (utils:price-float-to-integer price))
(log:info "new price: " price)
(setf authors (str:trim authors))
(setf book (models::update-book-with book
`((:title ,title)
(:isbn ,isbn)
(:price ,price)
(:authors ,authors)
(:shelf ,shelf))))
;; Save.
(mito:save-dao book)
;; We don't see the message after a redirect, too bad.
;; (bookshops.messages:add-message "The book was updated successfully.")
(hunchentoot:redirect (easy-routes:genurl 'route-card-page
:slug (str:concat id "-" (slug:slugify title)))))
(error (c)
;; XXX: 404 handled by hunchentoot
(format *error-output* c))))
(openbookstore.models:define-role-access receive-route :view :editor)
(defroute receive-route ("/receive" :method :get
:decorators ((@check-roles receive-route)))
() ;; args
(render-template* +receive.html+ nil
:route "/receive"
:shelves (models::find-shelf)
:title "Receive - OpenBookstore"))
(defroute receive-in-shelf-route ("/receive/:shelf-slug" :method :get
:decorators ((@check-roles receive-route)))
() ;; args
(let ((shelf (models::find-shelf-by :id
(first (str:split "-" shelf-slug)))))
(log:info shelf "request URI?" (hunchentoot:request-uri*))
(render-template* +receive.html+ nil
:route "/receive"
:current-shelf shelf
:shelves (models::find-shelf)
:title "Receive - OpenBookstore")))
(defroute receive-ws-route ("/receive-ws" :method :get
:decorators ((@check-roles receive-route)))
() ;; args
(render-template* +receive-ws.html+ nil
:route "/receive-ws"
:title "Receive WS Devel- OpenBookstore"))
(openbookstore.models:define-role-access sell-route :view :editor)
(defroute sell-route ("/sell" :method :get
:decorators ((@check-roles sell-route)))
() ;; args
(render-template* +sell.html+ nil
:route "/sell"
:title "Sell - OpenBookstore"))
(openbookstore.models:define-role-access history-route :view :editor)
(defroute history-route ("/history" :decorators ((@check-roles history-route))
:method :get)
() ;; args
(let ((now (local-time:now)))
(hunchentoot:redirect
(easy-routes:genurl
'history-route-month
:yearmonth (local-time:format-timestring nil now :format '(:year "-" (:month 2)))))))
(openbookstore.models:define-role-access history-route :view :editor)
(defroute history-route-month ("/history/month/:yearmonth" :decorators ((@check-roles history-route))
:method :get)
() ;; args
(let* ((today (local-time:today))
;; OK, so this works but is fragile.
(slugdate (str:split "-" yearmonth))
(year (parse-integer (first slugdate)))
(month (parse-integer (second slugdate)))
(min-date (local-time:encode-timestamp 0 0 0 0 1 ;; first day of month.
month
year))
;; (min-date (utils::x-days-ago 30))
;; (max-date (local-time:today))
(max-date (local-time:encode-timestamp 0 0 0 0
(local-time:days-in-month month year)
month
year))
;; We could have a search function that accepts strings for dates
;; (easier for testing).
(data (models::group-sells-and-soldcards :order :desc
:min-date min-date
:max-date max-date)))
(render-template* +history.html+ nil
:route "/history"
:title (format nil "History ~a - OpenBookstore" yearmonth)
:min-date min-date
:max-date max-date
:today today
:data data)))
(openbookstore.models:define-role-access loans-route :view :editor)
(defroute loans-route ("/stock/loans" :decorators ((@check-roles history-route))
:method :get)
(outdated) ;; args
(setf outdated (truthy-p outdated))
(render-template* +loans.html+ nil
:route "/stock/loans"
:title "Loans - OpenBookstore"
:loans (if outdated
(models::outdated-loans)
(models::find-loans))
:filter-outdated-p outdated))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Start-up functions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun start-app (&key (port *port*))
(openbookstore.models:connect)
;; fix a puri bug. puri:parse-uri "/login?referer-route=/stock?q=lisp" fails,
;; it doesn't like the last ?. See https://gitlab.common-lisp.net/clpm/puri/-/issues/2
(setf puri::*strict-illegal-query-characters*
;; xxx: mmmh… not enough (any more)
(remove #\? puri::*strict-illegal-query-characters*))
;; Watch out case output. This trips up JS.
;; The output of
#+(or) (cl-json:encode-json-plist-to-string (sell-search "test"))
;; should be encoded in lowercase.
;; This is the default but it has been a source of error already.
(setf json:*json-identifier-name-to-lisp* #'json:camel-case-to-lisp)
(setf json:*lisp-identifier-name-to-json* #'json:lisp-to-camel-case)
;; (setf *server* (make-instance 'easy-routes:easy-routes-acceptor :port port))
(setf *server* (make-instance 'acceptor :port port))
(hunchentoot:start *server*)
(if (deploy:deployed-p)
;; Binary release: don't serve files by reading them from disk.
(serve-static-assets-for-release)
;; Normal setup, running from sources: serve static files as usual.
(serve-static-assets))
(uiop:format! t "~&Application started on port ~a.~&" port))
(defun stop-app ()
;; disconnect db ?
(hunchentoot:stop *server*))
;;;;;;;;;;;;;;;
;; Dev helpers
;;;;;;;;;;;;;;;
(defun set-devel-profile ()
"- interactive debugger
- re-read Djula templates on change (maybe not enough, see in-memory template compilation)."
(log:config :debug)
(setf djula:*recompile-templates-on-change* t)
(setf hunchentoot:*catch-errors-p* nil))
| 32,937 | Common Lisp | .lisp | 641 | 39.720749 | 329 | 0.565151 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 6dd9c9b276237b0985058ca7375be6d198ad915e4bb4901bf5ba84ce026a25a7 | 4,567 | [
-1
] |
4,568 | search.lisp | OpenBookStore_openbookstore/src/web/search.lisp | (in-package :openbookstore/web)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Tools for web searches
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Low level stuff
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(function-cache:defcached (remote-isbn-search :timeout (* 24 3600)) (q &key datasource)
(declare (type string q))
(values
(if (dilicom:available-p)
(dilicom:search-books (list q))
(bookshops.datasources.main:search-books q :datasource datasource))
1))
(function-cache:defcached (remote-key-search :timeout (* 24 3600)) (q &key datasource)
(declare (type string q))
(values (bookshops.datasources.main:search-books q :datasource datasource)
1))
;;; Note: the local functions return lists of book objects, not lists of hash tables.
(declaim (ftype (function (string) models:list-of-books) local-isbn-search local-key-search))
(defun local-isbn-search (q)
(a:when-let ((res (models:find-by :isbn q)))
(list res)))
(defun local-key-search (q)
(models:find-book :query (bookshops.utils::asciify q)))
(declaim (ftype (function (hash-table &key (:save boolean)) models:book) save-remote-find))
(defun save-remote-find (find &key (save t))
"Convert a remote search result into a book object and optionally save."
(let*
((found find)
(title (gethash :title found))
(isbn (utils:clean-isbn (gethash :isbn found)))
(authors (gethash :authors found ""))
(price (gethash :price found ""))
(price (utils:ensure-float price))
(book (models:make-book :title title
:isbn isbn
:authors authors
:price price
:cover-url (access found :cover-url))))
(when (and save book)
(models:save-book book))
book))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Higher level search funcs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun search-datasources (q &key datasource)
"Search by keyword and ISBN on the given datasource.
After the search, we check if we have these books in our DB. If so, we augment their data with a `quantity' field.
Results are cached for a day.
QUERY can be an ISBN or keywords.
DATASOURCE comes from the web search form."
(declare (type string q))
(models::check-in-stock
(cond
((bookshops.utils:isbn-p q) (remote-isbn-search q :datasource datasource))
((not (str:blank? q)) (remote-key-search q :datasource datasource))
(t nil))))
(defvar *single-result* nil)
(declaim (ftype (function (string
&key
(:remote-key boolean) (:remote-isbn boolean) (:local-key boolean)
(:local-isbn boolean) (:save boolean))
models:list-of-books) get-or-search))
(defun get-or-search (q &key (remote-key t) (remote-isbn t)
(local-key t) (local-isbn t) save)
"General search function. Will perform an ISBN or keyword search, both local and remote. ISBN searches will be performed before keyword, and local searches will be performed before remote. Search will stop on the first kind of search that returns a result.
Any of :remote-key, :remote-isbn, :local-key or :local-isbn may be set to NIL to stop that particular search. If results are found, a list of book objects will be returned.
Cards will be created for remote finds if :save is set T."
(declare (type string q))
(if (utils:isbn-p q)
(a:if-let
(found (and local-isbn (local-isbn-search q)))
found
(a:when-let*
((found (and remote-isbn (remote-isbn-search q)))
(book (save-remote-find (car found) :save save)))
(list book)))
(a:if-let
(found (and local-key (local-key-search q)))
found
(a:when-let*
((found (and remote-key (remote-key-search q)))
(books (mapcar (lambda (b) (save-remote-find b :save save))
;;Only save what we are going to return
(if *single-result* (list (car found)) found))))
books))))
(declaim (ftype (function (string
&key
(:remote-key boolean) (:remote-isbn boolean) (:local-key boolean)
(:local-isbn boolean) (:save boolean))
(or null models:book)) get-or-search-single))
(defun get-or-search-single (q &key (remote-key t) (remote-isbn t)
(local-key t) (local-isbn t) save)
(let ((*single-result* t))
(setf q (str:trim q))
(car (get-or-search q :remote-key remote-key :remote-isbn remote-isbn :local-key local-key
:local-isbn local-isbn :save save))))
(defun quick-search (q)
"Either search an ISBN in our DB first, then on a datasource (and on that case, create a card object).
either search by keywords in our DB.
Return a plist:
- :GO + card base URL if we got a result by ISBN
- :RESULTS + JSON of books."
(let ((res (get-or-search q :remote-key nil :save t)))
(if (< 1 (length res))
;; Use strings as keys, because with symbols I have seen inconsistency
;; in the JSON results.
;; Once they are lowercased, once they are uppercased.
;; Switch from cl-json?
(list "results"
(mapcar (lambda (book)
(dict "url" (card-url book)
"title" (models:title book)))
res))
(when res
(list "go" (card-url (car res)))))))
(defun sell-search (q)
(let ((res (get-or-search q :remote-key nil :remote-isbn t :save t)))
(cond
((< 1 (length res))
(list "options"
(mapcar (lambda (book)
;; Embed the full book.
;; It will be serialized by the JSON library.
(dict "card" book
"url" (card-url book)
"title" (models:title book)))
res)))
((eq 1 (length res))
(list "card" (car res)))
(t (list "error"
(if (utils:isbn-p q)
"No book found for ISBN"
"No matches found in store"))))))
| 6,323 | Common Lisp | .lisp | 135 | 36.8 | 258 | 0.569922 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 38365fa3d2488aaac8205978b2667d6dbd0834dbad567b89730aaad93f548bb5 | 4,568 | [
-1
] |
4,569 | messages.lisp | OpenBookStore_openbookstore/src/web/messages.lisp | ;;;
;;; Light interface around hunchentoot's session to store and retrieve messages
;;; across web pages.
;;;
;;; In a Djula template, use like:
#|
{% for msg in messages %}
<div class="notification {{ msg.class }}">
<button class="delete"></button>
{{ msg.message }}
</div>
{% endfor %}
|#
;;;
;;; ;TODO: handle many messages
(defpackage bookshops.messages
(:use :cl)
(:export :add-message
:get-message-text
:get-message/status))
(in-package :bookshops.messages)
;; CSS classes. Overwrite, or adapt your stylesheet.
(defparameter +class-success+ "is-success")
(defparameter +class-error+ "is-error")
(defparameter +class-warning+ "is-warning")
(defparameter +class-info+ "is-info")
(defun get-class (status)
(case status
(:success +class-success+)
(:warning +class-warning+)
(:error +class-error+)
(t +class-info+)))
(defun add-message (message &key (status :success))
(setf (hunchentoot:session-value :message-status) status
(hunchentoot:session-value :message) message))
(defun %delete-data ()
(hunchentoot:delete-session-value :message)
(hunchentoot:delete-session-value :message-status) )
(defun get-message-text ()
"Get only the message's text, discard its status."
(let ((val (hunchentoot:session-value :message)))
(%delete-data)
val))
(defun get-message/status ()
"Return a plist with :message, :status and :class (CSS class) properties"
(let ((val (hunchentoot:session-value :message))
(status (hunchentoot:session-value :message-status)))
(when val
(%delete-data)
`((:message ,val
:status ,status
:class ,(get-class status))))))
| 1,734 | Common Lisp | .lisp | 52 | 28.596154 | 79 | 0.657501 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 9bed6073ba8c43525ff4dffa97b267089ed9fdcadea665fdb413ea71e076e6a8 | 4,569 | [
-1
] |
4,570 | receive-websocket.lisp | OpenBookStore_openbookstore/src/web/receive-websocket.lisp |
(in-package :openbookstore/web)
#|
Status: les websockets marchent, mais je n'arrive pas à afficher un livre PUIS à remplacer le div associé.
L'élément de DOM ajouté est seulement le div class=media, et pas le div class=card et id=card-x
càd la 2nd target de remplacement n'y est pas.
Pour tester:
https://www.piesocket.com/websocket-tester
|#
(defvar *clients-ws* nil
"List of connected WS")
(defparameter *html-card*
"
<div id=\"~a\" hx-swap-oob=\"~a\"
<div class=\"card\" id=\"~a\"
<div class=\"card-content\">
<div class=\"media\">
<div class=\"media-left\">
<figure class=\"image is-48x48\">
<img src=\"https://bulma.io/images/placeholders/96x96.png\" alt=\"Placeholder image\">
</figure>
</div>
<div class=\"media-content\">
<p class=\"title is-5\"> ~a
</p>
<p class=\"subtitle is-6\"> counter: ~a </p>
<p class=\"subtitle is-6\"> </p>
<p class=\"subtitle is-6\">
9.90 €
</p>
</div>
</div>
<div class=\"content\">
</div>
</div>
</div>
</div>
")
(defun make-htmx-message (msg &key replace counter)
"Return a HTML snippet with somehow the id and title."
(let* ((cnt (or counter
(incf *counter*)))
(card-id (format nil "card-~a" cnt)))
(format nil *html-card*
(if replace card-id "id-livres")
(if replace "true" "afterend")
card-id
msg
cnt)))
(defun broadcast (msg)
;; not by default in Portal, why not?
;;
;; broadcast n'est pas nécessaire pour cette page,
;; mais c'est bien pratique pour tester avec une autre fenêtre piesocket tester et voir
;; si les messages sont reçus.
(loop for client in *clients-ws* do
(pws:send client msg)))
(defvar *counter* 0
"Counter for the DIV to update.")
(pws:define-resource "/echo"
:open (lambda (websocket)
;; On receive, display a simple message for a ACK (testing).
(push websocket *clients-ws*)
(setf *counter* 0)
(pws:send websocket
"<div id=\"body\"> test </div>
<div id=\"notifications\" hx-swap-oob=\"true\"> hello from ws app ! </div>"))
:message (lambda (websocket message)
(handler-case
(let* ((counter (incf *counter*))
(json (shasht:read-json message))
(msg (access json "chat_message")))
;; Envoyer un 1er message avec un id égale à "card-<counter>",
;; qui est retourné de suite.
(broadcast (make-htmx-message msg :counter counter))
;; Puis lancer une thread qui est censée mettre à jour ce premier snippet.
(bt:make-thread
(lambda ()
(sleep 1)
;; (broadcast (format nil "<div id=\"card-~a\" hx-swap-oob=\"true\"> Message is: ~a and counter is ~a </div>" counter msg counter))
;; Ici on essaie de remplacer le 1er snippet avec un nouveau titre.
(broadcast (print (make-htmx-message
(format nil "nouveau titre ~a" counter)
:counter counter
:replace t))))
:name "ws-child-thread")
(pws:send websocket (format nil "<div id=\"notifications\" hx-swap-oob=\"afterbegin\"> Exited right away. Message was: ~a </div>" msg))
)
(sb-int:closed-stream-error (c)
;; Quand on met le PC en pause, les connexions sont fermées,
;; mais il faut gérer ça à la mano.
(declare (ignore c))
;; see also pws:*debug-on-error* ?
(format t "websocket is closed, removing from clients: ~S" websocket)
;; Il y a un restart dans Portal qui permet de clore la socket,
;; à étudier pour l'appeler par défaut…
(pws::call-resource-function :close websocket)
(setf *clients-ws* (remove websocket *clients-ws*))
))
;; Premiers tests simples.
;; (pws:send websocket (format nil "message 1: ~a" message))
;; (pws:send websocket
;; "<div id=\"notifications\" hx-swap-oob=\"true\"> message 1 </div>")
;; (broadcast
;; "<div id=\"notifications\" hx-swap-oob=\"afterbegin\"> message 1 </div>")
;; (sleep 1)
)
:close (lambda (websocket)
(declare (ignorable websocket))
(format t "~&--- ws list: ~S" *clients-ws*)
(format t "~&--- client leaving: ~S" websocket)
;; Gérer la liste de clients… pas besoin pour la page Réception.
(setf *clients-ws* (remove websocket *clients-ws*))
(format t "~&--- ws list after removal: ~S" *clients-ws*)))
(defparameter ws-server nil)
(defun start-ws ()
(setf ws-server (pws:server 4432 t)))
| 5,457 | Common Lisp | .lisp | 116 | 33.043103 | 156 | 0.511351 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 2f107d306130f730c566c653117a7027065d2164aa953835feae5d42fa017408 | 4,570 | [
-1
] |
4,571 | mito-forms.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-forms.lisp |
(in-package :mito-admin)
#|
Trying…
Find a Mito slot
(mito.class:find-slot-by-name 'book 'shelf)
#<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::SHELF>
(inspect *)
The object is a STANDARD-OBJECT of type MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS.
0. SOURCE: #S(SB-C:DEFINITION-SOURCE-LOCATION
:NAMESTRING "/home/vince/projets/openbookstore/openbookstore/src/models/models.lisp"
:INDICES 262185)
1. NAME: SHELF
2. INITFORM: NIL
3. INITFUNCTION: #<FUNCTION (LAMBDA (&REST REST)
:IN
"SYS:SRC;CODE;FUNUTILS.LISP") {5374305B}>
4. INITARGS: (:SHELF)
5. %TYPE: T
6. %DOCUMENTATION: "Shelf"
7. %CLASS: #<MITO.DAO.TABLE:DAO-TABLE-CLASS OPENBOOKSTORE.MODELS:BOOK>
8. READERS: (SHELF)
9. WRITERS: ((SETF SHELF))
10. ALLOCATION: :INSTANCE
11. ALLOCATION-CLASS: NIL
12. COL-TYPE: (OR :NULL SHELF)
13. REFERENCES: NIL
14. PRIMARY-KEY: NIL
15. GHOST: T
16. INFLATE: "unbound"
17. DEFLATE: "unbound"
>
List of slot names with normal MOP:
(mapcar #'mopp:slot-definition-name slots)
(MITO.DAO.MIXIN::CREATED-AT MITO.DAO.MIXIN::UPDATED-AT MITO.DAO.MIXIN::SYNCED
MITO.DAO.MIXIN::ID DATASOURCE DETAILS-URL TITLE TITLE-ASCII ISBN PRICE
DATE-PUBLICATION PUBLISHER PUBLISHER-ASCII AUTHORS AUTHORS-ASCII SHELF
SHELF-ID COVER-URL REVIEW)
List of Mito slots from those names:
(mapcar (^ (name) (mito.class:find-slot-by-name 'book name))
'(MITO.DAO.MIXIN::ID title shelf))
(#<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS MITO.DAO.MIXIN::ID>
#<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:TITLE>
#<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::SHELF>)
Mito column types:
(mapcar #'mito.class:table-column-type *)
;; (:BIGSERIAL (:VARCHAR 128) SHELF)
but not (or null shelf) ?
|#
(defclass form ()
((model
:initarg :model
:initform nil
:accessor form-model
:documentation "Class table symbol. Eg: 'book")
(fields
:initarg :fields
:initform nil
:accessor fields
:documentation "List of field names to render in the form.")
(input-fields
:initform nil
:documentation "Hash-table. See the `input-fields' method.")
(exclude-fields
:initarg :exclude-fields
:initform nil
:documentation "List of field names to exclude. Better use the `exclude-fields' method.")
(search-fields
:initargs :search-fields
:initform '(title name)
:accessor search-fields
:documentation "List of fields to query when searching for records. Defaults to 'title and 'name, two often used field names. Overwrite them with the `search-fields' method.")
(target
:initarg :target
:initform "/admin/:table/create"
:documentation "The form URL POST target when creating a record.
Allows a :table placeholder to be replaced by the model name. Use with `form-target'.")
(view-record-target
:initarg :view-target
:initform "/admin/:table/:id"
:documentation "The form URL POST target to view a record.
Allows a :table and a :id placeholder. Use with `view-record-target'.")
(edit-target
:initarg :edit-target
:initform "/admin/:table/:id/edit"
:documentation "The form URL POST target when updating a record.
Allows a :table and a :id placeholder. Use with `edit-form-target'.")
(validators
:initargs :validators
:accessor validators
:documentation "Hash-table: key (field symbol) to a validator function.")))
#+openbookstore
(defclass book-form (form)
())
#+openbookstore
(defclass place-form (form)
())
;; => automatically create a <table>-form class for all tables.
#+openbookstore
(defparameter book-form (make-instance 'book-form :model 'book))
(defparameter *template-select-input* (djula:compile-template* "includes/select.html"))
(defparameter *template-admin-create-record* (djula:compile-template* "create_or_edit.html"))
(defmethod initialize-instance :after ((obj form) &key)
"Populate fields from the class name."
(when (slot-boundp obj 'model)
(with-slots (fields model) obj
(setf fields
;; Use direct slots.
;; If we get all slot names, we get MITO.DAO.MIXIN::SYNCED and the like.
;;TODO: exclude -ID fields.
;;(mito.class:table-column-type (mito.class:find-slot-by-name 'book 'shelf-id))
;; SHELF
;; => it's a table, so exclude shelf-id.
(mito-admin::class-direct-slot-names model)))))
(defgeneric exclude-fields (obj)
(:documentation "Return a list of fields (symbols) to exclude from the form. This method can be overriden. See also the form object :exclude-fields slot.")
(:method (obj)
(list)))
#+openbookstore
(defmethod exclude-fields (book-form)
"Return a list of field names (symbols) to exclude from the creation form."
'(title-ascii
publisher-ascii
authors-ascii
datasource
;; ongoing: handle relations
;; we need to exclude shelf, or we'll get an error on mito:insert-dao if the field is NIL.
;; shelf
shelf-id
shelf2-id
))
;; Do we want to get the search fields from a table name or a form class?
(defmethod search-fields (table)
'(title name))
#+openbookstore
(defmethod search-fields ((form book-form))
'(title))
#+openbookstore
(defmethod search-fields ((table (eql 'book)))
'(title authors-ascii))
(defgeneric form-fields (form)
(:documentation "Return a list of this form's fields, excluding the fields given in the constructor and in the `exclude-fields' method.")
(:method (form)
(with-slots (fields exclude-fields) form
;; set operations (set-difference) don't respect order.
(loop for field in fields
with exclude-list-1 = exclude-fields
with exclude-list-2 = (exclude-fields form)
unless (or (find field exclude-list-1)
(find field exclude-list-2))
collect field))))
#+(or)
(assert (equal 0 (mismatch
(form-fields (make-instance 'book-form :model 'book))
'(COVER-URL SHELF-ID SHELF AUTHORS PUBLISHER DATE-PUBLICATION PRICE ISBN TITLE DETAILS-URL))))
;;;
;;; How best define the input types/widgets ?
;;;
(defgeneric input-fields (form)
(:documentation "Define the fields' widgets. Return: a hash-table with key (field symbol name) and property list with keys: :widget, :validator…
Widgets are: :textarea, :datetime-local… TBC
Shall we infer the widgets more thoroughly?")
(:method (form)
(dict)))
(defun validate-ok (&optional it)
(declare (ignorable it))
(print "ok!"))
#+openbookstore
(defmethod input-fields ((form book-form))
;; Here we don't use another class to not bother with special :widget slots and a metaclass…
(dict 'review (list :widget :textarea :validator #'validate-ok)
'date-publication (list :widget :datetime-local)))
;; so, an "accessor":
(defun input-field-widget (form field)
(access:accesses (input-fields form) field :widget))
#+(or)
(input-field-widget (make-form 'book) 'review)
;; :TEXTAREA
;; section: define forms.
;; That's a second way to define form inputs isn't it?
;; We added field-input first, but it's to render HTML.
(defgeneric render-widget (form field widget &key name record)
(:documentation "Return HTML to render a widget given a form, a field name (symbol), a widget type (keyword).
The user simply chooses the widget type and doesn't write HTML.
NAME: the column type field (symbol). If \"shelf2\" refers to the \"shelf\" table, FIELD is \"shelf2\" and NAME must be \"shelf\".
See also `field-input'.")
(:method (form field widget &key name record)
(case widget
(:select
(let ((objects (mito:select-dao field)))
(log:info "caution: we expect ~a objects to have an ID and a NAME field" field)
(djula:render-template* *template-select-input* nil
:name (or name field)
:options objects
:record record
:selected-option-id (ignore-errors
(mito:object-id (slot-value record field)))
:empty-choice t
:empty-choice-label (format nil "-- choose a ~a… --"
(str:downcase field))
:label field
:select-id (format nil "~a-select" (str:downcase field)))))
(:textarea
(format nil "<div class=\"field\">
<label class=\"label\"> ~a </label>
<div class=\"control\">
<textarea name=\"~a\" class=\"input\" rows=\"5\">
~a
</textarea>
</div>
</div>" field field (if record (slot-value record field) "")))
(:datetime-local
(format nil "<div class=\"field\">
<label class=\"label\"> ~a </label>
<div class=\"control\">
<input type=\"datetime-local\" name=\"~a\" class=\"input\"> </input>
</div>
</div>" field field))
(t
(format nil "<div> todo for ~a </div>" field)))))
;;;
;;; end of input types/widgets experiment.
;;;
;;;
;;; section: let's continue and generate a form.
;;;
(defgeneric field-input (form field &key record errors value)
(:documentation "Return HTML for this field. It's important to have a name=\"FIELD\" for each input, so that they appear in POST parameters.
When a record is given, pre-fill the form inputs.
When an errors list is given, show them.
This is the method called by the form creation and edition. When we find a widget specified for a field, we call render-widget.
A user can subclass this method and return HTML or just set the widget type and let the default rendering.")
(:method (form field &key record errors value)
(declare (ignorable form))
(cond
((field-is-related-column (form-model form) field)
(log:info "render column for ~a" field)
(render-widget form (field-is-related-column (form-model form) field) :select
:name field
:record record))
((not (null (input-field-widget form field)))
(render-widget form field (input-field-widget form field)
:record record))
(t
(format nil "<div class=\"field\">
<label class=\"label\"> ~a </label>
<div class=\"control\">
<input name=\"~a\" class=\"input\" type=\"text\" ~a> </input>
</div>
~a
</div>"
field
field
(cond
(record
(format nil "value=\"~a\"" (slot-value? record field)))
(value
(format nil "value=\"~a\"" value))
(t
""))
;; XXX: use templates to render those fields. It gets messy with errors.
(if errors
(with-output-to-string (s)
(loop for error in errors
do (format s "<p class=\"help is-danger\"> ~a </p>" error)))
"")
)))))
;; We can override an input fields for a form & field name
;; by returning HTML.
#+openbookstore
(defmethod field-input ((form book-form) (field (eql 'shelf)) &key record errors value)
(let ((shelves (mito:select-dao field)))
(log:info record)
(djula:render-template* *template-select-input* nil
:name field
:options shelves
:selected-option-id (ignore-errors
(mito:object-id (shelf record)))
:record record
:empty-choice t
:empty-choice-label "-- choose a shelf… --"
:label "select a shelf"
:select-id "shelf-select")))
(defun collect-slot-inputs (form fields &key record)
(loop for field in fields
collect (list :name field
:html (field-input form field :record record))))
(defun make-form (table)
"From this table name, return a new form."
;; XXX: here, if the class <db model>-form (shelf-form) doesn't exist why not define
;; and create it?
(make-instance (alexandria:symbolicate (str:upcase table) "-" 'form)
:model (alexandria:symbolicate (str:upcase table))))
(defmethod form-target ((obj form))
"Format the POST URL.
Replace the :table placeholder by the model name."
(cond
((slot-boundp obj 'model)
(with-slots (target model) obj
(if (str:containsp ":table" target)
(str:replace-all ":table" (str:downcase model) target)
target)))
(t
"")))
(defmethod edit-form-target ((obj form) id)
"Return the POST URL of the edit form.
Replace the :table placeholder by the model name and the :id placeholder."
(cond
((slot-boundp obj 'model)
(with-slots (edit-target model) obj
(cond
((str:containsp ":table" edit-target)
(str:replace-using (list ":table" (str:downcase model)
":id" (string id))
edit-target))
(t
edit-target))))
(t
"")))
(defgeneric table-target (form)
(:documentation "/admin/:table/ URL to view a list of records of this table. ")
(:method (form)
(str:concat "/admin/" (str:downcase (slot-value? form 'model)) "/")))
(defgeneric view-record-target (form id)
(:documentation "/admin/:table/:id URL to view a record. ")
(:method ((obj form) id)
(cond
((slot-boundp obj 'model)
(with-slots (view-record-target model) obj
(cond
((str:containsp ":table" view-record-target)
(str:replace-using (list ":table" (str:downcase model)
":id" (princ-to-string id))
view-record-target))
(t
view-record-target))))
(t
""))))
;; Serve the form.
(defgeneric create-record (table)
(:method (table)
(let* ((form (make-form table))
(fields (form-fields form))
(inputs (collect-slot-inputs form fields)))
(log:info form (form-target form))
(djula:render-template* *template-admin-create-record* nil
:form form
:target (form-target form)
:fields fields
:inputs inputs
:table table
;; global display
:tables (tables))
)))
#|
Tryng out…
(defparameter params '(("NAME" . "new place")))
(cdr (assoc "NAME" params :test #'equal))
;; transform our "PARAM" names (strings) to symbols (to hopefully map our field names)
(defun params-symbols-alist (params)
(loop for (key . val) in params
collect (cons (alexandria:symbolicate key) val))
)
(params-symbols-alist params)
;; ((NAME . "new place"))
(defun params-keywords-alist (params)
(loop for (field . val) in params
collect (cons (alexandria:make-keyword field) val))
)
(params-keywords-alist (params-symbols-alist params))
((:NAME . "new place"))
(defun params-keywords (params)
(params-keywords-alist (params-symbols-alist params)))
`(make-instance 'place ,@(alexandria:flatten '((:NAME . "new place"))))
(MAKE-INSTANCE 'PLACE :NAME "new place")
ok!
|#
;;;
;;; section: Save
;;;
(defparameter *catch-errors* nil
"Set to T to not have the debugger on an error. We could use hunchentoot's *catch-errors*.")
(defun params-symbols-alist (params)
"Transform this alist of strings to an alist of symbols."
(loop for (field . val) in params
collect (cons (alexandria:symbolicate (str:upcase field)) val)))
#+(or)
(params-symbols-alist '(("NAME" . "test")))
;; ((NAME . "test"))
(defun params-keywords-alist (params)
(loop for (field . val) in params
collect (cons (alexandria:make-keyword field) val)))
(defun params-keywords (params)
(params-keywords-alist (params-symbols-alist params)))
#+(or)
(params-keywords '(("TITLE" . "test")))
;; ((:TITLE . "test"))
(defun cleanup-params-keywords (params-keywords)
"Remove null values."
(loop for (field . val) in params-keywords
if (not (null val))
collect (cons field val)))
#+(or)
(cleanup-params-keywords '((TEST . :yes) (FOO . NIL)))
;;((TEST . :YES))
(defun field-is-related-column (model field)
"The Mito table-column-type of this field (symbol) is a DB table (listed in our *tables*).
Return: field symbol or nil."
;; (let* ((slot (mito.class:find-slot-by-name 'book (alexandria:symbolicate (str:upcase field))))
(let* ((slot (mito.class:find-slot-by-name model (alexandria:symbolicate (str:upcase field))))
(column-type (and slot (mito.class:table-column-type slot))))
(log:info slot column-type (tables))
(find column-type (tables))))
#++
(field-is-related-column 'book 'shelf)
;; SHELF
#++
(assert
;; TODO: this was working with all symbols in the same package.
;; (alexandria:symbolicate 'cosmo-admin-demo::book)
;; => BOOK => we loose the package prefix.
;; but… the book creation form loads correctly O_o
;; Same for str:upcase.
(equal
(field-is-related-column 'cosmo-admin-demo::book 'cosmo-admin-demo::shelf)
'SHELF))
#++
(field-is-related-column 'book 'title)
;; NIL
(defun replace-related-objects (table params)
"If a parameter is a related column, find the object by its ID and put it in the PARAMS alist.
Change the alist in place.
This is done before the form validation.
PARAMS: alist of keywords (string) and values.
Return: params, modified."
(loop for (field . val) in params
;; for slot = (mito.class:find-slot-by-name 'book (alexandria:symbolicate (str:upcase field)))
for slot = (mito.class:find-slot-by-name table (alexandria:symbolicate (str:upcase field)))
for col = (and slot (mito.class:table-column-type slot))
for col-obj = nil
if (find col (tables))
do (if val
(progn
(setf col-obj (mito:find-dao col :id val))
(log:info "~a is a related column with value: ~s" field col-obj)
(if col-obj
(setf (cdr (assoc field params :test #'equal))
col-obj)
;; when col-obj is NIL, remove field from list.
;; Otherwise Mito tries to get the ID of an empty string.
(progn
(log:info "delete param ~a from the params list: it is a related object with no value." field)
(setf params (remove field params :test #'equal :key #'car)))))
;; The shelf value from the form can be NIL and not ""
;; (use cleanup-params-keywords to avoid).
(progn
(log:info "~a is NOT a related column: ~s" field col-obj)
(log:info "ignoring field with no value: " field)))
else
do
(log:info "ignoring column ~a, not found in (tables)" col))
params)
;TODO: test again with cosmo-admin-demo
#+test-openbookstore
(let ((params (replace-related-objects 'book '(("TITLE" . "test") ("SHELF" . "1")))))
;; => (("TITLE" . "test") ("SHELF" . #<SHELF 1 - Histoire>))
(assert (not (equal (cdr (assoc "SHELF" params :test #'equal))
"1"))))
#+test-openbookstore
(let ((params (replace-related-objects 'book '(("TITLE" . "test") ("SHELF" . NIL)))))
(assert params))
(defun merge-fields-and-params (fields params-alist)
(loop for field in fields
for field/value = (assoc field params-alist)
if field/value
collect field/value
else
collect `(,field . nil)))
;; ???: we dispatch on table (symbol), but we use a form object,
;; and we always create a new form object. Are the two useful?
(defgeneric save-record (table &key params record &allow-other-keys)
(:documentation "Process POST paramaters, create or edit a new record or return a form with errors.
Return a hash-table to tell the route what to do: render a template or redirect.")
(:method (table &key params record &allow-other-keys)
(log:info params)
(setf params (replace-related-objects table params))
(log:info "params with relations: ~a" params)
(let* ((form (make-form table))
(fields (form-fields form))
(inputs (collect-slot-inputs form fields))
(keywords (params-keywords params))
(params-symbols-alist (params-symbols-alist params))
;; help preserve order? nope.
(fields/values (merge-fields-and-params fields params-symbols-alist))
(record-provided (and record))
(model (slot-value form 'model))
(errors nil))
;;ONGOING: form validation…
;; (multiple-value-bind (status errors)
(multiple-value-bind (status inputs)
;; (validate-form form params-symbols-alist)
(validate-collect-slot-inputs form fields/values)
(unless status
(log:info status errors)
(return-from save-record
(dict
:status :error
:render (list *template-admin-create-record* nil
;; errors:
;; :errors errors
:errors (list "Invalid form. Please fix the errors below.")
:form form
:target (form-target form)
:fields fields
:inputs inputs
:table table
;; global display
:tables (tables))))
))
;; Create or update?
(cond
;; Create object, unless we are editing one.
((null record)
(handler-bind
((error (lambda (c)
;; Return our error when in development mode,
;; inside handler-bind so we have the full backtrace of what happened
;; before this point.
(unless *catch-errors*
(error c))
(log:error "create or update record error: " c)
(push (format nil "~a" c) errors))))
;; produce:
;; (MAKE-INSTANCE 'BOOK :TITLE "new title")
(setf record
(apply #'make-instance model
(alexandria:flatten
(cleanup-params-keywords keywords))))
))
;; Update
(t
(update-record-with-params record params-symbols-alist)))
(when errors
(return-from save-record
(dict
:status :error
;; list of keys to call djula:render-template*
:render (list *template-admin-create-record* nil
;; errors:
:form-errors errors
:form form
:target (form-target form)
:fields fields
:inputs inputs
:table table
;; global display
:tables (tables)))))
;; Save record.
(handler-case
(progn
(log:info "saving record in DB…" record)
(if record-provided
;; save (update)
(mito:save-dao record)
;; create new.
(mito:insert-dao record)))
(error (c)
;; dev
(unless *catch-errors*
(error c))
(push (format nil "~a" c) errors)))
(when errors
(return-from save-record
(dict
:status :error
:render (list *template-admin-create-record* nil
;; errors:
:errors errors
:form form
:target (form-target form)
:fields fields
:inputs inputs
:table table
;; global display
:tables (tables)))))
;; Success: redirect to the table view.
(values
(dict
:status :success
:redirect (if record
(view-record-target form (mito:object-id record))
(table-target form))
;; Use my messages.lisp helper?
:successes (list "record created"))
record)
)))
#+(or)
(save-record 'place :params '(("NAME" . "new place test")))
#+(or)
(save-record 'book :params '(("TITLE" . "new book")))
#|
This fails:
(apply #'make-instance 'book (alexandria:flatten
(params-keywords '(("REVIEW" . "") ("COVER-URL" . "")
("SHELF-ID" . "") ("SHELF" . "")
("AUTHORS" . "") ("PUBLISHER" . "") ("DATE-PUBLICATION" . "")
("PRICE" . "") ("ISBN" . "") ("TITLE" . "crud")
("DETAILS-URL" . "")))))
(mito:insert-dao *)
=> error: mito.dao.mixin::ID missing from object
=> exclude relational columns for now.
Works:
(apply #'make-instance 'book (alexandria:flatten
(params-keywords '(("REVIEW" . "") ("COVER-URL" . "")
;; ("SHELF-ID" . "")
;; ("SHELF" . "")
("AUTHORS" . "") ("PUBLISHER" . "") ("DATE-PUBLICATION" . "")
("PRICE" . "") ("ISBN" . "") ("TITLE" . "crud")
("DETAILS-URL" . "")))))
(mito:insert-dao *)
|#
;;;
;;; section: Edit
;;;
(defgeneric edit-record (table id)
(:documentation "Edit record with a pre-filled form.")
(:method (table id)
(let* ((form (make-form table))
(fields (form-fields form))
(record (mito:find-dao table :id id))
(inputs (collect-slot-inputs form fields :record record)))
(log:info form (form-target form))
(djula:render-template* *template-admin-create-record* nil
:form form
:target (edit-form-target form id)
:fields fields
:inputs inputs
:table table
;; global display
:tables (tables)))))
(defgeneric update-record-with-params (record params)
(:documentation "Update slots, don't save to DB.
RECORD: DB object. PARAMS: alist with key (symbol), val.")
(:method (record params)
(loop for (key . val) in params
unless (equal "ID" key) ;; just in case.
do (setf (slot-value record key) val))))
#+test-openbookstore
(let ((place (mito:find-dao 'place :id 2)))
(loop for (key . val) in '((NAME . "test place"))
do (setf (slot-value place key) val))
(describe place)
place)
| 27,462 | Common Lisp | .lisp | 652 | 32.342025 | 179 | 0.580721 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | b49b8835e2ce1c328fffb183fd1acfa0b1b34b085c20da64a0097183a4261b21 | 4,571 | [
-1
] |
4,572 | mito-admin-records.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-admin-records.lisp | (in-package :mito-admin)
;;; Functions to deal with single records.
;;; (more are in mito-forms)
(defparameter *admin-record* (djula:compile-template* "record.html"))
(defun url-parameter (name)
"Get Hunchentoot's parameter NAME if we are inside a web request, otherwise return NIL."
;; Helps accessing URL parameters from inside say render-record
;; without adding too many key arguments to the generic method.
;; So this should be used for optional parameters, like ?debug=t.
(if (boundp 'hunchentoot:*request*)
(hunchentoot:parameter name)
(log:debug "not inside a web request, cannot get parameter ~a" name)))
(defgeneric render-record (table id)
(:documentation "Render a record of id ID from TABLE to HTML. This method renders a Djula template.")
(:method (table id)
;; XXX: a little macro to abstract this.
(let* ((form (make-form table))
(record (mito:find-dao table :id id))
(raw (print-instance-slots record :stream nil))
;; (fields (collect-slots-values record))
;;TODO: we want to see created-at
(fields/values (collect-fields-values record (form-fields form)))
;; (rendered-fields (collect-rendered-slots record)))
(rendered-fields/values
(collect-rendered-fields-values record (form-fields form))))
;; Arf… a discovered Djula thingy. To call a function/method on an object,
;; like {{ record.print-record }}
;; we need to set Djula's execute package. It uses cl-user by default.
;; see https://github.com/mmontone/djula/issues/34
;; Here we need the app package to call the print-record method on the object.
;; For a book, this displays its title as the page header and page title.
(let ((djula:*djula-execute-package* *app-package*))
(djula:render-template* *admin-record* nil
:raw raw
;; :fields fields
:fields fields/values
;; :rendered-fields rendered-fields
:rendered-fields rendered-fields/values
:table table
:tables (tables)
:record record
:debug (url-parameter "debug")
))
)))
(defgeneric delete-record (table id &key params &allow-other-keys)
(:documentation "Delete record.
Return a hash-table to tell the route what to do: render a template or redirect.")
(:method (table id &key params &allow-other-keys)
(declare (ignorable params))
(log:info table id)
(handler-case
;; (let ((record (mito:find-dao table id)))
;; (unless record
;; (return-from delete-record
;; (dict :status :error
;; :message (format nil "The record of ID ~a doesn't exist." id)
;; :render (list *admin-table* nil
;; ;; errors:
;; :table table
;; ;; global display
;; :tables (tables))))))
(progn
;; This doesn't throw any error or warning on non-existing record?
(mito:delete-by-values table :id id)
(dict :status :success
:redirect (str:concat "/admin/" (str:downcase table))))
(error (c)
(log:error c)
(dict :status :error
:redirect (str:concat "/admin/" (str:downcase table)))))))
| 3,626 | Common Lisp | .lisp | 70 | 40.785714 | 103 | 0.571509 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 6e6e70a874c0c6ba019d36d0db36eba6115e9d85de0fe06d62cece983021a56c | 4,572 | [
-1
] |
4,573 | mito-admin-tables.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-admin-tables.lisp |
(in-package :mito-admin)
;; We have Mito *tables*
;; (BOOK PLACE PLACE-COPIES CONTACT CONTACT-COPIES BASKET BASKET-COPIES USER ROLE USER-ROLE ROLE-COPY SELL SOLD-CARDS SHELF PAYMENT-METHOD)
(djula:add-template-directory
(print (asdf:system-relative-pathname "mito-admin" "templates/")))
(defparameter *admin-index* (djula:compile-template* "index.html"))
(defparameter *admin-table* (djula:compile-template* "table.html"))
;;; We might want a admin-page class and instances, to set parameters:
;;; - show the search input on the table view?
;;; - action buttons (to do)
;;; - more settings.
(defparameter *tables* '(user)
"List of tables names to include in the admin dashboard. Override with the TABLES method.")
;; Specialize for an admin app?
(defgeneric tables ()
(:method ()
*tables*))
(defgeneric render-index ()
(:method ()
(djula:render-template* *admin-index* nil
:tables (tables))))
(defvar *pagination-template*)
(defun pagination-template ()
(unless (boundp '*pagination-template*)
(setf *pagination-template*
(asdf:system-relative-pathname :cosmo-pagination
"src/templates/pagination.html")))
*pagination-template*)
(djula:add-template-directory (asdf:system-relative-pathname :cosmo-pagination
"src/templates/"))
(defparameter *page-size* 50
"Default page size when listing records.")
(defun table-records (table &key (page 1) (page-size *page-size*))
(let ((offset (* (1- page) page-size)))
(mito:select-dao table
(sxql:order-by (:desc :created-at))
(sxql:limit page-size)
(sxql:offset offset))))
#+test-openbookstore
(progn
;; latest books
(table-records 'book)
;; older books:
(table-records 'book :page 2)
)
(defun href-format (base &key q)
"Return something like: /admin/book/search?q=foo&page=2
If no search query, no \"search?q\" part."
;; XXX: use a search URL and accessors on the table form.
(str:concat base
(if (str:non-blank-string-p q)
(format nil "/search?q=~a" q)
"?q=")))
#+test-openbookstore
(assert (equal (href-format "/admin/book" :q "foo")
"/admin/book/search?q=foo"))
(defgeneric render-table (table &key records search-value page page-size) ;; &key (order-by :desc))
(:method (table &key (records nil records-provided-p)
search-value
(page 1)
(page-size *page-size*))
;; Our Hunchentoot route ensures page and page-size are transformed to an integer.
;; The route always adds :page key params, so they can be null.
;; Set the default values there.
(let* ((records (if records-provided-p
records
(table-records table :page (or page 1)
:page-size (or page-size *page-size*))))
(count (if (str:non-blank-string-p search-value)
(count-records table search-value)
(mito:count-dao table)))
(pagination (cosmo/pagination:make-pagination
:href (href-format (format nil "/admin/~a" (str:downcase table))
:q search-value)
:page (or page 1)
:page-size (or page-size *page-size*)
:nb-elements count))
;; XXX: add our message utility.
;; (messages (bookshops.messages:get-message/status))
)
;; (log:info messages pagination)
(djula:render-template* *admin-table* nil
;; :messages messages
:table table
:search-value search-value
:tables (tables)
:records records
;; :pagination-template (pagination-template)
:pagination-template
(djula:render-template* (pagination-template) nil
:pagination pagination)
))))
| 4,270 | Common Lisp | .lisp | 92 | 34.152174 | 139 | 0.567444 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 9a5579d2d630faf83af77f79f30df363a7fcbed0a4faf5fec900cd0e6c73aae0 | 4,573 | [
-1
] |
4,574 | mito-validation.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-validation.lisp |
(in-package :mito-admin)
;;;
;;; This is were cl-forms seems good at.
;;;
#+(or)
;; do we want this?
;; Actually, we want to infer field types from mito types.
(defform book ()
((name
:constraints (list (clavier:not-blank))
:formatter #'identity)))
#+(or)
(clavier:not-blank)
;; aka (make-instance 'clavier::not-blank-validator)
;; then (clavier:validate * "")
;; => 2 values: NIL and error message: "Should not be blank"
(defgeneric validators (obj)
(:documentation "Return a hash-table of validators for this table's fields.")
(:method (obj)
(dict)))
#+openbookstore
(defmethod validators ((obj (eql 'place)))
(dict 'name (list (clavier:not-blank)
(clavier:len :max 200)
(clavier:len :min 2))))
#+(or)
(defparameter *validator* (clavier:||
(clavier:blank)
(clavier:&& (clavier:is-a-string)
(clavier:len :min 10)))
"Allow blank. When non blank validate.")
;; I want to simplify this to:
;;
;; (list :allow-blank (clavier:len :min 10))
;;
;; see https://github.com/mmontone/clavier/pull/10
;; moved to demo app:
;; (defmethod mito-admin::validators ((obj (eql 'book)))
;; (dict 'isbn (list :allow-blank
;; (clavier:len :min 10 :max 13
;; ;; :message works with clavier's commit of <2024-02-27>
;; ;; :message "an ISBN must be between 10 and 13 characters long"
;; ))
;; 'title (clavier:~= "test"
;; "this title is too common, please change it!")))
(defun field-validators (table field)
;; f**, access returns NIL,T ??
(uiop:ensure-list
(gethash field (validators table))))
#+test-openbookstore
(progn
;; Allow blanks:
(validate-field 'book 'isbn "")
;; if non blank, validate:
(validate-field 'book 'isbn "123")
)
(defun validate-all (validators object)
"Run all validators in turn. Return two values: the status (boolean), and a list of messages.
Allow a keyword validator: :allow-blank. Accepts a blank value. If not blank, validate."
;; I wanted this to be part of clavier, but well.
;; https://github.com/mmontone/clavier/pull/10
(let ((messages nil)
(valid t))
(loop for validator in validators
if (and (eql :allow-blank validator)
(str:blankp object))
return t
else
do (unless (symbolp validator)
(multiple-value-bind (status message)
(clavier:validate validator object :error-p nil)
(unless status
(setf valid nil))
(when message
(push message messages)))))
(values valid
(reverse (uiop:ensure-list messages)))))
(defgeneric validate-field (table field val)
(:documentation "Return two values: T if the field passes validation, a list of messages.")
(:method (table field val)
(validate-all (field-validators table field) val)))
#+test-openbookstore
(validate-field 'place 'name "rst")
(defgeneric validate-form (form field/values)
(:documentation "values: alist with field name (symbol) and its value.
We prefer to use `validate-collect-slot-inputs'.")
(:method (form field/values)
(let ((messages nil)
(ok t)
(table (slot-value form 'model)))
(loop for (field . value) in field/values
do (multiple-value-bind (status msgs)
(validate-field table field value)
(unless status
(setf ok nil)
;; (push (list :name field
;; :status "error"
;; :message (format nil "~a: ~a"
;; (str:downcase field)
;; msg))
;; messages)
(setf messages
(append msgs messages)))))
(values ok messages))))
#+test-openbookstore
(progn
;; ok:
(validate-form (make-form 'place) '((name . "test")))
;; name too short:
(validate-form (make-form 'place) '((name . "t")))
)
(defgeneric validate-collect-slot-inputs (form fields/values)
(:documentation "Return two values: t if all fields pass validation and a plist of field inputs. When the field isn't validated against the given input value, add an error message under the field input.")
(:method (form fields/values)
(let ((inputs nil)
(ok t)
(table (slot-value form 'model)))
(loop for (field . value) in fields/values
do (multiple-value-bind (status msgs)
(validate-field table field value)
(unless status
(setf ok nil))
(push (list :name field
:html (field-input form field :errors msgs :value value))
inputs)))
(values ok (reverse inputs)))))
#+(or)
;; Must return NIL and the HTML contain a validation error:
(validate-collect-slot-inputs (make-form 'place) '((name . "t")))
;; TODO: allow blank field and validate only if non blank.
| 5,307 | Common Lisp | .lisp | 130 | 32.930769 | 206 | 0.571373 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 70e0ae50603ff630ef3170f56e86b0dbea8c369ce497aacfd2e7a60308e6dbca | 4,574 | [
-1
] |
4,575 | mito-admin.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-admin.lisp | (in-package :mito-admin)
(defparameter *app-package* *package*
"The app package name.
It is necessary to register our app package, because many functions and methods manipulate symbols: in /admin/:table/:id, table is turned to the 'BOOK symbol, and this symbol exists in the application, not in mito-admin where the route is defined.")
(defun register-app (name)
;; We then use find-package.
(setf *app-package* name))
;; A class.
;; book
;;
;; (defclass person ()
;; ((name
;; :initarg :name
;; :accessor name)
;; (lisper
;; :initform nil
;; :accessor lisper)))
;;
;; Column types:
;;
;; :col-type (:varchar 128))
;; :col-type (or :null shelf)
;; An object.
#+openbookstore
(defparameter p (make-instance 'book :title "clos introspection" :price "10k"))
;; The object's class.
#+openbookstore
(defparameter p-class (class-of p))
;; or
#+openbookstore
(defparameter p-class (find-class 'book))
;; #<MITO.DAO.TABLE:DAO-TABLE-CLASS OPENBOOKSTORE.MODELS:BOOK>
;; The class direct slots.
#+openbookstore
(defparameter slots
(closer-mop:class-slots p-class)) ;; all slots, not only direct ones.
;; (#<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION MITO.DAO.MIXIN::CREATED-AT>
;; #<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION MITO.DAO.MIXIN::UPDATED-AT>
;; #<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION MITO.DAO.MIXIN::SYNCED>
;; #<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION MITO.DAO.MIXIN::ID>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::DATASOURCE>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:DETAILS-URL>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:TITLE>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::TITLE-ASCII>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:ISBN>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:PRICE>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:DATE-PUBLICATION>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:PUBLISHER>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::PUBLISHER-ASCII>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:AUTHORS>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::AUTHORS-ASCII>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::SHELF>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::SHELF-ID>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS:COVER-URL>
;; #<MITO.DAO.COLUMN:DAO-TABLE-COLUMN-CLASS OPENBOOKSTORE.MODELS::REVIEW>)
#+openbookstore
(defparameter slots *)
;; Get slot values.
(defun slot-name (slot-definition)
(sb-mop:slot-definition-name slot-definition))
#+(or)
(mapcar #'slot-name slots)
;; (DATASOURCE DETAILS-URL TITLE TITLE-ASCII ISBN PRICE DATE-PUBLICATION PUBLISHER
;; PUBLISHER-ASCII AUTHORS AUTHORS-ASCII SHELF SHELF-ID COVER-URL
;; REVIEW)
;; so:
(defun class-direct-slot-names (class)
"class: symbol or class object.
(class-direct-slot-names (class-of *book*))
=
(class-direct-slot-names 'book)"
(let ((class (if (symbolp class)
(find-class class)
class)))
(mapcar #'slot-name (mopp:class-direct-slots class))))
#+(or)
(class-slot-names 'book)
(export 'print-record)
(defgeneric print-record (o)
(:documentation "Pretty print this record for end-users. Used everywhere in the admin: list of search results, the view page, etc.
Example:
(defmethod print-record ((obj shelf))
(name obj))")
(:method (o)
(princ-to-string o)))
#+openbookstore
(defmethod print-record ((o book))
(or (title o)
;; and… just in case.
(princ-to-string o)))
#+openbookstore
(defmethod print-record ((o place))
(or (name o)
(princ-to-string o)))
#+openbookstore
(defmethod print-record ((o shelf))
(name o))
(defgeneric print-slot (o slot)
(:documentation "String representation of this object slot to be shown on the record view page.
It is usually the slot name, but in case of related columns, we need to return a string representing this column, instead of the unredeable object representation.
To render HTML, use `render-slot'.
Example:
(slot-value *some-book* 'shelf) ;; => #<SHELF 3 - Littérature>
but the object representation isn't good for a user-level view page, not considering the fact that the #<…> won't show up in some HTML. What we want is:
(print-slot *some-book* 'shelf) ;; => \"Littérature\"
Specialize methods for your database models like so:
(defmethod ((obj book) (slot (eql 'field-name)))
(when obj
(access:accesses obj slot 'related-field-name)))
Beware: this method is called by `slot-value?', so don't call it here.
note: we strip the #< and > parts of the object representation for now, let's see in usage.
")
(:method (o slot)
(when (and o (slot-boundp o slot))
(str:replace-using (list "#<" ""
">" "")
(princ-to-string
(slot-value o slot))))))
#+openbookstore
(defmethod print-slot (o (slot (eql 'shelf)))
(when o
(access:accesses o slot 'name)))
;; or simply use pprint for a class object?!
#+(or)
(print-slot (mito:find-dao 'book :id 109) 'shelf)
(defun slot-value? (o slot)
"o : class symbol or Mito record.
slot: slot-definition symbol or object (MOP)."
;; (log:info *package* o slot (slot-value o slot))
;; (log:info o) ;; silly. Without it we won't get the shelf.
;; (describe o)
(cond
((null o)
(error "slot-value? object should not be null"))
((and (symbolp slot)
;; (symbolp o) ;; I saw this called with a Mito object. Correct?
(field-is-related-column (if (symbolp o)
o
(type-of o)) ;; if book record, get 'book symbol.
slot))
(log:info "render column for ~a" slot)
(print-slot o slot))
;; that's just less natural to call:
;; (print-record (slot-value o slot)))
((and (symbolp slot)
(slot-boundp o slot))
(log:info "slot ~a is bound in ~a" slot o)
(slot-value o slot))
((not (symbolp slot))
(let ((name (slot-name slot)))
(log:info "last case: slot-boundp avec " o slot name)
(when (and name (slot-boundp o name))
(slot-value o name))))
(t
(error "slot-value? doesn't know how to deal with object ~a of type ~a and the slot ~a of type ~a" o (type-of o) slot (type-of slot)))))
#++
(slot-value? COSMO-ADMIN-DEMO::COOKBOOK 'COSMO-ADMIN-DEMO::shelf)
#++
(mapcar (^ (slot) (slot-value? p slot)) slots)
;; (NIL NIL "clos introspection" NIL NIL "10k" NIL NIL NIL NIL NIL NIL NIL NIL NIL)
(defun print-instance-slots (o &key (stream t))
(let* ((class (class-of o))
(slots (mopp:class-slots class)))
(loop for slot in slots
for name = (slot-name slot)
for val = (slot-value? o slot)
collect
(format stream "~s (~a) = ~s~&" name (type-of name) val))))
#+(or)
(print-instance-slots p)
;; MITO.DAO.MIXIN::CREATED-AT (SYMBOL) = NIL ;; <= don't print package.
;; MITO.DAO.MIXIN::UPDATED-AT (SYMBOL) = NIL
;; MITO.DAO.MIXIN::SYNCED (SYMBOL) = NIL
;; MITO.DAO.MIXIN::ID (SYMBOL) = NIL
;; DATASOURCE (SYMBOL) = NIL
;; DETAILS-URL (SYMBOL) = NIL
;; TITLE (SYMBOL) = "clos introspection"
;; TITLE-ASCII (SYMBOL) = NIL
;; ISBN (SYMBOL) = NIL
;; PRICE (SYMBOL) = "10k"
;; DATE-PUBLICATION (SYMBOL) = NIL
;; PUBLISHER (SYMBOL) = NIL
;; PUBLISHER-ASCII (SYMBOL) = NIL
;; AUTHORS (SYMBOL) = NIL
;; AUTHORS-ASCII (SYMBOL) = NIL
;; SHELF (SYMBOL) = NIL
;; SHELF-ID (SYMBOL) = NIL
;; COVER-URL (SYMBOL) = NIL
;; REVIEW (SYMBOL) = NIL
;; NIL
(defgeneric render-slot (object slot)
(:documentation "try it")
(:method (object slot)
(format nil " <div>~a</div>" (slot-value? object slot))))
;; (defmethod render-slot ((obj book) (slot (eql 'title)))
;; (format nil "<div> ~a </div>"
;; (if (slot-boundp obj slot)
;; (slot-value obj slot)
;; "")))
;; (defmethod render-slot ((obj book) (slot (eql 'cover-url)))
;; (let ((val (or (slot-value? obj slot)
;; "")))
;; (format nil "<a href=\"~a\"> ~a </a>" val val)))
;; (defun short-timestamp (date)
;; (local-time:format-timestring
;; nil date :format '(:year "/" (:month 2) "/" (:day 2) " " (:hour 2) ":" (:min 2))))
;; (defmethod render-slot ((obj book) (slot (eql 'mito.dao.mixin::created-at)))
;; (let ((val (or (slot-value? obj slot)
;; "")))
;; (short-timestamp val)))
;; (defmethod render-slot ((obj book) (slot (eql 'mito.dao.mixin::updated-at)))
;; (let ((val (or (slot-value? obj slot)
;; "")))
;; (short-timestamp val)))
;; (defmethod render-slot ((obj book) (slot (eql 'shelf)))
;; (let ((val (or (slot-value? obj slot)
;; "")))
;; (format nil "~a" val)))
#++
(render-slot p 'title)
;; DEPRECATED
(defun collect-rendered-slots (o)
(let* ((class (class-of o))
(slots (mopp:class-slots class)))
(loop for slot in slots
for name = (slot-name slot)
collect
(list :name name
:html (render-slot o name)))))
(defun collect-rendered-fields-values (o fields)
"Similar as `collect-fields-values', but renders the HTML of fields with `render-slot'."
(log:info "package " *package*)
(loop for field in fields
collect (list :name field
:html (render-slot o field))))
;; DEPRECATED
(defun collect-slots-values (o)
"Collect a plist of this record's slot names and values.
But this collects *all* slots. Use `collect-fields-values' instead that takes the list of fields, given by `form-fields'.
Thus, this function isn't useful to me anymore and is DEPRECATED."
(let* ((class (class-of o))
(slots (mopp:class-slots class)))
(loop for slot in slots
for name = (slot-name slot)
for val = (slot-value? o slot)
collect
(list :name name :value val))))
(defun collect-fields-values (o fields)
(loop for field in fields
collect (list :name field :value (slot-value? o field))))
(defgeneric render-input (obj slot)
(:method (obj slot)
(let ((name (str:downcase slot))
(val (if (slot-boundp obj slot)
(slot-value obj slot)
"")))
(format t "<label for=\"~a\"> ~a </label>
<input type=\"text\" placeholder=\"~a\"></input>" name name val))))
#++
(render-input p 'title)
#++
(mapcar (^ (slot) (render-input p (slot-name slot)))
slots)
;; Don't re-do cl-forms!
;; But it doesn't totally do what we need: automatic form, exclude some fields.
| 10,806 | Common Lisp | .lisp | 265 | 36.588679 | 251 | 0.646975 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | ef38a25477f5d7d7ee70033d023b49488d199e01c8fbf4da5ad96b484d271aba | 4,575 | [
-1
] |
4,576 | mito-admin-search.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-admin-search.lisp |
(in-package :mito-admin)
(defun join-query-by-% (q)
"Intersect \"%\" signs in the search query (string)
so the SQL search is non exact.
Example:
(join-query-by-% \"foo bar\")
;; => \"%foo%bar%\""
(if (str:non-blank-string-p q)
(str:concat "%" (str:join "%" (str:words q)) "%")
""))
#+test-openbookstore
(and
(assert (equal (join-query-by-% "foo")
"%foo%"))
(assert (equal (join-query-by-% "foo bar")
"%foo%bar%"))
(assert (equal (join-query-by-% "")
"")))
;; Example working query:
#++
(mito:select-dao 'book
(sxql:where
(:or
(:like 'title "%foo%")
(:like 'name "%foo%")))
(sxql:order-by (:desc :id)))
(defun %build-sxql-like-query (s fields)
"S: the SQL-ready search term, prepared from the search query.
FIELDS: list of field names (symbols or keywords).
Example: S is \"%foo%\"."
(loop for field in fields
collect `(:like ,field ,s)))
#++
(%build-sxql-like-query "%foo%" '(:title :name))
;; ((:LIKE :TITLE "%foo%") (:LIKE :NAME "%foo%"))
(defun %join-or (clauses)
"join list of clauses with a :OR.
Useful to join the clauses of a text query together, when we don't need
to join them with another filter."
`(:or
,@(loop for clause in clauses
collect clause)))
#++(%join-or (%build-sxql-like-query "%foo%" '(:title :name)))
;; (:OR (:LIKE :TITLE "%foo%") (:LIKE :NAME "%foo%"))
;; You don't imagine the time I needed to figure this out ;) (years ago as a Lisp newcomer, but still)
(defun select-query-by-fields (table q fields &key offset limit)
(let* ((order-by '(:desc :id))
(fields (uiop:ensure-list fields))
(search-field :name)
(sql-query (join-query-by-% q))
(records nil))
(mito:select-dao table
(sxql:where
(%join-or
(%build-sxql-like-query sql-query fields)))
(sxql:order-by order-by)
(when limit
(sxql:limit limit))
(when offset
(sxql:offset offset)))))
#++
(select-query-by-fields 'book "foo" '(title name))
;; (#<BOOK 121 - foo. SHELF: Histoire> #<BOOK 120 - foo. SHELF: NIL>)
;; #<SXQL-STATEMENT: SELECT * FROM book WHERE ((title LIKE '%foo%') OR (name LIKE '%foo%')) ORDER BY id DESC>
#+test-openbookstore
;; Searching for books with "lisp" in title should return results.
(assert (select-query-by-fields 'book "lisp" '(title name)))
(defparameter *page-size* 50) ;TODO: re-use other parameter.
(defgeneric search-records (table q &key page page-size)
(:documentation "Search records in TABLE by the query Q (string)")
(:method (table q &key page (page-size *page-size*))
(let* ((order-by '(:desc :id))
(search-field :name)
(sql-query (join-query-by-% q))
(offset (when page
(* (1- page) page-size)))
(records nil))
(print "searching…")
(setf records
(select-query-by-fields table q (search-fields table)
:offset offset
:limit page-size))
(log:info records)
records)))
(defun count-query-by-fields (table q fields)
"Build our lax search query across those fields, but count the result only."
;; mito:count-dao is too simple, doesn't allow to filter.
;; https://github.com/fukamachi/mito/issues/110
(let* ((order-by '(:desc :id))
(fields (uiop:ensure-list fields))
(sql-query (join-query-by-% q)))
(cadr (first
;; result is like ((:|COUNT(*)| 6))
(mito:retrieve-by-sql
(sxql:select ((:count :*))
(sxql:from table)
(sxql:where
(%join-or
(%build-sxql-like-query sql-query fields)))
(sxql:order-by order-by)))))))
#++
(progn
(count-query-by-fields 'book "foo" '(title name))
;; 0 result with an author search??
(count-query-by-fields 'book "sofocle" '(title name authors-ascii))
)
(defgeneric count-records (table q)
(:documentation "Filter results by the query Q and count the number of results.")
(:method (table q)
(count-query-by-fields table q (search-fields table))))
| 4,160 | Common Lisp | .lisp | 110 | 31.609091 | 109 | 0.59757 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 70d7b2e3f5f0aeaef15bb2d0d2239674443513b000c0c0bf4da1369301205871 | 4,576 | [
-1
] |
4,577 | mito-admin-routes.lisp | OpenBookStore_openbookstore/src/web/mito-admin/mito-admin-routes.lisp |
;; bug? lol
#+openbookstore
(defun openbookstore::render-index ()
(openbookstore.models::render-index))
(in-package :mito-admin)
(djula:def-filter :render-object-field (obj val)
(declare (ignorable obj val))
(format nil "hello"))
;; XXX: this filter shouldn't be needed.
;; In Djula templates we should be able to call methods like:
;; {{ record.print-record }}
;; but… doesn't work? => use *djula-execute-package*
;; This filter always works.
(djula:def-filter :print-record (obj)
(print-record obj))
(defmacro with-app (() &body body)
"Run BODY under our app registered with REGISTER-APP.
In other words, set the current *package* to our app's, so than we can reference its table symbols.
Indeed, our default routes are defined under mito-admin, our DB classes under our project package, and 'MITO-ADMIN:BOOK is not the same as 'MY-APP::BOOK."
;; The issue is manipulating symbols, in the mito-admin package,
;; that exist in another package/app.
;; Instead of alexandria:symbolicate we'd need (find-symbol "BOOK" *my-app-package*).
;; The crux of the issue is slot-value obj slot:
;; wether slot is 'book or cosmo-admin-demo::book is not the same.
`(let ((*package* (find-package *app-package*)))
(progn ,@body)))
(easy-routes:defroute route-admin-index ("/admin/" :method :get) ()
"Admin index: show our database tables and a simple dashboard."
(let ((*package* (find-package *app-package*)))
(with-app ()
(render-index))))
(easy-routes:defroute route-admin-table ("/admin/:table" :method :get)
(q (page :parameter-type 'integer) (page-size :parameter-type 'integer))
"List this table's records with pagination."
(with-app ()
(render-table (alexandria:symbolicate (str:upcase table))
:search-value q
:page page
:page-size page-size)))
(easy-routes:defroute route-admin-record ("/admin/:table/:id" :method :get) ()
"Show record."
(with-app ()
(if (str:blankp id)
;; Happens with /admin/book/
;; we should define a route with regexp and optional trailing /
(hunchentoot:redirect (easy-routes:genurl* 'route-admin-table :table table))
(render-record (print (alexandria:symbolicate (str:upcase table))) id))))
(easy-routes:defroute route-admin-record-create ("/admin/:table/create" :method :get) ()
"Create a record: show a form."
(with-app ()
(log:info *package*)
(create-record (alexandria:symbolicate (str:upcase table)))))
(easy-routes:defroute route-admin-record-create/post ("/admin/:table/create" :method :post) ()
"Create record (POST).
Return to the table view or display the same form with errors."
(with-app ()
(let ((action (save-record (alexandria:symbolicate (str:upcase table))
:params (hunchentoot:post-parameters*))))
(cond
((equal :error (access action :status))
(log:info "on error: return template…")
(apply #'djula:render-template* (access action :render)))
(t
(log:info "redirect…" action)
;; Does my messages helper work? nope
;; Does it in the session activated?
;; XXX: add our messages utility.
;; (mapcar #'bookshops.messages:add-message (access action :successes))
(hunchentoot:redirect (access action :redirect)))))))
(easy-routes:defroute route-admin-record-delete/post ("/admin/:table/:id/delete" :method :post)
()
"Delete record."
(with-app ()
(let ((action (delete-record (alexandria:symbolicate (str:upcase table))
id
:params (hunchentoot:post-parameters*))))
(cond
((equal :error (access action :status))
(hunchentoot:redirect (access action :redirect)))
(t
(log:info action)
;; Does my messages helper work? nope
;; Does it in the session activated?
;; XXX: add our messages utility.
;; (mapcar #'bookshops.messages:add-message (access action :messages))
(hunchentoot:redirect (access action :redirect)))))))
(easy-routes:defroute route-admin-record-edit ("/admin/:table/:id/edit" :method :get) ()
"Edit record: show a pre-filled form."
(with-app ()
(edit-record (alexandria:symbolicate (str:upcase table))
id)))
(easy-routes:defroute route-admin-record-edit/post ("/admin/:table/:id/edit" :method :post) ()
"Save edited record (POST)."
(log:info table id (hunchentoot:post-parameters*))
(with-app ()
(let* ((table (alexandria:symbolicate (str:upcase table)))
(record (mito:find-dao table :id id))
(action (save-record table
:params (hunchentoot:post-parameters*)
:record record)))
(cond
((equal :error (access action :status))
(log:info "edit: ")
;; why did I have redirect here?
;; (hunchentoot:redirect (access action :redirect)))
(apply #'djula:render-template* (access action :render)))
(t
(log:info "edit: redirect…" action)
;; Does my messages helper work? nope
;; Does it in the session activated?
;; XXX: add our messages utility.
;; (mapcar #'bookshops.messages:add-message (access action :messages))
(hunchentoot:redirect (or (access action :redirect)
(error "The URL to redirect to is null."))))))
))
;;;
;;; section: search
;;;
(easy-routes:defroute route-admin-table-search ("/admin/:table/search" :method :get)
(q (page :parameter-type 'integer) (page-size :parameter-type 'integer))
"Search records.
Search on the table or form `search-fields'."
(log:info "search! " q)
(with-app ()
(let* ((table (alexandria:symbolicate (str:upcase table)))
(records (search-records table q :page (or page 1) :page-size (or page-size *page-size*))))
(render-table table
:records records
:search-value q))))
(defun toggle-devel-profile (&optional (val nil val-p))
"Show Lisp errors in the browser."
;; XXX: do better.
(setf hunchentoot:*catch-errors-p* (if val-p val t))
(setf hunchentoot:*show-lisp-errors-p* (if val-p val t)))
#+(or)
(toggle-devel-profile nil)
| 6,340 | Common Lisp | .lisp | 136 | 39.426471 | 156 | 0.640531 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | ac3388c39211192aee17e74a65274160a6f69ff3a40025a7324526f3b7b2f719 | 4,577 | [
-1
] |
4,578 | blocks-search.lisp | OpenBookStore_openbookstore/src/web/weblocks-test/blocks-search.lisp | ;; (defpackage bookshops-weblocks
;; (:use #:cl
;; #:weblocks-ui/form
;; #:weblocks/html)
;; (:import-from #:weblocks/widget
;; #:render
;; #:update
;; #:defwidget)
;; (:import-from #:weblocks/actions
;; #:make-js-action)
;; (:import-from #:weblocks/app
;; #:defapp)
;; (:import-from #:weblocks-navigation-widget
;; #:defroutes))
(in-package :bookshops-weblocks)
(defwidget search-widget (weblocks-ui:ui-widget)
((results
:initarg :results
:initform nil
:accessor results)))
(defun make-search-widget ()
(make-instance 'search-widget))
(defwidget search-result-widget (weblocks-ui:ui-widget)
((result
:initarg :result
:initform nil
:accessor result)))
(defun data-search (search-widget query)
(let* ((results (bookshops:books query))
(results-widgets (loop for res in results
collect (make-instance 'search-result-widget :result res))))
(setf (results search-widget) results-widgets)
(update search-widget)))
(defmethod render ((widget search-widget))
(with-html
(:div :class "grid-container"
(with-html-form (:POST (lambda (&key query &allow-other-keys)
(data-search widget query)))
(:div :class "cell medium-9"
(:input :type "text"
:name "query"
:placeholder "Search")
(:input :type "submit"
:class "button"
:value "Search"))
(:div (loop for elt in (results widget)
do (with-html
(render elt))))))))
;TODO: doesn't save the result.
;function not called.
(defun save-book (result-widget)
"Save this book in the stock, aka add one copy to the default place."
(log:info "--- calling save-book with " result-widget)
(let ((book (result result-widget)))
(log:info "-- bookresult is" book) ;; not seen.
(openbookstore.models:add-to (openbookstore.models:default-place)
book)
(update result-widget)))
(defmethod render ((widget search-result-widget))
(let ((book (result widget)))
(with-html
(:div :class "grid-x"
(:div :class "cell medium-6"
(:div :class "cell medium-6" (openbookstore.models:title book))
(:div :class "cell medium-4" (openbookstore.models:authors book)))
(:div :class "cell medium-5"
(:div :class "cell medium-1" (openbookstore.models:price book) "€")
(:div :class "cell medium-2" "x" (openbookstore.models:quantity book)))
(with-html-form (:POST (lambda (&key query &allow-other-keys)
(declare (ignorable query))
;TODO:
;; function pas appellée
;; Quelle est l'URL du POST? retourne sur search/
(save-book widget)))
(:input :type "submit"
:class "button"
:title "Add 1 copy to your stock"
:value "Save"))))))
(defmacro defrun-test (name &body body)
`(progn
(defun ,name ()
,@body)
(funcall #',name)))
(defrun-test hello-test
(print "now testing…")
(assert (= 1 1)))
| 3,521 | Common Lisp | .lisp | 86 | 30.44186 | 89 | 0.531149 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | c39402caf8bcbcc27c955d22468069fb71edabf3eec445b2040bb9f0f97d8b4f | 4,578 | [
-1
] |
4,579 | blocks.lisp | OpenBookStore_openbookstore/src/web/weblocks-test/blocks.lisp | (defpackage bookshops-weblocks
(:use #:cl
#:weblocks-ui/form
#:weblocks/html)
(:import-from #:weblocks/widget
#:render
#:update
#:defwidget)
(:import-from #:weblocks/actions
#:make-js-action)
(:import-from #:weblocks/app
#:defapp)
(:import-from #:weblocks-navigation-widget
#:defroutes))
(in-package :bookshops-weblocks)
(defapp stock :prefix "/")
(weblocks/debug:on)
(defparameter *port* 8888)
(defroutes main-routes
("/stock/" (make-book-list-widget (openbookstore.models:find-book)))
("/search/" (make-search-widget))
("/" (weblocks/response:redirect "/stock/")))
(defwidget book-widget (weblocks-ui:ui-widget)
((book
:initarg :book
:initform nil
:accessor book)))
(defun make-book-widget (book)
(make-instance 'book-widget :book book))
(defun add-book (book-widget)
"Add one copy to the default place."
(let ((book (book book-widget)))
(openbookstore.models:add-to (openbookstore.models:default-place)
book)
(update book-widget)))
;; (defmethod render ((widget book-widget))
;; (log:debug "-- render book-widget")
;; (let ((book (book widget)))
;; (with-html
;; (:td (openbookstore.models:title book))
;; (:td (openbookstore.models:authors book))
;; (:td (openbookstore.models:price book) "€")
;; (:td (format nil "x ~a" (openbookstore.models:quantity book)))
;; (:td (with-html-form (:POST (lambda (&key &allow-other-keys)
;; (add-book widget)))
;; (:input :type "submit"
;; :title "Add 1 copy to your stock"
;; :value "+ 1"))))))
(defmethod render ((widget book-widget))
(let ((book (book widget)))
(with-html
(:div :class "grid-x"
(:div :class "cell medium-6"
(:div :class "cell medium-6" (openbookstore.models:title book))
(:div :class "cell medium-4" (openbookstore.models:authors book)))
(:div :class "cell medium-5"
(:div :class "cell medium-1" (openbookstore.models:price book) "€")
(:div :class "cell medium-2" "x" (openbookstore.models:quantity book)))
(with-html-form (:POST (lambda (&key &allow-other-keys)
(add-book widget)))
(:input :type "submit"
:class "button"
:title "Add 1 copy to your stock"
:value "+ 1"))))))
(defwidget book-list-widget ()
((books
:initarg :books
:initform nil
:accessor books)))
(defun stock-search (list-widget query)
(let* ((results (openbookstore.models:find-book :query query))
(book-widgets (mapcar #'make-book-widget results)))
(setf (books list-widget) book-widgets)
(update list-widget)))
(defmethod render ((widget book-list-widget))
(with-html
(with-html-form (:POST (lambda (&key query &allow-other-keys)
(stock-search widget query)))
(:div :class "cell medium-9"
(:input :type "text"
:name "query"
:placeholder "search title")
(:input :type "submit"
:class "button"
:value "Search"))
(:div :class "grid-container"
(loop for elt in (books widget)
do (with-html
(render elt)))))))
(defun make-book-list-widget (books)
(let ((widgets (mapcar #'make-book-widget books)))
(make-instance 'book-list-widget :books widgets)))
(defmethod weblocks/session:init ((app stock))
(declare (ignorable app))
(make-main-routes))
(defun start ()
;; (weblocks/server:start :port *port*))
;(setf weblocks/default-init::*welcome-screen-enabled* nil)
(unless mito::*connection*
(openbookstore.models:connect))
(restart-case
(weblocks/server:start :port *port*)
(connect-to-db ()
:report "Connect to the DB"
(openbookstore.models:connect))))
#+nil
(weblocks/debug:reset-latest-session)
| 4,177 | Common Lisp | .lisp | 107 | 30.934579 | 89 | 0.576267 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 1383402fd60941ae7c06206253b90eea99b06456a22231c3d6353146a362fd71 | 4,579 | [
-1
] |
4,580 | test-utils.lisp | OpenBookStore_openbookstore/tests/test-utils.lisp |
(defpackage bookshops-test.utils
(:use :cl)
(:import-from :openbookstore.models
:*db*
:*db-name*
:connect
:ensure-tables-exist
:migrate-all)
(:export :with-empty-db))
(in-package bookshops-test.utils)
(defun random-string (length)
;; thanks hacrm.
(let ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
(coerce (loop repeat length
collect (aref chars (random (length chars))))
'string)))
(defmacro with-empty-db (&body body)
"Run `body` with a new temporary DB."
`(let* ((*random-state* (make-random-state t))
(prefix (concatenate 'string
(random-string 8)
"/"))
(connection *db*))
(unwind-protect
(uiop:with-temporary-file (:pathname name :prefix prefix)
(let* ((*db-name* name))
(connect)
;; catch anything to always re-connect to our real db.
;XXX: a verbose or debug parameter would be nice.
;XXX: see *mito-migration-logger-stream* to use with
; with-sql-logging
;TODO: UNWIND-PROTECT
(with-output-to-string (s)
(let ((*standard-output* s))
(ensure-tables-exist)
(migrate-all)))
,@body))
;; (setf *db* (mito:connect-toplevel :sqlite3 :database-name db-name))
(connect))))
| 1,628 | Common Lisp | .lisp | 39 | 27.25641 | 92 | 0.503793 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 0e0fed0b2254a62e94472db8b99656792d6a5f989056110fc5669a9ce46a25b3 | 4,580 | [
-1
] |
4,581 | test-authentication.lisp | OpenBookStore_openbookstore/tests/test-authentication.lisp | (in-package #:bookshops-test)
(with-empty-db
(openbookstore.models:bootstrap-base-roles)
(let ((user
(openbookstore.models:create-user "Joe Blogg" "[email protected]" "secret")))
(openbookstore.models:add-role user :admin)
(assert (member :visitor (can:user-roles user))
nil "Visitor should be an inherited role for the admin role.")
(let ((login-attempt (openbookstore.models:login "[email protected]" "wrong")))
(assert (null login-attempt) nil "Should not have authenticated with wrong password"))
(let ((login-attempt (openbookstore.models:login "[email protected]" "secret")))
(assert (typep login-attempt 'openbookstore.models:user)
nil "login does not return the user when they login successfully"))))
| 786 | Common Lisp | .lisp | 13 | 54.230769 | 92 | 0.709845 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 69aba2f819ac8b08aa7493ce7f9f566110f844628032a17db7a705c36978905b | 4,581 | [
-1
] |
4,582 | test-bookshops.lisp | OpenBookStore_openbookstore/tests/test-bookshops.lisp | (defpackage bookshops-test
(:shadow :search)
(:use :cl
:bookshops
:openbookstore.models
:mito
:sxql
:prove
;; :parachute
)
(:import-from :bookshops-test.utils
:with-empty-db))
(in-package :bookshops-test)
(plan nil)
(subtest "Simple creation and access"
(let ((book (make-instance 'book :title "Antigone")))
(ok book "creation")
(is (title book) "Antigone" "title access"))
)
(defparameter *books* nil)
(defparameter *places* nil)
(defparameter *contacts* nil)
(defmacro with-fixtures (&body body)
"Create books and places."
`(progn
(setf *books* (list (create-book :title "title1"
:title-ascii "title1"
:authors "author1"
:authors-ascii "author1"
:isbn "9782710381419")
(create-book :title "title2"
:title-ascii "title2"
:authors "author2"
:authors-ascii "author2"
:isbn "9784567890123")))
;; contacts
(setf *contacts* (list (create-contact "first contact")))
;; places
(setf *places* (list (create-place "place 1")
(create-place "place 2")))
(log:info "--- fixture adding ~a of id ~a~&" (first *books*) (object-id (first *books*)))
(add-to (first *places*) (first *books*))
(add-to (second *places*) (second *books*) :quantity 2)
,@body))
(subtest "add to places"
;; Our fixtures work.
(with-empty-db
(with-fixtures
(is (quantity (first *books*))
1
"add-to")
(is (quantity (second *books*))
2
"add many")
(is (quantity (second *places*))
2
"quantity of books in a place"))))
(subtest "Creation and DB save"
(with-empty-db
(with-fixtures
(let ((bk (make-book :title "in-test")))
(log:info "~&-- qty book not saved: ~a~&" (quantity bk))
(save-book bk)
(log:info "~&-- qty: ~a~&" (quantity bk))
(is (quantity bk)
0
"book creation ok, quantity 0.")))))
(subtest "Add a book that already exists"
(with-empty-db
(with-fixtures
(let* ((bk (first *books*))
(same-bk (make-book :title "different title"
:isbn (isbn bk))))
(is (object-id (save-book same-bk))
(object-id bk)
"saving a book that already exists doesn't create a new one.")
))))
(subtest "Create a default place"
(with-empty-db
(is (type-of (default-place))
'openbookstore.models::place
"we create a default place if there is none.")))
(subtest "Deleting cards"
(with-empty-db
(with-fixtures
(is (count-dao 'place-copies)
2)
(delete-obj (first *books*))
(is (quantity (first *books*))
0)
(is (count-dao 'place-copies)
1
"deleting a book"))))
(subtest "Delete a place"
(with-empty-db
(with-fixtures
(delete-obj (first *places*))
(is 1 (count-dao 'place)
"deleting a place")
;; delete a list of objects
(delete-objects (append *books* *places*))
(is 0 (count-dao 'place))
(is 0 (count-dao 'book)
"deleting a list of objects"))))
(subtest "search books with permutations of keywords"
(with-empty-db
(with-fixtures
(let ((res (openbookstore.models:find-book :query "title1")))
(is (length res)
1
"search one keyword")
(is (title (first res))
"title1"
"titles match"))
(let ((res (openbookstore.models:find-book :query "title1 author1"))
(res2 (openbookstore.models:find-book :query "author1 title1"))
(res3 (openbookstore.models:find-book :query "title1 author2"))
(res4 (openbookstore.models:find-book :query "author2 title1"))
(res5 (openbookstore.models:find-book :query "titl"))
(res6 (openbookstore.models:find-book :query "titl author2")))
(is (length res)
1
"search with title + author")
(is (length res2)
1
"search with author + title")
(is (length res3)
0
"title1 + author2 gives no results")
(is (length res4)
0
"author2 + title1 gives no results")
(is (length res5)
2
"search common title")
(is (length res6)
1
"narrow keyword search by and-ing each keyword")))))
;; (finalize) ;; done in the last test file (test-contacts).
| 4,903 | Common Lisp | .lisp | 139 | 24.805755 | 94 | 0.525063 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | b1d5f35254786f32bfec764000221717ab557b083d493eb1e2a558e0157b9f7e | 4,582 | [
-1
] |
4,583 | test-contacts.lisp | OpenBookStore_openbookstore/tests/test-contacts.lisp | (in-package :bookshops-test)
(subtest "Create a contact"
;; Our fixtures work.
(with-empty-db
(is (object-id (create-contact "contact test"))
1
"create a contact")))
(subtest "Lend books, see loans"
(with-empty-db
(with-fixtures
(ok (lend (first *books*) (first *contacts*))
"Lend")
;; error:
;; (ok (loans)
;; "Loans")
)))
(finalize)
| 412 | Common Lisp | .lisp | 17 | 18.941176 | 51 | 0.568878 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 16e52dd0454a4eef8c1da2f57340c4c871dc55815a68239095a36e2020638cc0 | 4,583 | [
-1
] |
4,584 | openbookstore.asd | OpenBookStore_openbookstore/openbookstore.asd | #|
This file is part of the OpenBookstore project.
|#
(require "asdf") ;; for CI
(require "uiop") ;; for CI?
(require "cl+ssl")
(uiop:format! t "~&------- ASDF version: ~a~&" (asdf:asdf-version))
(uiop:format! t "~&------- UIOP version: ~a~&" uiop:*uiop-version*)
(asdf:defsystem "openbookstore"
:version "0.2"
:author "vindarel"
:license "GPL3"
:description "Free software for bookshops."
:homepage "https://gitlab.com/myopenbookstore/openbookstore/"
:bug-tracker "https://gitlab.com/myopenbookstore/openbookstore/-/issues/"
:source-control (:git "https://gitlab.com/myopenbookstore/openbookstore/")
:depends-on (
;; web client
:dexador
:plump
:lquery
:clss ;; might do with lquery only
;; DB
:mito
:dbd-sqlite3 ;; required for the binary (?)
:mito-auth
;; readline
:unix-opts
:replic
:cl-ansi-text
:parse-number
;; utils
:alexandria
:can
:function-cache ;; scrapers
:str
:local-time
:local-time-duration
:cl-ppcre
:parse-float
:serapeum
:log4cl
:trivial-backtrace
:deploy ;; must be a build dependency, but we also use deployed-p checks in our code.
:fiveam ;; dep of dep for build, required by deploy??
;; cache
:cacle
;; web app
:hunchentoot
:hunchentoot-errors ;; augment stacktrace with request data: params, headers…
:easy-routes
:djula
:djula-gettext
:cl-json
:cl-slug
:gettext
)
:components ((:module "src/datasources"
:components
((:file "dilicom")
(:file "dilicom-flat-text")
(:file "base-scraper")
(:file "scraper-fr")
(:file "scraper-argentina")
;; Depends on the above.
(:file "datasources")))
(:module "src"
:components
;; stand-alone packages.
((:file "parameters")
(:file "utils")
(:file "i18n")
(:file "termp")
;; they depend on the above.
(:file "packages")
(:file "authentication")
(:file "bookshops") ;; depends on src/web
(:file "database")))
(:module "src/models"
:components
((:file "shelves")
(:file "models")
(:file "models-utils")
(:file "baskets")
(:file "contacts")
(:file "sell")))
;; readline-based, terminal user-facing app (using REPLIC).
(:module "src/terminal"
:components
((:file "commands")
;; relies on the above:
(:file "manager")))
;; One-off utility "scripts" to work on the DB.
(:module "src/management"
:components
((:file "management")))
(:module "src/web"
:components
((:file "package")
(:file "messages")
(:file "authentication")
(:file "search")
(:file "pre-web")
(:file "web")
(:file "api")))
(:static-file "README.md")
;; Declare our templates to compile them in-memory, for delivery.
(:module "src/web/templates"
:components
;; Order is important: the ones that extend base.html
;; must be declared after it, because we compile all of them
;; at build time.
((:static-file "login.html")
(:static-file "404.html")
(:static-file "base.html")
(:static-file "dashboard.html")
(:static-file "history.html")
(:static-file "loans.html")
(:static-file "search.html")
(:static-file "stock.html")
(:static-file "sell.html")
(:static-file "receive.html")
(:static-file "card-edit.html")
(:static-file "card-stock.html")
(:static-file "card-page.html")
(:static-file "card-create.html")
(:static-file "permission-denied.html")
(:static-file "no-nav-base.html")))
;; Static files (JS, CSS)
(:module "src/static"
:components
((:static-file "openbookstore.js")
(:static-file "card-page.js"))))
;; :build-operation "program-op"
:entry-point "openbookstore:run"
:build-pathname "openbookstore"
;; For a .deb (with the two lines above).
;; :build-operation "linux-packaging:build-op"
;; With Deploy, ship foreign libraries (and ignore libssl).
:defsystem-depends-on (:deploy) ;; (ql:quickload "deploy") before
:build-operation "deploy-op" ;; instead of "program-op"
;; :long-description
;; #.(read-file-string
;; (subpathname *load-pathname* "README.md"))
:in-order-to ((test-op (test-op "bookshops-test"))))
;; Don't ship libssl, rely on the target OS'.
;; Needs to require or quickload cl+ssl before we can compile and load this .asd file? :S
#+linux (deploy:define-library cl+ssl::libssl :dont-deploy T)
#+linux (deploy:define-library cl+ssl::libcrypto :dont-deploy T)
;; Use compression: from 108M, 0.04s startup time to 24M, 0.37s.
#+sb-core-compression
(defmethod asdf:perform ((o asdf:image-op) (c asdf:system))
(uiop:dump-image (asdf:output-file o c) :executable t :compression t))
(asdf:defsystem "bookshops/gui"
:version "0.1.0"
:author "vindarel"
:license "GPL3"
:depends-on (:bookshops
:nodgui)
:components ((:module "src/gui"
:components
((:file "gui"))))
:build-operation "program-op"
:build-pathname "bookshops-gui"
:entry-point "bookshops.gui:main"
:description "Simple graphical user interface to manage one's books."
;; :long-description
;; #.(read-file-string
;; (subpathname *load-pathname* "README.md"))
:in-order-to ((test-op (test-op "bookshops-test"))))
;; Now ASDF wants to update itself and crashes.
;; On the target host, when we run the binary, yes. Damn!
;; Thanks again to Shinmera.
(deploy:define-hook (:deploy asdf) (directory)
(declare (ignorable directory))
#+asdf (asdf:clear-source-registry)
#+asdf (defun asdf:upgrade-asdf () nil))
| 7,519 | Common Lisp | .asd | 177 | 27.40678 | 100 | 0.479962 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 1cb2fdd900d03899e6fc37588bacf500f6cb82e3f6342e0761377951c4bf46d6 | 4,584 | [
-1
] |
4,585 | bookshops-test.asd | OpenBookStore_openbookstore/bookshops-test.asd | #|
This file is a part of bookshops project.
|#
(asdf:defsystem "bookshops-test"
:author "vindarel"
:license "GPL3"
:depends-on ("openbookstore"
"prove"
"mito"
"sxql"
"parachute")
:components ((:module "tests"
:components
((:file "test-utils")
(:file "test-bookshops")
(:file "test-contacts")
(:file "test-authentication"))))
:description "Test system for OpenBookstore"
;; :perform (test-op (op c) (symbol-call :prove-asdf :run-test-system c))
)
| 608 | Common Lisp | .asd | 20 | 21.35 | 75 | 0.53413 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 35a8e11992fa3427afd099c31cd1d734d6a631743cba998dfbd829fcc829ce75 | 4,585 | [
-1
] |
4,586 | themes-clil.csv | OpenBookStore_openbookstore/src/datasources/themes-clil.csv | 3000;;;;SCOLAIRE
;3001;;;Pré-scolaire et primaire
;;3002;;Pré-scolaire et maternelle
;;3003;;Élémentaire
;3004;;;Manuels scolaires Secondaire Général
;;3005;;Collège
;;3006;;Lycée général
;3007;;;Manuels scolaires Secondaire Technique et professionnel
;;3008;;Lycée professionnel, Bac professionnel (4e/3e technologique, CAP, BEP...)
;;3009;;Lycée technologique, Bac technologique
;3010;;;Manuels scolaires Supérieur Technique
;;3011;;Brevet de Technicien Supérieur (BTS)
;;3012;;Diplôme Universitaire de Technologie (DUT)
;4271;;;Classes préparatoires aux grandes écoles (CPGE)
3013;;;;PARASCOLAIRE
;3014;;;Cahier de vacances
;;3015;;Maternelle
;;3016;;Primaire
;;3017;;Collège
;;3018;;Lycée
;3019;;;Cahier de soutien
;;3020;;Maternelle
;;3021;;Élémentaire
;;3022;;Collège
;;3023;;Lycée
;3024;;;Préparation aux examens
;;3025;;Préparation au Brevet des collèges
;;3026;;Préparation au Baccalauréat général
;;3027;;Préparation au Baccalauréat professionnel et technique
;;4157;;Préparation aux CAP
;;4158;;Préparation aux BTS
;;4159;;Préparation aux examens de l’enseignement supérieur
;3028;;;Annales
;;3029;;Annales Brevet des collèges
;;3030;;Annales Baccalauréat général
;;3031;;Annales Baccalauréat professionnel et technique
;3032;;;Ouvrage de référence
;;3033;;Mémentos, aide-mémoires, méthodes de français
;;;4137;Grammaire
;;;4138;Orthographe
;;;4139;Conjugaison
;;;4140;Vocabulaire et expression
;;3034;;Mémentos, aide-mémoires et méthodes de langues étrangères
;;3035;;Mémentos, aide-mémoires, méthodes hors langues
;;3036;;Atlas parascolaire
;3037;;;Formation pour adultes
;3038;;;Classiques pédagogiques
;;4141;;Œuvre commentée
;;4142;;Analyse d'œuvre
;3039;;;Pédagogie et formation des enseignants
;;3040;;Didactique, pédagogie
;;3041;;Matériel éducatif pour la maternelle
;;3042;;Supports pédagogiques pour le niveau élémentaire
;;3043;;Supports et ouvrages pédagogiques liés aux programmes Collège et Lycée ou à la Formation continue
;;3044;;Éducation Nationale : concours, carrières
;;3045;;Revues pédagogiques, Revues des professeurs
;3046;;;Orientation, Préparation aux concours
;;3047;;Études, Orientation, Métiers
;;3048;;Concours administratifs
;;3049;;Préparation aux autres concours et examens
;3050;;;Français Langue Étrangère
3051;;;;SCIENCES FONDAMENTALES
;4050;;;Histoire des sciences
;4130;;;Biographie et autobiographie : science et technologie
;3052;;;Mathématiques
;;3053;;Algèbre
;;3054;;Analyse
;;3055;;Géométrie
;;3056;;Probabilités et statistiques
;3057;;;Informatique théorique, Mathématiques discrètes
;3058;;;Physique
;3059;;;Chimie
;;3060;;Biochimie
;;3061;;Chimie analytique
;;3062;;Chimie organique
;;3063;;Chimie minérale (inorganique)
;;3064;;Chimie expérimentale
;3065;;;Sciences de la vie
;;4042;;Biologie
;;4041;;Botanique
;;4092;;Ecologie
;;4043;;Microbiologie
;;4044;;Zoologie
;3066;;;Astronomie
;3067;;;Sciences de la terre (géologie, climatologie, hydrologie...)
;3068;;;Paléontologie
;4117;;;Archéologie
;4118;;;Ethique des sciences et des technologies
;4119;;;Astrophysique
;4120;;;Electromagnétisme
;4121;;;Thermodynamique
;4122;;;Physique quantique
;4123;;;Théorie de la relativité
;4124;;;Neurosciences
3069;;;;TECHNIQUES ET SCIENCES APPLIQUÉES
;3070;;;Agriculture
;3071;;;Génie civil
;3072;;;Électronique
;3073;;;Mécanique
;3074;;;Sciences et techniques industrielles
;3075;;;Bâtiment
;3076;;;Architecture, Urbanisme
;3077;;;Graphisme et image
;3078;;;Optique
;3079;;;Énergies
3080;;;;SCIENCES HUMAINES ET SOCIALES, LETTRES
;3081;;;Sciences sociales
;;3082;;Changement social
;;3083;;Classes sociales et stratification
;;3084;;Diversités, Discriminations
;;3085;;Addiction
;;3086;;Exclusion et pauvreté
;;3087;;Sociologie du genre
;;3088;;Générations
;;3089;;Histoire sociale
;;3090;;Inégalités
;;3091;;Migrations et immigrations
;;;4054;Démographie
;;3092;;Mobilités
;;3093;;Santé
;;3094;;Sexualité
;;3095;;Sociabilité
;;4093;;Sociologie
;;;3096;Sociologie de la famille
;;;3097;Sociologie des organisations
;;;3098;Sociologie des sciences
;;;3099;Sociologie du temps
;;;4096;Sociologie du sport
;;;4095;Sociologie du tourisme
;;;4094;Sociologie des transports
;3100;;;Action sociale, aide sociale
;;3101;;Accueil familial
;;3102;;Aide et protection de l'enfance
;;3103;;Conduites à risques
;;3104;;Travail social, intervention, animation, accompagnement
;;3105;;Public empêché, besoins spécifiques
;;3106;;Maladie
;;3107;;Vieillesse, action gérontologique
;;3108;;Protection sociale
;;3109;;Fragilité sociale
;;3110;;Solidarité, humanitaire
;3111;;;Anthropologie
;;3112;;Anthropologie physique et biologique
;;;3113;Homo sapiens
;;;3114;Primatologie comparée
;;;3115;Paléoanthropologie
;;3116;;Anthropologie sociale et culturelle
;;;3117;Théorie de l'évolution (évolutionnisme)
;;;3118;Homme et environnement
;;;3119;Anthropologie politique
;;;3120;Anthropologie des mondes contemporains
;;;3121;Anthropologie économique
;;4097;;Diasporas
;3122;;;Ethnologie
;;3123;;Les modèles et les codes sociaux
;;3124;;La parenté et les alliances
;;3125;;Aspects symboliques
;3126;;;Philosophie
;;3916;;Histoire de la philosophie
;;3127;;Philosophie antique
;;3128;;Philosophie médiévale (scolastique)
;;3129;;Philosophie moderne
;;;3130;Philosophie humaniste
;;;3131;Philosophe XVIIe siècle
;;;3132;Philosophie des Lumières
;;3133;;Philosophie contemporaine
;;4125;;Esthétique et philosophie de l'art
;;4126;;Métaphysique et ontologie
;;4127;;Philosophie éthique et politique
;;;4160;Bioéthique
;;4128;;Epistémologie, philosophie des sciences, logique
;3134;;;Psychologie
;;3135;;Psychologie générale
;;3136;;Psychologie du comportement (ou behaviorisme)
;;3137;;Psychologie cognitive
;;3138;;Psychologie du développement
;;3139;;Psychopathologie
;;3140;;Psychologie sociale
;;3141;;Psychophysiologie
;;3142;;Psychologie évolutionniste
;;3143;;Psychologie de l'éducation
;;3144;;Psychologie de l'apprentissage
;;3145;;Psychologie animale (ou éthologie)
;3918;;;Psychanalyse
;3146;;;Lettres et Sciences du langage
;;4024;;Lettres
;;;4025;Méthodologie
;;;4053;Théorie littéraire
;;;4027;Etudes littéraires générales et thématiques
;;;4028;Etudes de littérature comparée
;;4026;;Langue française
;;4029;;Langues régionales
;;4030;;Langues anciennes
;;;4031;Etudes de littérature grecque
;;;4032;Etudes de littérature latine
;;4033;;Langues étrangères
;;3147;;Linguistique, Sciences du langage
;;;3148;Théories et écoles linguistiques
;;;3149;Phonétique et phonologie
;;;3150;Morphologie et syntaxe
;;;3151;Lexicologie, pragmatique lexicale, sémantique
;;;3152;Linguistique diachronique (philologie)
;;;3153;Typologie linguistique
;;;3154;Stylistique et analyse du discours, esthétique
;;;3155;Sémiologie
;;;3156;Psycholinguistique
;;3157;;Sciences de l'information et de la communication
;;;3158;Théories de la communication
;;;3159;Économie, Production de l'information
;;;3160;Systèmes médiatiques, SIC et TIC
;;3161;;Sciences de l'éducation
;;3162;;Systèmes de formation et apprentissages : évaluation et modélisation
;;3163;;Perspectives sociocognitives, apprentissage et conduites sociales
;;3164;;Technologisation, formation, activités professionnelles
3165;;;;MÉDECINE, PHARMACIE, PARAMÉDICAL, MÉDECINE VÉTÉRINAIRE
;3166;;;Dictionnaire, Guide, Outil, Pratique
;3167;;;Histoire de la médecine
;3168;;;Sciences fondamentales
;3169;;;Spécialités médicales
;3170;;;Imagerie médicale
;3171;;;Pharmacie
;3172;;;Dentaire, Odontostomatologie
;3173;;;Neurologie, Psychiatrie
;3174;;;Paramédical, Médico-social, Aide-soignant, Infirmier
;3175;;;Médecine Vétérinaire
;3176;;;Revues médicales, Revues paramédicales
;4161;;;Éthique médicale
3177;;;;MANAGEMENT, GESTION ET ÉCONOMIE D'ENTREPRISE
;3178;;;Entreprise
;3179;;;Création d'entreprise
;3180;;;Comptabilité, expertise comptable, contrôle de gestion
;3181;;;Finance
;;3182;;Finance d'entreprise
;;3183;;Finance de marchés
;3184;;;Gestion industrielle
;3185;;;Méthodologie et gestion de projets
;3186;;;Management
;3929;;;Communication
;3187;;;Marketing
;3188;;;Production
;3189;;;Ressources humaines
;3190;;;Stratégie
;3191;;;Commerce international
;3192;;;Développement durable, écologie
;3930;;;Recherche et développement (R&D)
;4143;;;Vente
3193;;;;INFORMATIQUE
;3194;;;Théorie
;3195;;;Hardware et matériels
;;3196;;Architecture des ordinateurs
;;3197;;Périphériques
;3198;;;Graphisme
;;3199;;PAO
;;3200;;CAO
;;3201;;DAO - Retouche d'images
;;3202;;3D
;;3203;;Modélisation
;3204;;;Web (logiciel e-commerce, CMS, blog, réseaux sociaux...)
;;3205;;Réseaux sociaux, Blog
;;3206;;CMS
;;3207;;E-Commerce
;;3208;;CSS, Design web
;;3209;;SEO, Web analytics
;3210;;;Audio, Vidéo
;;3211;;Audio
;;3212;;Vidéo
;3213;;;Informatique d'entreprise
;;3214;;Conduite de projet
;;3215;;Gestion des sources
;;3216;;Stockage et archivage de données
;;3217;;Entrepôt de données
;;3218;;Management des systèmes d'information
;;3219;;Messagerie d'entreprise
;3220;;;Informatique personnelle
;;3221;;Systèmes d'exploitation
;;3222;;Bureautique
;;3223;;Internet (gestion de la messagerie, navigateur...)
;;3224;;Réseaux
;3225;;;Programmation et développement
;;3226;;Assembleur
;;3227;;HTML
;;3228;;Java - J2EE
;;3229;;Javascript
;;3230;;Langages C (C, C++, C#, Objective-C)
;;3231;;Python
;;3232;;Ruby
;;3233;;Modélisation et génie logiciel
;;3234;;PERL
;;3235;;PHP
;;3236;;Shell
;;3237;;Visual Basic
;3238;;;Réseaux et Télécommunications
;;3239;;Équipements réseaux
;;3240;;Généralités Réseaux
;;3241;;Protocoles et standards
;;3242;;Réseaux sans fil et télécommunications mobiles
;3243;;;Système
;;3244;;Généralités système
;;3245;;Unix - Linux
;;3246;;MacOS
;;3247;;Windows
;;3248;;Systèmes embarqués
;;3249;;Virtualisation
;;3250;;Systèmes mobiles (androïd...)
;3251;;;Données et Bases de données
;;3252;;Bases de données
;;3253;;Bases de données relationnelles
;;3254;;Bases de données non relationnelles
;;3255;;Data mining
;;3256;;XML
;;3257;;Indexation et moteurs de recherche
;3258;;;Sécurité
;;4066;;Protection de la vie privée et des données
;;4067;;Fraude et piratage informatique
;;4068;;Virus informatiques, chevaux de Troie et vers
;;4069;;Pare-feu
;;4070;;Spam
;;4072;;Cryptage des données
;;4071;;Spyware / logiciel espion
3259;;;;DROIT
;3260;;;Droit général
;;4272;;Professions du droit
;;;4273;Déontologie
;;4274;;Vocabulaire juridique
;;3261;;Introduction au droit
;;3262;;Histoire du droit
;;3263;;Théorie, philosophie et sociologie du droit
;;4098;;Droit comparé
;3264;;;Droit public
;;4099;;Libertés publiques - Droits de l'Homme
;;4100;;Droit des étrangers
;;4101;;Droit électoral
;;3265;;Droit constitutionnel
;;3266;;Droit administratif
;;3267;;Finances publiques
;;4275;;Droit de la régulation
;3271;;;Droit pénal et procédure pénale
;;4276;;Droit pénal
;;4277;;Procédure pénale
;3268;;;Droit privé
;;3269;;Droit civil
;;4278;;Procédure civile/ Droit de l’exécution/ Droit processuel
;;3270;;Droit des affaires et commercial
;;;4102;Droit de l'arbitrage
;;3272;;Droit de la propriété intellectuelle et industrielle
;;3273;;Droit social
;;3274;;Droit de la concurrence
;;3275;;Droit fiscal
;;3276;;Droit de la consommation
;;4073;;Droit du travail
;3277;;;Droit international
;;3278;;Droit international privé
;;3279;;Droit international public
;3280;;;Droit de l'Union européenne
;;3281;;Droit institutionnel de l'Union européenne
;;3282;;Droit matériel de l'Union européenne
;4103;;;Droit immobilier - Urbanisme - Construction
;4104;;;Droit environnement - Transport - Rural - Energie
;4105;;;Droit des médias et de l'information
;4106;;;Droit des associations et des fondations
;4107;;;Droit des assurances
;4108;;;Droit notarial
;4109;;;Droit de la santé - Droit médical
;4110;;;Droit du sport
;4111;;;Droit du tourisme
;4112;;;Droit de la culture
;4113;;;Droit de l'éducation
3283;;;;SCIENCES POLITIQUES
;3284;;;Histoire des idées politiques
;;3285;;Histoire des idées politiques jusqu'à la fin du XVIIe siècle
;;3286;;Histoire des idées politiques depuis le XVIIIe siècle
;;3287;;Vie politique française et européenne
;;3288;;Analyse des comportements politiques
;;3289;;Philosophie politique controverses contemporaines
;3290;;;Organisation de l'État et action publique
;;3291;;Institutions politiques françaises
;;3292;;Institutions administratives locales
;;3293;;Socialisation politique
;;3294;;Démocratie délibérative, participative
;;3295;;Élections, mobilisation électorale, campagnes
;;3296;;Construction européenne
;3297;;;Relations internationales
;;3298;;Relations internationales
;;3299;;Politique étrangère
;3300;;;Politique et pouvoir
;;3301;;Les forces armées, les forces de police
;;3302;;Le pouvoir judiciaire
;;3303;;Le pouvoir économique
;;3304;;Le pouvoir religieux et l'État
3305;;;;SCIENCES ÉCONOMIQUES
;3306;;;Économie de la mondialisation et du développement
;;3307;;Commerce international
;;3308;;Économie du développement
;;3309;;Économie géographique
;;3310;;Économie de l'environnement et des ressources naturelles
;;3311;;Économie de l'agriculture
;3312;;;Économie publique, économie du travail et inégalités
;;3313;;Économie du bonheur
;;3314;;Économie politique des institutions
;;3315;;Éducation
;;3317;;Patrimoine, revenu, redistribution
;;3318;;Santé
;;3319;;Travail, emploi et politiques sociales
;3320;;;Économie théorique et expérimentale
;;3321;;Comportements individuels
;;3322;;Économétrie
;;3323;;Économie expérimentale
;;3324;;Interaction des comportements
;;3325;;Microéconomie
;;3326;;Méthode quantitative
;;3327;;Théorie des jeux
;;3328;;Macroéconomie
;;3329;;Dynamique macroéconomique
;;3330;;Économie financière
;;3331;;Finance internationale
;;3332;;Macroéconomie et accumulation d'actifs
;;3333;;Marché du travail
;;3334;;Politiques monétaires et budgétaires
;3335;;;Marchés, risque et organisation
;;4114;;Bourse - Patrimoine
;;3336;;Organisation industrielle
;;3337;;Régulation de secteurs spécifiques (santé, enseignement, marchés de l'énergie, politique de l'environnement...)
;;3338;;Risques, marchés financiers et assurance
;;3339;;Structure de marché et politique de concurrence
;3340;;;Histoire économique
;;3341;;Histoire de la pensée économique
;;3342;;Accumulation et transmission de la richesse
;;3343;;Mobilité occupationnelle et géographique
;;3344;;Histoire des institutions et marchés monétaires et financiers
3345;;;;RELIGION
;3347;;;Christianisme
;;4048;;Textes bibliques
;;;4162;Ancien testament
;;;4163;Bibles
;;;4164;Evangiles et Nouveau Testament
;;;4165;Bibles pour enfants
;;4049;;Etudes bibliques
;;;4166;Introduction à la Bible
;;;4167;Histoire biblique
;;;4168;Dictionnaires et atlas bibliques
;;;4169;Exégèse et philologie biblique
;;4170;;Mysticisme
;;4171;;Œcuménisme
;;3359;;Spiritualité et témoignages chrétiens
;;3348;;Catholicisme
;;;4172;Fêtes et pratiques catholiques
;;;4173;Textes spirituels du catholicisme
;;;4174;Liturgies et prières
;;;4175;Textes du magistère
;;;3358;Saints et grands figures du catholicisme
;;;3361;Catéchèse jeunesse
;;;3362;Catéchuménat, catéchèse adulte
;;;4279;Préparation aux sacrements
;;3349;;Protestantisme
;;;4176;Fêtes et pratiques protestantes
;;;4177;Textes spirituels du protestantisme
;;;4178;Liturgies et prières
;;;4179;Grands figures du protestantisme
;;;4180;Catéchèse jeunesse
;;;4181;Catéchuménat, catéchèse adulte
;;3350;;Orthodoxie
;;;4182;Fêtes et pratiques orthodoxes
;;;4183;Textes spirituels de l'orthodoxie
;;;4184;Liturgies et prières
;;;4185;Textes du magistère
;;;4186;Saints et grandes figures de l'orthodoxie
;;;4187;Catéchèse jeunesse
;;;4188;Catéchuménat, catéchèse adulte
;;4046;;Théologie
;;;4189;Théologies médiévales
;;;4190;Théologies modernes (XVI-XVIII siècle)
;;;4191;Théologies contemporaines
;;;4192;Philosophie et théologie
;;;4193;Thèmes doctrinaux
;;4045;;Patristique
;;;4194;Pères du désert
;;;4195;Pères grecs
;;;4196;Pères latins
;;;4197;Pères orientaux
;;;4198;Patrologie
;;4199;;Monachisme
;3351;;;Islam
;;4200;;Fêtes et pratiques de l'islam
;;4201;;Coran
;;;4202;Etudes et commentaires coraniques
;;4203;;Prières et invocations
;;4204;;Philosophie
;;4205;;Hadith
;;4206;;Droit et jurisprudence
;;4207;;Grandes figures de l'islam
;;4208;;Prophètes
;;4209;;Courants de l'islam
;;;4210;Sunnisme
;;;4211;Chiismes
;;;4212;Soufisme
;3352;;;Judaïsme
;;4213;;Torah
;;;4214;Talmud et écrits talmudiques
;;;4215;Loi juive
;;4216;;Kabbale et autres textes spirituels
;;4217;;Liturgies et prières
;;4218;;Fêtes et pratiques du judaïsme
;;4219;;Enseignement du judaïsme
;;4220;;Grandes figures du judaïsme
;;4221;;Littérature rabbinique
;3353;;;Religions et sagesses orientales
;;3354;;Bouddhisme
;;;4222;Prières
;;;4223;Fêtes et pratiques du bouddhisme
;;;4224;Enseignement du bouddhisme
;;;4225;Textes spirituels du bouddhisme
;;;4226;Grands figures du bouddhisme
;;;4227;Bouddhisme ancien
;;;4228;Bouddhisme theravada
;;;4229;Bouddhisme mahayana
;;;4230;Bouddhisme tibétain (vajrayana)
;;3355;;Hindouisme
;;;4231;Prières
;;;4232;Fêtes et pratiques de l’hindouisme
;;;4233;Enseignement de l’hindouisme
;;;4234;Théologie de l’hindouisme
;;;4235;Textes spirituels de l’hindouisme
;;;4236;Grandes figures de l’hindouisme
;;4237;;Shintoïsme
;;;4238;Prières
;;;4239;Fêtes et pratiques du shintoïsme
;;;4240;Enseignement du shintoïsme
;;;4241;Textes spirituels du shintoïsme
;;;4242;Grandes figures du shintoïsme
;;4243;;Taoïsme
;;;4244;Prières
;;;4245;Fêtes et pratiques du taoïsme
;;;4246;Enseignement du taoïsme
;;;4247;Textes spirituels du taoïsme
;;;4248;Grandes figures du taoïsme
;;4249;;Confucianisme
;;;4250;Prières
;;;4251;Fêtes et pratiques du confucianisme
;;;4252;Enseignement du confucianisme
;;;4253;Textes spirituels du confucianisme
;;;4254;Grands figures du confucianisme
;4255;;;Polythéisme, spiritualité ethnique
;3917;;;Religions de l'Antiquité
;4064;;;Agnosticisme
;4256;;;Athéisme
;3356;;;Histoire des religions
;;4034;;Histoire du christianisme
;;;4257;Histoire du catholicisme
;;;4258;Histoire du protestantisme
;;;4259;Histoire de l’orthodoxie
;;4051;;Histoire de l'islam
;;4035;;Histoire du judaïsme
;;4260;;Histoire des religions orientales
;;;4261;Histoire du bouddhisme
;;;4262;Histoire de l'hindouisme
;3363;;;Jeunesse
;;4263;;Christianisme
;;4264;;Islam
;;4265;;Judaïsme
;;4266;;Religions orientales
;3364;;;Religion et société
;4267;;;Dialogue interreligieux
;4268;;;Religion comparée
;4269;;;Spiritualité, témoignages de sagesses
;4270;;;Méditations
3365;;;;ÉSOTÉRISME, OCCULTISME
;3366;;;Magie
;;3367;;Hermétisme, Alchimie
;;3368;;Ésotérisme
;;3369;;Sorcellerie
;;3370;;Symboles
;;3371;;Parapsychisme, Magnétisme, Guérisseurs
;;3372;;Art divinatoire
;3373;;;Énigme, Phénomène inexpliqué
;3374;;;Esprit, Paranormal
;3375;;;Sociétés secrètes
;3376;;;Croyance, Mythe, Rêve
3377;;;;HISTOIRE
;3378;;;Histoire générale et thématique
;;3379;;Personnages historiques
;;3380;;Documents historiques
;;3381;;Monde
;;4040;;Afrique
;;4037;;Amériques
;;4036;;Asie
;;4039;;Moyen-Orient
;;4038;;Océanie
;;3382;;Europe
;;3383;;France
;3384;;;Préhistoire
;3385;;;Antiquité
;3386;;;Moyen Age
;3387;;;Renaissance
;3388;;;Les Temps Modernes (avant 1799)
;3389;;;Histoire contemporaine (1799 - 1914)
;3390;;;Première Guerre Mondiale
;3391;;;Histoire de l'entre-deux guerres (1919-1939)
;3392;;;Deuxième Guerre Mondiale
;3393;;;Période 1945-1989
;3394;;;Histoire post-moderne (depuis 1989)
3395;;;;GÉOGRAPHIE
;3396;;;Géographie générale, thématique
;3397;;;Géographie régionale, géographie des territoires
;3398;;;Géographie physique, géo-système
;;3399;;Géomorphologie
;;3400;;Climatologie
;;3401;;Hydrologie
;;3402;;Biogéographie
;3403;;;Géographie humaine, écoumène
;;3404;;Géographie sociale
;;3405;;Géopolitique
;;3406;;Géographie de l'environnement
;;3407;;Géographie culturelle
;3408;;;Géographie mathématique
;;3409;;Techniques cartographiques
;;3410;;Photogrammétrie
;;3412;;Analyse spatiale
;3413;;;Techniques géographiques
;;3414;;Système d'information géographique, géomatique
;;3415;;Télédétection
;3416;;;Géographie quantitative, géostatistique
;3417;;;Géographie qualitative
3418;;;;OUVRAGES DE REFERENCE
;3419;;;Dictionnaires de français
;;3420;;Dictionnaires de français en un seul volume
;;3421;;Dictionnaires de français en plusieurs volumes
;;3422;;Dictionnaires généralistes
;;3423;;Dictionnaires de langage
;;3424;;Dictionnaires scolaires
;3425;;;Dictionnaires de langues étrangères
;;3426;;Dictionnaires de langues d'origine étrangère
;;3427;;Dictionnaires bilingues français/autres langues
;4078;;;Dictionnaires de sciences humaines
;3428;;;Encyclopédies générales
;;3429;;Encyclopédie générale en un seul volume
;;3430;;Encyclopédie générale en plusieurs volumes
;3431;;;Encyclopédies et dictionnaires thématiques
;;3432;;Encyclopédie et dictionnaire thématique en un seul volume
;;3433;;Encyclopédie et dictionnaire thématique en plusieurs volumes
;3434;;;Encyclopédies en fascicules
;3801;;;Ouvrages de documentation
;;4280;;Almanach
;;4281;;Annuaire
;;4282;;Catalogue éditeur
;;4283;;Bibliothéconomie
3435;;;;LITTÉRATURE GÉNÉRALE
;3436;;;Oeuvres classiques
;;3437;;Antiquité
;;3438;;Moyen Age
;;3439;;Moderne (avant 1799)
;;3440;;XIXe siècle
;;3441;;XXe siècle avant 1945
;3442;;;Romans
;;3443;;Romans francophones
;;3444;;Romans étrangers
;3445;;;Romans et nouvelles de genre
;;3446;;Romans d'aventures
;;3447;;Romans d'espionnage
;;3448;;Romans policiers
;;;3449;Policier historique
;;;3450;Policier procédural (type série les Experts)
;;;3451;Policier humoristique
;;3452;;Romans noirs
;;3453;;Thriller
;;;3454;Thriller psychologique
;;;3455;Thriller conspiration, politique, espionnage et militaire
;;;3456;Thriller médical et scientifique
;;;3457;Thriller juridique et financier
;;;3458;Thriller ésotérique
;;3459;;Romans d'amour, romans sentimentaux
;;;3460;Sentimental contemporain
;;;3461;Sentimental suspens
;;;3462;Sentimental historique
;;;3463;Sentimental paranormal, bit-lit
;;;3464;Comédie sentimentale
;;3465;;Chick-lit
;;3466;;Science-fiction
;;;3467;Fiction spéculative
;;;3468;Dystopie et Uchronie
;;;3469;Cyberpunk, technologique
;;;3504;Hard Science
;;;3470;Space Opéra et Planet Opéra
;;;3471;Militaire
;;;3472;Voyage dans le temps
;;;3473;Post-Apocalyptique
;;3474;;Fantastique, Terreur
;;;3475;Horreur, Terreur
;;;3476;Gothique
;;;3477;Créatures surnaturelles (vampire, zombie, fantôme, fée, etc.)
;;3478;;Fantasy, Merveilleux
;;;3479;Fantasy médiévale et arthurienne
;;;3480;Heroic fantasy
;;;3481;Fantasy épique
;;;3482;Fantasy humoristique
;;;3483;Dark Fantasy
;;;3484;Fantasy historique
;;;3485;Fantasy urbaine
;;;3486;Fantasy animalière
;;3487;;Romans érotiques
;;3488;;Romans humoristiques
;;3489;;Romans historiques
;;;3490;Préhistoire
;;;3491;Antiquité
;;;3492;Moyen Age
;;;3493;Moderne (avant 1799)
;;;3494;XIXe siècle
;;;3505;1914-1918
;;;3506;XXe siècle avant 1945
;;;3507;1939-1945
;3495;;;Contes et légendes
;;3496;;Contes et légendes du monde
;;3497;;Contes et légendes de France
;;3498;;Contes et légendes d'Europe
;;3499;;Contes et légendes Maghreb, Moyen-Orient
;;3500;;Contes et légendes d'Afrique
;;3501;;Contes et légendes d'Asie
;;3502;;Contes et légendes des Amériques
;;3503;;Contes et légendes d'Océanie
;3508;;;Romans régionaux, Terroir
;;3509;;Alsace, Lorraine
;;;3510;Alsace (Strasbourg, Colmar, Mulhouse)
;;;3511;Lorraine (Metz, Nancy)
;;3512;;Aquitaine
;;;3513;Béarn (Pau)
;;;3514;Gascogne
;;;3515;Guyenne (Bordeaux)
;;;3516;Navarre
;;;3517;Périgord
;;3518;;Auvergne
;;;3519;Bourbonnais (Moulins)
;;;3520;Livradois, Forez
;;;3521;Velay (Le Puy en Velay, Yssingeaux)
;;3522;;Normandie
;;;3523;Alençon
;;;3524;Perche
;;;3525;Pays d'Auge
;;;3526;Pays de Caux
;;3527;;Bourgogne
;;;3528;Chalonnais
;;;3529;Charolais
;;;3530;Mâconnais
;;;3531;Morvan
;;;3532;Nivernois (Nevers)
;;3533;;Bretagne
;;3534;;Centre, Val-de-Loire
;;;3535;Berry (Bourges)
;;;3536;Blésois
;;;3537;Chartrain
;;;3538;Drouais
;;;3539;Dunois
;;;3540;Orléanais
;;;3541;Sancerrois
;;;3542;Sologne
;;;3543;Touraine (Tours)
;;;3544;Val-de-Loire
;;3545;;Champagne, Ardennes
;;;3546;Givet
;;;3547;Mouzon
;;3548;;Corse
;;3549;;Franche-Comté
;;3550;;Paris, Ile-de-France
;;;3551;Paris
;;;3552;Ile-de-France
;;3553;;Languedoc, Roussillon
;;;3554;Cévennes
;;;3555;Gévaudan
;;;3556;Languedoc (Montpellier)
;;3557;;Nord, Pas de Calais, Picardie
;;;3558;Artois (Arras)
;;;3559;Flandre (Lille)
;;;3560;Picardie (Amiens)
;;3561;;Pays de la Loire
;;;3562;Anjou (Angers)
;;;3563;Maine et Perche (Le Mans)
;;;3564;Nantais
;;;3565;Vendée
;;3566;;Poitou-Charentes
;;;3567;Angoumois (Angoulême)
;;;3568;Aunis-et-Saintonge (La Rochelle)
;;;3569;Poitou (Poitiers)
;;3570;;PACA
;;;3571;Camargue
;;;3572;Luberon
;;;3573;Nice
;;;3574;Orange
;;;3575;Provence (Aix)
;;;3576;Riviera
;;;3577;Venaissin
;;3578;;Rhône-Alpes
;;;3579;Beaujolais
;;;3580;Bresse
;;;3581;Dauphiné (Grenoble)
;;;3582;Forez
;;;3583;Lyonnais (Lyon)
;;;3584;Mercantour
;;;3585;Savoie
;;;3586;Vivarais
;;3587;;Limousin
;;;3588;La Marche (Guéret)
;;;3589;Limousin (Limoges)
;;3590;;Midi-Pyrénées
;;;3591;Armagnac
;;;3592;Aubrac
;;;3593;Bigorre
;;;3594;Causses
;;;3595;Comminges
;;;3596;Couserans
;;;3597;Comté de Foix
;;;3598;Haut-Languedoc, Toulousain
;;;3599;Quercy
;;;3600;Lavedan
;;;3601;Rouergue
;;3602;;DOM-TOM, Outre-mer, Territoires français
;;;3603;Antilles françaises
;;;3604;Guyane
;;;3605;La Réunion
;;;3606;Nouvelle-Calédonie (Mélanésie)
;;;3607;Polynésie française, Wallis-et-Futuna
;;;3608;Saint-Pierre et Miquelon
;;;3609;TAAF (Terres australes antarctiques françaises)
;;3610;;Monaco
;;3611;;Benelux (Belgique, Pays-Bas, Luxembourg)
;;;3612;Brabant wallon
;;;3613;Flandres
;;;3614;Hainaut
;;;3615;Liège
;;;3616;Namur
;;;3617;Luxembourg
;;;3618;Pays-Bas
;;3619;;Provinces de Québec
;;3620;;Cantons de Suisse
;3621;;;Nouvelles
;3622;;;Théâtre
;;3623;;Tragédie
;;;3624;Tragédie antique
;;;3625;Tragédie classique
;;;4084;Dramaturgie contemporaine
;;3626;;Comédie
;;;4088;Comédie musicale
;;;3627;Comédie de caractères, de moeurs
;;;3628;Comédie ballet
;;;3629;Farce
;;;3630;Vaudeville
;;;4085;Comédie antique et classique
;;;4086;Comédie contemporaine
;;;4087;Sketch
;;;4089;Comédie dramatique
;;3631;;Tragi-comédie
;;3632;;Drame
;;4090;;Monologue
;3633;;;Poésie
;;3634;;Poésie lyrique (poésie chantée : ballade, élégie, rondeau...)
;;3635;;Poésie épique (épopée...)
;;3636;;Poésie satirique
;;3637;;Poésie didactique (fables...)
;;3638;;Poésie contemporaine
;3639;;;Art épistolaire, Correspondances, Discours
;3640;;;Récits de voyages
;3641;;;Récits
;3642;;;Pamphlets, Maximes, Pensées, Portraits
;3643;;;Essais littéraires
;3644;;;Actualités, Reportages
;;3645;;Société (culture, éducation, famille, mode, religion, sexualité)
;;3646;;Nature, écologie, climat, énergie, terre, agroalimentaire
;;3647;;Aventures, documentaires, exploration, voyages
;;3648;;Affaires, criminalité, enquêtes, justice, police
;;3649;;Médecine, santé, psychiatrie
;;3650;;Économie, Entreprise, Finance, Industrie
;;3651;;Sciences, Techniques (astronomie, biologie, physique, chimie...)
;;3652;;Média, Télévision, Presse, Radio, Edition, Internet
;;3653;;Sport
;;3654;;Musique
;;3655;;Cinéma
;;3656;;Théâtre
;;3657;;Spectacle, Danse
;;3658;;Politique
;3659;;;LGBT (lesbien, gay, bisexuel et transgenre)
;3660;;;Biographies, Mémoires
;;3661;;Autobiographies
;;3662;;Biographies
;;3663;;Journal intime
;;3664;;Mémoires
;;3665;;Témoignages
;3666;;;Humour
3667;;;;ARTS ET BEAUX LIVRES
;3668;;;Histoire de l'art, études
;;3669;;Histoire de l'art
;;3670;;Ecrits sur l'art
;;3671;;Essais biographiques
;;3672;;Dictionnaires d'histoire de l'art
;;3673;;Musées, muséologie
;;3674;;Marché de l'art
;;3675;;Revues sur l'art
;3676;;;Arts majeurs
;;3677;;Architecture, urbanisme
;;3678;;Sculpture
;;3679;;Peinture
;;;3680;Peintres, Monographie
;;;3681;Histoire de la peinture
;;3682;;Arts graphiques (dessin, estampes, fresques, graffiti, gravures...)
;;;3683;Dessin
;;;3684;Typographie, Calligraphie
;;;3685;Estampes
;;3686;;Arts du spectacle
;;3687;;Musique
;;;3934;Dictionnaire et guide de la musique
;;;3935;Méthode, formation musicale
;;;3936;Histoire de la musique
;;;3937;Instruments généralités
;;;4056;Instruments à clavier
;;;4057;Instruments à percussions
;;;4058;Instruments à cordes
;;;4059;Instruments à vent
;;;4060;Instruments mécaniques
;;;4061;Instruments électroniques
;;;3938;Musique classique
;;;3932;Chanson, variété française
;;;3939;Chanson, variété internationale
;;;3940;Pop
;;;3948;Rock
;;;3941;Reggae, dub
;;;3942;Electronique
;;;3933;Blues, jazz, soul
;;;3943;Country, folk
;;;3944;Hip hop, rap
;;;3945;Opéra
;;;3946;Musique de film, comédie musicale
;;;3947;Musique du monde
;;3688;;Poésie
;;3689;;Cinéma
;;3690;;Théâtre
;;3691;;Photographie
;;;3692;Essai sur la photographie
;;;3693;Histoire de la photographie
;;;3694;Monographies
;;;3695;Techniques photographiques
;;;3696;Vidéo
;3697;;;Arts décoratifs
;;3698;;Tapisseries, Tapis et Brocarts
;;3699;;Métal ciselé, Ferronnerie
;;3700;;Pierres fines et précieuses
;;3701;;Email
;;3702;;Sculpture (bois, ivoire, jade...)
;;3703;;Travail du verre et du cristal
;;3704;;Marqueterie
;;3705;;Céramique
;;3706;;Enluminure et miniatures
;;3707;;Mosaïque
;;3708;;Art floral
;;3709;;Design
;4055;;;Catalogues d'expositions
;3710;;;Beaux livres illustrés (histoire, nature, mode, transports...)
;;3711;;Histoire, Civilisation, Société
;;4131;;Sciences
;;3712;;Astronomie, Espace
;;3713;;Nature, Animaux
;;3714;;Transports (bateau, train, avion, auto, moto)
;;3715;;Mode, textile, parfums, bijoux, joaillerie, montres
;;3716;;Nu, Charme, Érotisme
;;3717;;Jardins et plantes
;;3718;;Lieux, paysage, pays, voyages
;;3719;;Littérature, poésie, manuscrit
;;3720;;Sports
;;3721;;Gastronomie
3722;;;;JEUNESSE
;3723;;;Éveil, petite enfance (- de 3 ans)
;;3724;;Tout-carton, imagier
;;3725;;Albums
;;3726;;Albums animés, pop-up
;;3727;;Livres objets, livre jouet, livre puzzle, livre surprise, livre matière
;3728;;;Livres illustrés (+ de 3 ans)
;;3729;;Premières histoires
;;3730;;Albums
;;3731;;Albums animés, pop-up
;;3732;;Livres objets, livre jouet, livre puzzle, livre surprise
;;3733;;Recueils (contes, fables...)
;3734;;;Livres d'activités
;;3735;;Activités manuelles
;;3736;;Activités artistiques
;;3737;;Activités d'extérieur
;3738;;;Livres et produits à usage unique
;;3739;;Autocollants, gommettes, collage
;;3740;;Coloriage, dessin
;;3741;;Images à coller (ayant une existence propre constituant une série, une collection)
;;3742;;Tatouage, transfert, magnet
;;3743;;Papeterie (dérivative d'une oeuvre jeunesse. Ex : calendriers, agendas...)
;3744;;;Fiction Jeunesse
;;3745;;Premières lectures, premiers romans
;;3746;;Histoires
;;3747;;Séries, héros préférés
;;3748;;Contes et mythologie
;;3749;;Romans
;3750;;;Fiction adolescents
;;3751;;Romans
;;;3752;Fantastique, Paranormal
;;;3753;Magie, Fantasy
;;;3754;Science-fiction
;;;3755;Sentimental
;;;4156;Chick-lit
;;;3756;Policier, thriller
;;;4074;Epouvante
;;;3757;Historique
;;;3758;Action, aventures
;;3759;;Témoignages
;3760;;;Documentaire / Encyclopédie
;;3761;;Animaux
;;3762;;Arts
;;3763;;Atlas
;;3764;;Encyclopédie
;;3765;;Géographie
;;3766;;Histoire, Monde et civilisations
;;3767;;Nature, environnement
;;3768;;Sciences
;;3769;;Sport
;;3770;;Vie quotidienne et société
3771;;;;BANDES DESSINÉES, COMICS, MANGAS
;3772;;;Bandes dessinées
;;3773;;Bandes dessinées tout public
;;3774;;Bandes dessinées de genre
;;;3776;Science-fiction
;;;3777;Fantasy
;;;3778;Fantastique, ésotérisme
;;;3779;Policier thriller
;;;4065;Horreur
;;;3780;Histoire
;;;3781;Action et aventures
;;;3782;Western
;;;3783;Humour
;;;3784;Bandes dessinées d'auteur
;;;3785;Public averti (érotique, hyper violence...)
;;3775;;Documentaire
;;;4132;Culture
;;;4133;Société
;;;4134;Littérature
;;;4135;Adaptation littéraire
;;;4136;Bande dessinée de savoir
;;4076;;Bandes dessinées d'auteur
;;4077;;Tirage de tête
;;4075;;Guides et critiques
;3786;;;Comics
;;3787;;Classique
;;3788;;Strip
;;3789;;Super Héros
;;3790;;Adaptation
;;3791;;Graphic Novel
;3792;;;Manga
;;3793;;Kodomo
;;3794;;Shôjo
;;3795;;Shonen
;;3796;;Seinen
;;3797;;Josei
;;4062;;Manga Yaoi
;;4063;;Manga Yuri
;;3798;;Public averti (érotique, hyper violence...)
;;3799;;Revues mangas
;;3800;;Guides mangas
3802;;;;PRATIQUE
;3803;;;Tourisme, Guides et Monographies
;;3804;;Guides de tourisme (destination)
;;;3805;Guide d'Europe
;;;3806;Guide d'Afrique
;;;3807;Guide du Moyen Orient
;;;3808;Guide d'Asie
;;;3809;Guide d'Amérique du Nord
;;;3810;Guide d'Amérique Centrale
;;;3811;Guide d'Amérique du Sud
;;;3812;Guide d'Océanie
;;;3813;Guides France
;;3814;;Guides de conversation
;;3815;;Guides spécialisés
;;;3816;Guides hébergement et restauration
;;;3817;Guides camping Caravaning
;;;3818;Guides de randonnées
;;;3819;Guides fluviaux ou maritimes
;;3820;;Albums et beaux livres et carnets de voyages (paysages, pays, villes, lieux, voyages)
;3821;;;Méthodes de langues (hors scolaire)
;3822;;;Vie professionnelle
;;3823;;Efficacité professionnelle
;;3824;;Recherche d'emploi
;3825;;;Santé et Bien-être (santé physique et mentale, hygiène, sexualité, psychologie, pédagogie, enfants)
;;3826;;Régimes alimentaires
;;3827;;Médecine naturelle, douce, familiale
;;3828;;Forme, beauté
;;3829;;Sexualité
;;3830;;Bien-être
;;3831;;Développement personnel
;;4047;;Vieillissement
;3832;;;Vie quotidienne, Vie de la famille
;;3833;;Enfance
;;3834;;Seniors
;;3835;;Maternité, puériculture
;;3836;;Éducation
;;3837;;Économie domestique
;;3838;;Gestion du patrimoine
;;4081;;Correspondance
;3839;;;Activités artistiques
;3840;;;Activités manuelles
;;3841;;Loisirs créatifs
;;3842;;Artisanat
;;3843;;Art du fil
;3844;;;Bricolage, décoration, habitat
;;3845;;Bricolage
;;;4021;Manuels de bricolage
;;;3931;Entretien, restauration de la maison
;;;3926;Cuisine et bains
;;;3925;Electricité, domotique, sécurité, alarmes
;;;3927;Plomberie, chauffage, climatisation
;;;4022;Maçonnerie
;;;4023;Menuiserie
;;3846;;Décoration
;;3928;;Habitat
;3847;;;Cuisine, gastronomie
;;4080;;histoire de la cuisine
;;3848;;Cuisine au quotidien
;;3849;;Cuisine actuelle et tendances
;;3850;;Cuisine de saison
;;3851;;Cuisine régionale
;;3852;;Cuisine du monde
;;3853;;Cuisine des chefs
;;4079;;Cuisine bio
;;3854;;Cuisine pour les enfants
;;3855;;Cuisine santé-minceur
;;3856;;Pâtisserie, confiserie, chocolat
;3857;;;Boissons
;;3858;;Vins, champagne
;;3859;;Alcools
;;3860;;Cocktails
;;3861;;Thé, café, infusions
;;3862;;Boissons non alcoolisées (jus, smoothies, milk-shake...)
;3864;;;Sports et loisirs
;;3920;;Sports collectifs
;;;3921;Football
;;;3949;Rugby
;;;3950;Hand-ball
;;;3951;Volley-ball
;;;3952;Basket-ball
;;;3953;Base-ball
;;;3954;Hockey
;;;3955;Polo
;;;4012;Pelote basque
;;3956;;Athlétisme
;;3957;;Gymnastique
;;3958;;Tir sportif
;;;3959;Carabine, pistolet
;;;3960;Arc, arbalète
;;3961;;Sport de combat
;;;3962;Boxe
;;;3963;Lutte
;;;3964;Escrime
;;3965;;Art martial
;;;3966;Aïkido
;;;3967;Judo
;;;3968;Ju-jitsu
;;;3969;Karaté
;;;3970;Kendo
;;;3971;Kung-fu
;;;3972;Free fight
;;;3973;Sumo
;;3974;;Sports mécaniques
;;;3975;Course automobile
;;;3976;Rallye automobile
;;;3977;Karting
;;;3978;Dragster
;;;3979;Camion
;;;3980;Course de moto
;;;3981;Tout terrain moto
;;;3982;Sports aériens
;;;3983;Sport de navigation
;;3984;;Sports aériens non motorisés
;;3985;;Cyclisme, vélo tout terrain (VTT)
;;;3986;Cyclisme
;;;3987;Cyclo-cross, vélo tout terrain (VTT)
;;3988;;Sports aquatiques
;;;3989;Natation
;;;3990;Plongeon
;;;3991;Water-polo
;;;3992;Plongée sous-marine
;;3993;;Sports nautiques
;;;3994;Voile, voilier
;;;3995;Ski nautique
;;;3996;Aviron
;;;3997;Planche à voile
;;;3998;Surf
;;;3999;Canoë
;;4000;;Sports de montagne, sports d'hiver
;;;4001;Ski
;;;4002;Alpinisme, escalade
;;;4003;Bobsleigh, luge
;;;4004;Patinage
;;;4005;Curling
;;;4018;Hockey sur glace
;;;3922;Spéléologie
;;4006;;Sports équestres
;;4007;;Sports de raquettes
;;;4008;Tennis
;;;4009;Tennis de table
;;;4010;Squash
;;;4011;Badminton
;;4013;;Golf
;;4014;;Jeux de boules
;;4015;;Sports extrêmes
;;4016;;Olympisme, para-olympisme
;;4017;;Entraînement sportif
;;3891;;Jeux de société, Sports cérébraux, Jeux de cartes
;;;3892;Jeux de rôle (guides, univers, etc.)
;;;3893;Sports cérébraux
;;;3894;Jeux de cartes
;;;3895;Jeux de société
;;4091;;Jeu vidéo
;3923;;;Chasse, pêche
;3865;;;Transport
;3866;;;Animaux
;;3867;;Animaux d'élevage
;;3868;;Animaux de compagnie (ou domestiques)
;;3869;;Animaux sauvages
;;3870;;Apiculture
;3871;;;Nature
;;3872;;Écologie
;;3873;;Champignons
;;3874;;Fleurs sauvages
;;3875;;Arbres
;;3876;;Océans et mers
;;3877;;Montagne
;;3878;;Ressources naturelles (roches, minéraux, fossiles)
;;3879;;Volcans et forces naturelles
;;3880;;Climat et météo
;;3881;;Astronomie
;3882;;;Jardinage
;;4019;;Encyclopédies du jardinage
;;4020;;Jardins bio, écologiques
;;3883;;Jardin d'ornement, fleurs
;;3884;;Plantes d'intérieur
;;3885;;Potager
;;3886;;Arbres et arbustes
;;3887;;Verger
;;3888;;Techniques et soin des plantes
;;3889;;Aménagements de jardins et petits espaces (terrasse, balcon, etc.)
;;3890;;Art et histoire des jardins
;;3924;;Bassins, fontaines
;3896;;;Généalogie
;3897;;;Collections
3898;;;;CARTES GÉOGRAPHIQUES ET ATLAS
;3899;;;Cartes géographiques
;;3900;;Cartes routières
;;3901;;Cartes géologiques
;;3902;;Cartes marines
;;3903;;Cartes météorologiques
;;3904;;Cartes topographies
;;3905;;Cartes touristiques
;;3906;;Cartes thématiques
;;3907;;Cartes célestes
;;3908;;Cartes aériennes
;3909;;;Atlas
;;3910;;Atlas généraux
;;3911;;Atlas géographiques
;;3912;;Atlas thématiques
;;3913;;Atlas routiers
;3914;;;Plans
;;3915;;Plans de ville
4129;;;;JEUNES ADULTES
;4144;;;Fantastique, paranormal
;4145;;;Magie, fantasy
;4146;;;Science-fiction
;4147;;;Policier, thriller
;4148;;;Contemporain
;4149;;;Historique
;4150;;;Action, aventures
;4151;;;Sentimental
;4152;;;Chick-lit
;4153;;;Epouvante
;4154;;;Témoignages
;4155;;;Dystopie
| 38,351 | Common Lisp | .cl | 1,272 | 28.483491 | 119 | 0.784549 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | afa079c7e747acb3805d27d4e5c95a263d04b189d8ceb8683e6e58f3ff484867 | 4,586 | [
-1
] |
4,588 | .gitlab-ci.yml | OpenBookStore_openbookstore/.gitlab-ci.yml | image: clfoundation/sbcl
# uncomment to run the jobs in parallel.
# stages:
# - test
# - build
# We need to install some system dependencies,
# to clone libraries not in Quicklisp,
# and to update ASDF to >= 3.3.4 in order to use local-package-nicknames.
before_script:
- apt-get update -qy
- apt-get install -y git-core sqlite3 tar gettext
# The image doesn't have Quicklisp installed by default.
- QUICKLISP_ADD_TO_INIT_FILE=true /usr/local/bin/install-quicklisp
# clone libraries not in Quicklisp or if we need the latest version.
- make install
# Upgrade ASDF (UIOP) to 3.3.5 because we want package-local-nicknames.
- mkdir -p ~/common-lisp/asdf/
- ( cd ~/common-lisp/ && wget https://asdf.common-lisp.dev/archives/asdf-3.3.5.tar.gz && tar -xvf asdf-3.3.5.tar.gz && mv asdf-3.3.5 asdf )
- echo "Content of ~/common-lisp/asdf/:" && ls ~/common-lisp/asdf/
qa:
allow_failure: true
# stage: test
script:
# QA tools:
# install Comby:
- apt-get install -y sudo
# - bash <(curl -sL get.comby.dev)
- bash <(curl -sL https://raw.githubusercontent.com/vindarel/comby/set-release-1.0.0/scripts/install.sh)
# install Colisper:
- git clone https://github.com/vindarel/colisper ~/colisper
- chmod +x ~/colisper/colisper.sh
- alias colisper=~/colisper/colisper.sh # doesn't work?
- cd src/ && ~/colisper/colisper.sh
build:
# stage: build
script:
- make build
artifacts:
name: "openbookstore"
paths:
- bin/
| 1,496 | Common Lisp | .l | 41 | 33.097561 | 142 | 0.691937 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 36073bf26b9ade7d90f46df32b88e6df068f30b282241e9b56b3cc2e77fc94e4 | 4,588 | [
-1
] |
4,589 | Makefile | OpenBookStore_openbookstore/Makefile | LISP ?= sbcl
# SHELL := bash
# List lisp files, unless they contains a #
SRC := $(shell find src/ -name '*.lisp' -a ! -name '*\#*')
HTML := $(shell find src/ -name '*.html' -a ! -name '*\#*')
DEPS := $(SRC) $(HTML) bookshops.asd # and some more...
# list of supported locales
LOCALES := fr_fr
# Example of how the variable should look after adding a new locale:
# LOCALES := fr_FR en_GB
# list of .po files (computed from the LOCALES variable)
PO_FILES := $(foreach locale,$(LOCALES),locale/$(locale)/LC_MESSAGES/bookshops.po)
# list of .mo files (computed from the LOCALES variable)
MO_FILES := $(foreach locale,$(LOCALES),locale/$(locale)/LC_MESSAGES/bookshops.mo)
all: test
run:
rlwrap $(LISP) --load run.lisp
build: ${MO_FILES}
# quickload cl+ssl: required to load the .asd, for Deploy.
# Don't reload templates and use a memory store.
#
# I use a feature flag, bc using djula:*recompile-templates-on-change*
# requires to load Djula before our app, and it isn't exactly the same meaning.
$(LISP) --non-interactive \
--eval '(ql:quickload "deploy")' \
--eval '(ql:quickload "cl+ssl")' \
--load openbookstore.asd \
--eval '(push :djula-binary *features*)' \
--eval '(ql:quickload :openbookstore)' \
--eval '(asdf:make :openbookstore)'
build-package:
# This must use a custom-built SBCL with a special parameter,
# see linux-packaging README.
# I have it under ~/.local/bin/bin/sbcl
$(LISP) --non-interactive \
--load openbookstore.asd \
--eval '(ql:quickload :openbookstore)' \
--eval '(load "~/common-lisp/asdf/tools/load-asdf.lisp")' \
--eval '(setf *debugger-hook* (lambda (c h) (declare (ignore h)) (format t "~A~%" c) (sb-ext:quit :unix-status -1)))' \
--eval '(asdf:make :openbookstore)'
build-gui:
$(LISP) --non-interactive \
--load openbookstore.asd \
--eval '(ql:quickload :bookshops/gui)' \
--eval '(asdf:make :bookshops/gui)'
docker-build:
sudo docker build . -t openbookstore
docker-run:
sudo docker run -it --rm --name my-obs openbookstore
test:
$(LISP) --non-interactive \
--load openbookstore.asd \
--load bookshops-test.asd \
--eval '(ql:quickload :bookshops-test)' # prove tests are run when loaded.
# Install dependencies, mostly for docker (gitlab CI).
install:
# we might need the latest.
git clone https://github.com/vindarel/replic/ ~/quicklisp/local-projects/replic/
git clone https://github.com/vindarel/cl-str/ ~/quicklisp/local-projects/cl-str/
# Workflow:
# - update
# - compile
# It seems we can not parse messages with the #! prefix, as does cl-i18n with its lisp storage.
# Needed to set the charset to UTF-8 in the pot manually.
# http://www.labri.fr/perso/fleury/posts/programming/a-quick-gettext-tutorial.html
#
# lisp.pot contains the string to translate that were extracted from
# the .lisp files.
#
# djula.pot contains the strings to transtlate that were extracted
# from the djula templates.
.PHONY: tr
tr: ${MO_FILES}
PO_TEMPLATE_DIR := locale/templates/LC_MESSAGES
PO_TEMPLATE := ${PO_TEMPLATE_DIR}/bookshops.pot
# Rule to extract translatable strings from SRC
${PO_TEMPLATE_DIR}/lisp.pot: $(SRC)
mkdir -p $(@D)
xgettext -k_ -kN_ --language=lisp -o $@ $^
# Rule to extract translatable strings from djula templates
${PO_TEMPLATE_DIR}/djula.pot: $(HTML) src/i18n.lisp
$(LISP) --non-interactive \
--eval '(ql:quickload "deploy")' \
--eval '(ql:quickload "cl+ssl")' \
--eval '(asdf:load-asd (truename "openbookstore.asd"))' \
--eval '(push :djula-binary *features*)' \
--eval '(ql:quickload :openbookstore)' \
--eval '(bookshops.i18n:update-djula.pot)'
# Rule to combine djula.pot and lisp.pot into bookshops.pot
${PO_TEMPLATE}: ${PO_TEMPLATE_DIR}/djula.pot ${PO_TEMPLATE_DIR}/lisp.pot
msgcat --use-first $^ > $@
# Rule to generate or update the .po files from the .pot file
locale/%/LC_MESSAGES/bookshops.po: ${PO_TEMPLATE}
mkdir -p $(@D)
[ -f $@ ] || msginit --locale=$* \
-i $< \
-o $@ \
&& msgmerge --update $@ $<
# Rule to create the .mo files from the .po files
locale/%/LC_MESSAGES/bookshops.mo: locale/%/LC_MESSAGES/bookshops.po
mkdir -p $(@D)
msgfmt -o $@ $<
| 4,124 | Common Lisp | .l | 102 | 38.294118 | 121 | 0.696424 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 6e3931ee844564f7cbfe4421b8708f775b6094c5b3ed0245c77f7da9574f2be9 | 4,589 | [
-1
] |
4,590 | Dockerfile | OpenBookStore_openbookstore/Dockerfile | #XXX: Experimental, needs more work.
# Currently fails when trying to open the db.db (lacking?).
FROM clfoundation/sbcl:latest
COPY . ~/projets/openbookstore/openbookstore/
WORKDIR ~/projets/openbookstore/openbookstore/
RUN DEBIAN_FRONTEND=noninteractive apt-get update && \
apt-get install -y \
sqlite3
RUN QUICKLISP_ADD_TO_INIT_FILE=true /usr/local/bin/install-quicklisp
#TODO: install Quicklisp dependencies here, not at every start up.
CMD [ "sbcl", "--load", "./run.lisp" ]
| 498 | Common Lisp | .l | 11 | 42.545455 | 68 | 0.756198 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 579c02635cb953fc96dbcb357942b165cc4fbc58440ea89fbcce51d8e7d8b05a | 4,590 | [
-1
] |
4,592 | djula.pot | OpenBookStore_openbookstore/locale/templates/LC_MESSAGES/djula.pot | # SOME DESCRIPTIVE TITLE.
# Copyright blabla
# This header was missing and was manually copied from lisp.pot
# it was preventing make build to complete.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-12-23 13:10+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
#: src/web/templates/login.html
#, lisp-format
msgid "Please login to continue"
msgstr ""
| 675 | Common Lisp | .l | 23 | 28.26087 | 63 | 0.752688 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 3ae1364d69546edbe56814a3378c53c8d1e40ce42e26016c431a2eb4d5df7fef | 4,592 | [
-1
] |
4,633 | record.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/record.html |
{% extends "base.html" %}
<!-- This would set the Djula package for all templates.
So far we use (let ((djula:*djula-execute-package*)) … render-template* ) -->
<!-- {% set-package "openbookstore.models" %} -->
<!-- {% set-package "mito-admin" %} -->
{% block title %}
mito-admin · {{ record.print-record }}
{% endblock %}
{% block content %}
<h3 class="title"> {{ table }} </h3>
<div class="columns">
<div class="column is-four-fifths">
<h4 class="title">
<!-- This method call works with djula:*djula-execute-package* -->
{{ record.print-record }}
<!-- A filter always works. -->
<!-- {{ record | print-record }} -->
<!-- Raw object view. -->
<!-- {{ record }} -->
</h4>
</div>
<div class="column">
<a class="button is-info is-light"
href="/admin/{{ table | lower }}/create"
title="create">
<span class="icon">
<i class="fas fa-plus"></i>
</span>
</a>
</div>
<div class="column">
<a class="button" href="/admin/{{ table | lower }}/{{ record.id }}/edit">
<span class="icon">
<i class="fas fa-edit"></i>
</span>
</a>
</div>
<div class="column">
<form action="/admin/{{table}}/{{ record.id }}/delete" method="POST"
onsubmit="return confirm('Are you sure to delete this record?');">
<button class="button is-danger" >
<span class="icon">
<i class="fas fa-trash"></i>
</span>
</button>
</form>
</div>
</div>
{% if debug and raw %}
<pre>
{{ raw }}
</pre>
{% endif %}
slots:
<table class="table is-hoverable">
<tbody>
{% for field in fields %}
<tr>
<td>
{{ field.name }}
</td>
<td>
{{ field.value }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
Rendered slots:
<table class="table is-hoverable">
<tbody>
{% for field in rendered-fields %}
<tr>
<td>
{{ field.name }}
</td>
<td>
{{ field.html | safe }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
| 2,087 | Common Lisp | .l | 84 | 19.857143 | 82 | 0.529055 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 79a42b2cc4ce2461122d7def1770705e00aac478dfaebb42be6c61bf9ad069f4 | 4,633 | [
-1
] |
4,634 | create_or_edit.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/create_or_edit.html |
{% extends "base.html" %}
{% block title %}
mito-admin · {{ record }}
{% endblock %}
{% block content %}
<h3 class="title"> {{ table }} </h3>
{% for error in errors %}
<div class="notification is-danger">
<button class="delete"> </button>
{{ error }}
</div>
{% endfor %}
<form class="form" action="{{ target }}" method="POST">
{% for input in inputs %}
{{ input.html | safe }}
{% endfor %}
<div class="field is-grouped">
<div class="control">
<button class="button is-link">Submit</button>
</div>
<div class="control">
<button class="button is-link is-light">Cancel</button>
</div>
</div>
</form>
{% endblock %}
| 678 | Common Lisp | .l | 26 | 22.576923 | 61 | 0.594384 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | d64de7edfff379f10f30002ded6eb11933274314cdf3c3e0327f9efdd48a0177 | 4,634 | [
-1
] |
4,635 | table.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/table.html |
{% extends "base.html" %}
{% block title %}
mito-admin · {{ table }}
{% endblock %}
{% block content %}
<div class="columns">
<div class="column is-four-fifths">
<h3 class="title"> {{ table }} </h3>
</div>
<div class="column"> </div>
<div class="column">
<a class="button is-info is-light"
href="/admin/{{ table | lower }}/create"
style="float: right;"
title="create">
<span class="icon">
<i class="fas fa-plus"></i>
</span>
</a>
</div>
</div>
{% for message in messages %}
<div class="notification {{ message.class }}">
<button class="delete"> </button>
{{ message.message }}
</div>
{% endfor %}
<div>
<form action="/admin/{{ table | lower }}/search">
<input name="q" type="text" class="input"
{% if search-value %}
value="{{ search-value }}"
{% else %}
placeholder="search"
{% endif %}/>
</form>
</div>
<div style="margin: 1em">
{{ pagination-template | safe }}
</div>
<table class="table is-hoverable is-fullwidth">
<tbody>
{% if not records %}
<div> no results </div>
{% endif %}
{% for record in records %}
<tr>
<td>
<a href="/admin/{{ table | lower }}/{{ record.id }}">
<!-- We might want a special method, similar to print-object but without the formatting. -->
<!-- Because print-object might show more data than only the record name. -->
{% if record.name %}
{{ record.name }}
{% elif record.title %}
{{ record.title }}
{% else %}
{{ record }}
{% endif %}
</a>
</td>
<td>
<div class="field is-grouped" style="float:right;">
<a class="control button" href="/admin/{{ table | lower }}/{{ record.id }}/edit">
<span class="icon">
<i class="fas fa-edit"></i>
</span>
</a>
<div class="control">
<form action="/admin/{{table}}/{{ record.id }}/delete" method="POST"
onsubmit="return confirm('Are you sure to delete this record?');">
<button class="button is-danger" >
<span class="icon">
<i class="fas fa-trash"></i>
</span>
</button>
</form>
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div style="margin: 1em">
{{ pagination-template | safe }}
</div>
{% endblock %}
| 2,503 | Common Lisp | .l | 87 | 21.793103 | 102 | 0.511706 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 081f0fa42ba5429dfdb4c2284e88445217a1a7d9d985bcf21bbde0dff51ba299 | 4,635 | [
-1
] |
4,636 | base.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/base.html | <!DOCTYPE html>
<html lang="en" data-theme="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bulma, Buefy -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<!-- Notiflix: cool notification -->
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/AIO/notiflix-aio-2.1.3.min.js"></script>
<!-- HTMX -->
<!-- <script src="https://unpkg.com/[email protected]"></script> -->
<script src="https://unpkg.com/[email protected]" integrity="sha384-cZuAZ+ZbwkNRnrKi05G/fjBX+azI9DNOkNYysZ0I/X5ZFgsmMiBXgDZof30F5ofc" crossorigin="anonymous"></script>
<!-- WebSocket extension -->
<!-- <script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script> -->
<!-- stylo editor -->
<!-- <script type="module" src="https://unpkg.com/@papyrs/stylo@latest/dist/stylo/stylo.esm.js"></script> -->
<!-- Other JS and UI helpers -->
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<!-- The app JS (global. More JS can be loaded per page) -->
<script defer src="/static/mito-admin.js"></script>
<!-- The app CSS -->
<!-- <link rel="stylesheet" type="text/css" href="/static/css/admin.css"> -->
<title>{% block title %} Admin dashboard {% endblock %}</title>
</head>
<body>
<!-- START NAV -->
<nav class="navbar">
<div class="container">
<div class="navbar-brand">
<a class="navbar-item brand-text" href="/admin/"> admin </a>
<div class="navbar-burger burger" data-target="navMenu">
<span></span>
<span></span>
<span></span>
</div>
</div>
<div id="navMenu" class="navbar-menu">
<div class="navbar-start">
<a class="navbar-item" href="/">
<div class="navbar-item has-dropdown is-hoverable navbar-menu">
<a class="navbar-link">
Database
</a>
<div class="navbar-dropdown is-right">
<a class="navbar-item">
Quick Action
</a>
</div>
</div>
</a>
<div id ="quick-search" class="navbar-item field">
<p class="control has-icons-right">
<b-autocomplete placeholder="ISBN or Keywords..."
v-model="name"
field="title"
:data ="data"
:loading="isFetching"
@typing="getAsyncData"
@select="option => itemSelected(option)"
><template slot-scope="props">{$ {{ props.option.title }} $}</template>
</b-autocomplete>
<span class="icon is-small is-right">
</span>
</p>
</div>
</div>
</div>
<div class="navbar-end" >
<div class="navbar-item has-dropdown is-hoverable navbar-menu" data-target="navMenu">
<a class="navbar-link is-arrowless">
<span class="icon">
<i class="fas fa-lg fa-sun" aria-hidden="true"></i>
</span>
</a>
<div class="navbar-dropdown is-right">
<a class="navbar-item">
<button data-scheme="light" class="bd-nav-item is-sun" aria-label="Light mode"
onclick="setTheme('light')">
<span class="icon">
<i class="fas fa-sun" aria-hidden="true"></i>
</span>
<span>Light</span>
</button>
</a>
<a class="navbar-item">
<button data-scheme="dark" class="bd-nav-item is-moon" aria-label="Dark mode"
onclick="setTheme('dark')">
<span class="icon">
<i class="fas fa-moon" aria-hidden="true"></i>
</span>
<span> Dark </span>
</button>
</a>
<a class="navbar-item">
<button data-scheme="system" class="bd-nav-item is-system" aria-label="System mode"
onclick="setTheme('system')">
<span class="icon">
<i class="fas fa-desktop" aria-hidden="true"></i>
</span>
<span> System </span>
</button>
</a>
</div>
<div class="navbar-item" >
{% if current-user %}
<div class="dropdown is-hoverable">
<div class="dropdown-trigger" >
<button class="button" aria-haspopup="true" aria-controls="profile-dropdown" >
<span class="icon is-small" >
<i class="fas fa-user" aria-hidden="true"></i>
</span>
<span>{{ current-user | user-name }}</span>
</button>
</div>
<div class="dropdown-menu" role="menu" id="profile-dropdown">
<div class="dropdown-content" >
<div class="dropdown-item" >
<form action="/logout" method="POST" >
<button class="button is-light">Logout</button>
</form>
</div>
</div>
</div>
</div>
{% else %}
<form action="/login" >
<input name="referer-route" type="hidden" value="{{ request-uri }}"/>
<button class="button is-light" >Login</button>
</form>
{% endif %}
</div>
</div>
</nav>
<!-- END NAV -->
<!-- START MENU -->
<div class="container">
<div class="columns">
<div class="column is-2">
<aside class="menu is-hidden-mobile">
<p class="menu-label">
Tables
</p>
<ul class="menu-list">
{% for table in tables %}
<li>
<a href="/admin/{{ table }}"> {{ table }} </a>
</li>
{% endfor %}
</ul>
</aside>
</div>
<div class="column is-9">
{% block content %} {% endblock %}
</div>
</div>
</div>
<footer class="footer" style="margin-top: 15em">
<div class="content has-text-centered">
<p>
<strong> mito-admin </strong> version <a href="#"> 0.01</a>. The <a href="#"> source code </a> is licensed under the GPLv3. <a href="https://github.com/sponsors/vindarel/"> We need your support! </a>
</p>
</div>
</footer>
</body>
<script>
// bulma.js: hamburger toggle for mobile.
(function() {
var burger = document.querySelector('.burger');
var menu = document.querySelector('#'+burger.dataset.target);
burger.addEventListener('click', function() {
burger.classList.toggle('is-active');
menu.classList.toggle('is-active');
});
})();
// Straight from Bulma website:
// (we could clean up some CSS classes: bd- etc)
// THEMES
const STORAGE_KEY = "bulma-theme";
const SYSTEM_THEME = "system";
// const DEFAULT_THEME = "light";
const DEFAULT_THEME = "dark";
const state = {
chosenTheme: SYSTEM_THEME, // light|dark|system
appliedTheme: DEFAULT_THEME, // light|dark
OSTheme: null, // light|dark|null
};
const $themeCycle = document.getElementById("js-cycle");
const $themeSwitchers = document.querySelectorAll(".js-themes button");
const $darkmodes = document.querySelectorAll(".js-darkmode");
const updateThemeUI = () => {
if (state.appliedTheme === "light") {
$themeCycle.className = "bd-cycle js-burger is-sun";
} else {
$themeCycle.className = "bd-cycle js-burger is-moon";
}
$themeSwitchers.forEach((el) => {
const swatchTheme = el.dataset.scheme;
if (state.chosenTheme === swatchTheme) {
el.classList.add("is-active");
} else {
el.classList.remove("is-active");
}
});
};
const setTheme = (theme, save = true) => {
state.chosenTheme = theme;
state.appliedTheme = theme;
if (theme === SYSTEM_THEME) {
state.appliedTheme = state.OSTheme;
document.documentElement.removeAttribute("data-theme");
window.localStorage.removeItem(STORAGE_KEY);
} else {
document.documentElement.setAttribute("data-theme", theme);
if (save) {
window.localStorage.setItem(STORAGE_KEY, theme);
}
}
updateThemeUI();
};
const toggleTheme = () => {
if (state.appliedTheme === "light") {
setTheme("dark");
} else {
setTheme("light");
}
};
const detectOSTheme = () => {
if (!window.matchMedia) {
// matchMedia method not supported
return DEFAULT_THEME;
}
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
// OS theme setting detected as dark
return "dark";
} else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
return "light";
}
return DEFAULT_THEME;
};
// On load, check if any preference was saved
const localTheme = window.localStorage.getItem(STORAGE_KEY);
state.OSTheme = detectOSTheme();
if (localTheme) {
setTheme(localTheme, false);
} else {
setTheme(SYSTEM_THEME);
}
// Event listeners
$themeSwitchers.forEach((el) => {
el.addEventListener("click", () => {
const theme = el.dataset.scheme;
setTheme(theme);
});
});
$darkmodes.forEach((el) => {
el.addEventListener("click", (e) => {
e.preventDefault();
toggleTheme();
});
});
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
const theme = event.matches ? "dark" : "light";
state.OSTheme = theme;
setTheme(theme);
});
</script>
</html>
| 10,424 | Common Lisp | .l | 271 | 27.575646 | 209 | 0.520262 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 84863b603257bb4de61d98ae042872e335adb598b3d2b38ae772294184daab0a | 4,636 | [
-1
] |
4,637 | index.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/index.html |
{% extends "base.html" %}
{% block content %}
<section class="hero is-primary welcome is-small">
<div class="hero-body">
<div class="container">
<h1 class="title">
Hello, Admin.
</h1>
<h2 class="subtitle">
I hope you are having a great day!
</h2>
</div>
</div>
</section>
<section class="info-tiles">
<div class="tile is-ancestor has-text-centered">
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> </p>
<p class="subtitle"> Number of records </p>
</article>
</div>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> Many </p>
<p class="subtitle"> cool things to do today </p>
</article>
</div>
</div>
</section>
<div class="columns">
<div class="column is-6">
<div class="card events-card">
<header class="card-header">
<p class="card-header-title">
Records…
</p>
<a href="#" class="card-header-icon" aria-label="more options">
<span class="icon">
<i class="fa fa-angle-down" aria-hidden="true"></i>
</span>
</a>
</header>
<div class="card-table">
<div class="content">
<table class="table is-fullwidth is-striped">
<tbody>
{% for record in records %}
<tr>
<td width="5%"><i class="fa fa-bell-o"></i></td>
<td>
<a href="/admin/{{ table }}/{{ record.id }}">{{ record }}
</a>
<td class="level-right"><a class="button is-small is-primary" href="#">Action</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<footer class="card-footer">
<a href="/stock/loans?outdated=t" class="card-footer-item">View All</a>
</footer>
</div>
</div>
<div class="column is-6">
<div class="card">
<header class="card-header">
<p class="card-header-title">
Quick search
</p>
<a href="#" class="card-header-icon" aria-label="more options">
<span class="icon">
<i class="fa fa-angle-down" aria-hidden="true"></i>
</span>
</a>
</header>
<div class="card-content">
<div class="content">
<form action="/search">
<div class="control has-icons-left has-icons-right">
<input class="input is-large" name="q" type="text" placeholder="Search…">
<span class="icon is-medium is-left">
<i class="fa fa-search"></i>
</span>
<span class="icon is-medium is-right">
<i class="fa fa-check"></i>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
| 2,947 | Common Lisp | .l | 96 | 21.9375 | 102 | 0.502821 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | d26ac84ad2f3461fab9f2165ce805881f0edac2e4f65a10ae861d0f17f500903 | 4,637 | [
-1
] |
4,638 | select.html | OpenBookStore_openbookstore/src/web/mito-admin/templates/includes/select.html | <div class="field">
<label class="label" for="{{ name }}">{{ label }}</label>
<select name="{{ name }}" id="{{ select-id }}" class="select">
{% if empty-choice %}
<option value=""> {{ empty-choice-label }} </option>
{% endif %}
{% for option in options %}
{% if record %}
{% if selected-option-id == option.id %}
<option value="{{ option.id }}" selected>
{{ option.name }}
</option>
{% else %}
<option value="{{ option.id }}">
{{ option.name }}
</option>
{% endif %}
{% else %}
<option value="{{ option.id }}">
{{ option.name }}
</option>
{% endif %}
{% endfor %}
</select>
</div>
| 787 | Common Lisp | .l | 25 | 22.24 | 69 | 0.434037 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 64b24532e7bafc84852f687b190f7b232f869c016f6d5f01853de958cfee799c | 4,638 | [
-1
] |
4,639 | card-page.html | OpenBookStore_openbookstore/src/web/templates/card-page.html | {% extends "base.html" %}
<!-- Some JS is loaded in the end. See card-page.js -->
{% block content %}
<div class="container is-fullheight" style="margin-bottom: 10em">
<div class="section">
<div class="columns is-centered">
<div class="column is-2">
<div class="card" id="{{ card.id }}">
<div class="card-image">
<figure class="image">
<img src="{{ card.cover-url }}" alt="Couverture de {{ card.title }}"/>
</figure>
</div>
</div>
<p style="padding-top: 1em">
<a href="/card/update/{{ card.id }}"> {_ "Edit" _} </a>
</p>
</div>
<div class="card-content column">
<div class="media">
<span class="media-content">
<!-- In card-stock.html: -->
{% block media_header %}
{% endblock media_header %}
<p class="title is-4 no-padding">
<a href="{{ card | url }}" style="color: black;">
{{ card.title }}
</a>
</p>
{% if card.authors %}
<p><span><a href="/search?q={{ card.authors }}">{{ card.authors | capfirst }}</a></span></p>
{% endif %}
{% if card.publisher %}
<p class="">{{ card.publisher | capfirst }}</p>
{% endif %}
<!-- -
{% if card.shelf %}
<p>
<a href="/search?rayon={{ card.shelf.id }}">
<span class="tag" title="{{ card.shelf }}"> {{ card.shelf.name | truncatechars:27 }} </span>
</a>
</p>
{% endif %}
-->
{% if card.isbn %}
<div class="has-text-grey-light"> {{ card.isbn }} </div>
{% endif %}
{% if card.price %}
<!--TODO: hard-coded € currency -->
<div class="title is-6"> {{ card.price | price }} €</div>
{% endif %}
</span>
</div>
<table class="table is-narrow">
<tbody>
<tr>
<td>
<div id="quantity">
{_ "In stock" _}
</td>
<td>
<span class="tag level-item
{{ card | quantity | quantity-style:(:positive "is-success" :negative "is-danger is-light" :zero "") }}">
x {{ card | quantity }}</span>
</td>
</div>
</tr>
<!-- Show places only if there is more than the default place
(preferably unused feature) -->
{% if places-copies.length != 1 %}
<tr>
<td></td>
<td>
<table id="place-copies-table" class="table">
{% for place-copy in places-copies %}
<tr id="place-copy{{ place-copy.id }}">
<td>
{{ place-copy | name }}
</td>
<td>
{{ place-copy | quantity }}
</td>
</tr>
{% endfor %}
</table>
</td>
</tr>
{% endif %}
<tr>
<td>
<!-- <a href="/search?rayon={{ card.shelf.id }}"> -->
<!-- <span class="tag" title="{{ card.shelf.name }}"> {{ card.shelf.name | truncatechars:27 }} </span> -->
<!-- </a> -->
{_ "Shelf" _}
</td>
<td>
<div hidden="true" data-shelves="{{ shelves }}"></div>
<div class="select is-small">
<select id="shelf-select" name="shelves">
<option value=""> </option>
{% for shelf in shelves %}
{% if shelf.id == card.shelf.id %}
<option value="{{ shelf.id }}" selected> {{ shelf.name }} </option>
{% else %}
<option value="{{ shelf.id }}"> {{ shelf.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<a id="link-stock-shelf"
color="black"
title="Search your stock"
href="/stock?shelf={{ card.shelf.name-ascii }}">
<span class="icon">
<i class="fas fa-search"></i>
</span>
</a>
</td>
</tr>
<tr>
<td>
Borrowed by:
</td>
<td>
{% for borrowed in borrowed-books %}
<div>
<!--TODO: click on the contact name to see the contact page. -->
<!--TODO: add an HTMX button to borrow the book, to cancel or validate a loan. -->
{{ borrowed.contact.name }}
<span>
due date:
<div class="tag level-item {{ borrowed | date-style:(:positive "is-success" :negative "is-danger is-light" :zero "") }}">
{{ borrowed.due-date
| date:(:year "-" (:month 2) "-" (:day 2))
}}
</div>
</span>
</div>
{% endfor %}
</td>
</tr>
</tbody>
</table>
{% block subinfo %}
<!-- TODO this is a bodge around no in boolean operator for if in djula -->
{% for role in current-user-roles %}
{% ifequal role "editor" %}
<div id="stock-management" >
<!-- TODO possibly use horizontal form addons from bulma instead -->
<form action="/card/add-stock/" method="POST" >
<input name="q" type="hidden" value="{{ q }}" />
<input name="referer-route" type="hidden" value="{{ referer-route }}">
<input name="isbn" type="hidden" value="{{ card.isbn }}"/>
<div class="field" >
<label class="label">
{_ "Place" _}
</label>
<select name="place-id" class="select" >
{% for place in places %}
<option value="{{ place.id }}">{{ place.name }}</option>
{% endfor %}
</select>
</div>
<div class="field">
<label class="label"> {_ "Quantity" _} </label>
<input name="quantity" type="text" id="quantity-input" value="0"/>
</div>
<div class="field is-grouped" >
<button action="submit" class="button is-link" >
{_ "Add" _}
</button>
</div>
</form>
</div>
{% endifequal %}
{% endfor %}
{% endblock subinfo %}
</div>
</div>
</div>
<div>
<div>
<div class="columns">
<div class="column is-four-fifths">
<h4 class="title is-6"
href="#review"
title="">
<span class="icon">
<i class="fas fa-comment" aria-hidden="true"></i>
</span>
Critique
</h4>
<em>
{_ "Pour modifier le texte, cliquez dessus. Pour mettre en forme, sélectionnez du texte et utilisez la barre d'outils qui apparaît. N'écrivez pas de code HTML directement." _}
</em>
</div>
<div class="column">
</div>
</div>
<stylo-editor></stylo-editor>
<!-- This editor id matches with the custom textid -->
<article contenteditable="true" id="card_review">
{% if card.review %}
{{ card.review | safe }}
{% else %}
<div>Lorem ipsum dolor sit amet.</div>
{% endif %}
</article>
<br/>
<button class="button"
onclick="save_review('card_review')"> save
</button>
</div>
</div>
</div>
<!-- Load JavaScript for this page: handle a change of the shelf select -->
<script defer src="/static/card-page.js"></script>
{% block script %}
<script>
window.addEventListener('load', (event) => {
const quantityInput = document.getElementById('quantity-input');
quantityInput.focus();
quantityInput.setSelectionRange(0, -1);
});
</script>
{% endblock script %}
{% endblock %}
| 10,180 | Common Lisp | .l | 227 | 23.955947 | 189 | 0.353393 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 17d75c12a8fef0019b2cb754b0aced78836e6b972da687fb8263624dd8c476b9 | 4,639 | [
-1
] |
4,640 | loans.html | OpenBookStore_openbookstore/src/web/templates/loans.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<h3 class="title is-3"> Loans </h3>
{% if filter-outdated-p %}
<div class="title is-6"> outdated loans </div>
{% endif %}
{% for contact-copy in loans %}
<div name="cardid" data-id="{{ contact-copy.book.id }}" id="card{{ contact-copy.book.id }}" class="box content">
<article class="post">
<div class="media">
<div class="media-left">
<p class="image is-64x64">
<img src="{{ contact-copy.book.cover-url }}">
</p>
</div>
<div class="media-content">
{% block contact-copy.book_content %}
<div class="content">
<a onclick="alert('clicked')">
<span class="title is-6"> {{ contact-copy.book.title }} </span>
</a>
<!-- it's me or Mito, but contact-copy.contact.name resolves to NIL, so let's use a filter. -->
<div> lended by {{ contact-copy | contact-name }} </div>
<span>
due date:
<div class="tag level-item {{ contact-copy | date-style:(:positive "is-success" :negative "is-danger is-light" :zero "") }}">
{{ contact-copy.due-date
| date:(:year "-" (:month 2) "-" (:day 2))
}}
</div>
</span>
<div class="has-text-grey-light"> {{ contact-copy.book.isbn }} </div>
<!-- <span> éd. {{ contact-copy.book.publisher | capfirst }} </span> -->
<p>
{% if contact-copy.book.availability %}
<span> availability: {{ contact-copy.book.availability }} </span>
{% endif %}
</p>
</div>
{% endblock contact-copy.book_content %}
</div>
<div class="media-right">
<div class="level">
<span class="tag level-item">
x {{ contact-copy.quantity }}
</span>
</div>
<!-- TODO how to handle duplication of forms? how to stop them getting out of sync
with the end point parameters too? -->
<div class="level">
{% block contact-copy.book_button_row %}
<form action="#" method="POST" class="level-item">
<input name="q" type="hidden" value="{{ q }}">
<input name="referer-route" type="hidden" value="{{ route }}">
<input name="book-id" type="hidden" value="{{ contact-copy.book.id ]}">
<input name="title" type="hidden" value="{{ contact-copy.book.title }}">
<input name="title" type="hidden" value="{{ contact-copy.book.title }}">
<input name="isbn" type="hidden" value="{{ contact-copy.book.isbn }}" />
<input name="cover-url" type="hidden" value="{{ contact-copy.book.cover-url }}" />
<input name="publisher" type="hidden" value="{{ contact-copy.book.publisher }}" />
<input type="submit" class="button" value="Do sthg...">
</form>
<form action="/contact-copy.book/quick-add-stock/" method="POST" class="level-item">
<input name="quantity" type="hidden" value="1" />
<input name="q" type="hidden" value="{{ q }}">
<input name="referer-route" type="hidden" value="{{ route }}">
<input name="book-id" type="hidden" value="{{ contact-copy.book.id }}" />
<input name="title" type="hidden" value="{{ contact-copy.book.title }}" />
<input name="isbn" type="hidden" value="{{ contact-copy.book.isbn }}" />
<input name="cover-url" type="hidden" value="{{ contact-copy.book.cover-url }}"/>
<input name="publisher" type="hidden" value="{{ contact-copy.book.publisher }}" />
</form>
{% endblock contact-copy.book_button_row %}
</div>
</div>
</div>
</article>
</div>
{% endfor %}
{% endblock %}
| 3,839 | Common Lisp | .l | 83 | 36.939759 | 137 | 0.542034 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 637d423d59edb9b49ed0bf571dfe9b28a9c86e0501c65896185f3ee085320693 | 4,640 | [
-1
] |
4,641 | login.html | OpenBookStore_openbookstore/src/web/templates/login.html | {% extends "no-nav-base.html" %}
{% block content %}
{% if current-user %}
<p> You're logged in as {{ current-user | user-name }} </p>
{% else %}
<div class="container is-widescreen is-fullhd">
<section class="hero is-info">
<div class="hero-body">
<div class="container">
<h1 class="title is-3">{_ "Welcome to OpenBookStore" _}</h1>
<p class="subtitle is-5">{_ "Please login to continue" _}</p>
</div>
</div>
</section>
<div class="section">
<div class="columns">
<div class="is-3">
<form id="login" action="/login" method="POST">
<input name="referer-route" type="hidden" value="{{ referer-route }}"/>
<div class="field" >
<label class="label">{_ "Email" _}</label>
<p class="control has-icons-left">
<input name="email" value="" class="input" type="text" >
<span class="icon is-small is-left" >
<i class="fas fa-envelope" ></i>
</span>
</p>
</div>
<div clas="field">
<label class="label" >{_ "Password" _}</label>
<p class="control has-icons-left">
<input name="password" class="input" type="password" value="" >
<span class="icon is-small is-left" >
<i class="fas fa-lock" ></i>
</span>
</p>
</div>
<div class="field">
<p class="control">
<button class="button is-primary">{_ "Login" _}</button>
</p>
</div>
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
| 1,655 | Common Lisp | .l | 49 | 25.020408 | 81 | 0.498127 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | f459286d16cded0916a52d3575fc5ef6fa9b16f541d4dcb73ca908c8df7bd636 | 4,641 | [
-1
] |
4,642 | receive.html | OpenBookStore_openbookstore/src/web/templates/receive.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div class="container">
<div class="columns">
<div class="column is-3">
<ul class="menu-list">
<li>
<a href="/receive"
{% if not current-shelf %}
class="is-active"
{% endif %}
>
All cards
</a></li>
{% for shelf in shelves %}
<li style="background-color: {{ forloop.counter0 | background-color }};">
<a href="/receive/{{ shelf.id }}-{{ shelf.name-ascii | slugify }}"
{% if current-shelf.id == shelf.id %}
class="is-active"
{% endif %}
>
{{ shelf.name }}
</a></li>
{% endfor %}
</ul>
</div>
<div class="column">
<div id="vue-receive">
<form id="form-input" v-on:submit.prevent="addCard">
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" type="text" placeholder="Scan ISBN..."
autofocus
v-model="input"
>
</div>
<div class="control submit">
<a class="button is-info">
Search
</a>
</div>
</div>
</form>
<!-- input: {$ {{ input }} $} -->
<div>
<div v-for="card in reversedCards()" :key="counter">
<!-- After fetch, display the book data. -->
<!-- Beware of property names: the card object is encoded as JSON,
and currently cl-json will easily transform lisp-case to camelCase. -->
<!-- A refresher: use Vue's escape symbol + Djula's one in HTML body,
use v-bind: for properties.-->
<div v-if="card.entry.card && card.entry.card.title">
<div class="card">
<div class="card-content">
<div class="media">
<div class="media-left">
<figure class="image is-48x48" >
<img v-bind:src="card.entry.card.coverUrl">
</figure>
</div>
<div class="media-content">
<div class="title is-5">
<a v-bind:href="card.entry.card.url" style="color: black;">
{$ {{ card.entry.card.title }} $}
</a>
</div>
<div class="has-text-grey-light"> {$ {{ card.entry.card.isbn }} $} </div>
<span class="subtitle is-6"> {$ {{ card.entry.card.publisher }} $} </span>
<span v-if="card.entry.card.shelf" class="tag">
<a color="black"
title="Search your stock"
href="/stock?shelf={{ card.shelf.name-ascii }}">
{$ {{ card.entry.card.shelf.name }} $}
</a>
</span>
<p v-if="card.entry.card.price" class="subtitle is-6">
{$ {{ card.entry.card.price }} $} €
</p>
<p v-else class="is-danger">
price missing
</p>
<!-- <p class="subtitle is-6"> {$ {{ card.entry.card }} $} </p> -->
</div>
</div>
<div class="content">
</div>
</div>
</div>
</div>
<!-- Before fetch: display raw input -->
<!-- (place after "after" because of the v-else) -->
<div v-else class="card">
<div class="card-content">
<div class="media">
<div class="media-content">
<p class="title is-4"> {$ {{ card.entry }} $} </p>
</div>
</div>
<div class="content">
</div>
</div>
</div>
</div>
</div>
</div>
</>
<!-- cols -->
</div>
</div>
</div>
{% endblock %}
| 4,275 | Common Lisp | .l | 114 | 22.692982 | 96 | 0.404353 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 54ee79e18cd10908998946772bb697ff79a6e6ddf192db119d308b97630d4edb | 4,642 | [
-1
] |
4,643 | search.html | OpenBookStore_openbookstore/src/web/templates/search.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
{% block search_form %}
<form action="{{ route }}">
<div class="field has-addons">
<span class="control has-icons-left">
<span class="select">
<select name="datasource">
{% if datasource == "france" %}
<option value="france" selected> France </option>
{% else %}
<option value="france"> France </option>
{% endif %}
{% if datasource == "argentina" %}
<option value="argentina" selected> Argentina </option>
{% else %}
<option value="argentina"> Argentina </option>
{% endif %}
<!-- <option value="dilicom" {% if datasource == "dilicom" %} selected {% endif %}> Dilicom (pro) </option> -->
</select>
</span>
<div class="icon is-small is-left">
<i class="fas fa-globe"></i>
</div>
</span>
<p class="control is-expanded">
<input class="input" name="q" type="text" {% if q %} value="{{ q }}" {% else %} placeholder="Search by title, author and ISBN" {% endif %}>
</p>
<button type="submit" class="button is-info">
<span class="icon">
<i class="fas fa-search"></i>
</span>
<span> </span>
</button>
</div>
{% if q and nb-results == 0 %}
<div class="columns is-centered">
<div class="is-half">
<p class="is-primary">
No results
</p>
</div>
</div>
{% endif %}
</form>
{% endblock search_form %}
</br>
{% for msg in messages %}
<div>
{{ msg }}
</div>
{% endfor %}
{% for card in cards %}
<div name="cardid" data-id="{{ card.id }}" id="card{{ card.id }}" class="box content">
<article class="post">
<div class="media">
<div class="media-left">
<p class="image is-64x64">
<img src="{{ card.cover-url }}">
</p>
</div>
<div class="media-content">
{% block card_content %}
<div class="content">
<a onclick="alert('clicked')">
<span class="title is-6"> {{ card.title }} </span>
</a>
<div> {{ card.authors }} </div>
<span class="has-text-grey-light"> {{ card.isbn }} </span>
<span> éd. {{ card.publisher | capfirst }} </span>
<p>
{% if card.availability %}
<span> availability: {{ card.availability }} </span>
{% endif %}
</p>
</div>
{% endblock card_content %}
</div>
<div class="media-right">
<div class="level">
<span class="level-item" name="price" data-price="{{ card.price }}"> {{ card.price | price }} €</span>
<span class="tag level-item
{{ card | quantity | quantity-style:(:positive "is-success" :negative "is-danger is-light" :zero "") }}">
x {{ card | quantity }}</span>
</div>
<!-- TODO how to handle duplication of forms? how to stop them getting out of sync
with the end point parameters too? -->
<!-- Every field of the dict object returned by the scrapers must be added in these forms. -->
<!-- Then the route parameters must be updated too: card-quick-add-route… -->
<div class="level">
{% block card_button_row %}
<form action="/card/add-or-create/" method="POST" class="level-item">
<input name="q" type="hidden" value="{{ q }}">
<input name="referer-route" type="hidden" value="{{ route }}">
<input name="book-id" type="hidden" value="{{ card.id ]}">
<input name="title" type="hidden" value="{{ card.title }}">
<input name="title" type="hidden" value="{{ card.title }}">
<input name="isbn" type="hidden" value="{{ card.isbn }}" />
<input name="price" type="hidden" value="{{ card.price }}" />
<input name="authors" type="hidden" value="{{ card.authors }}" />
<input name="cover-url" type="hidden" value="{{ card.cover-url }}" />
<input name="publisher" type="hidden" value="{{ card.publisher }}" />
<input type="submit" class="button" value="Add...">
</form>
<form action="/card/quick-add-stock/" method="POST" class="level-item">
<input name="quantity" type="hidden" value="1" />
<input name="q" type="hidden" value="{{ q }}">
<input name="referer-route" type="hidden" value="{{ route }}">
<input name="book-id" type="hidden" value="{{ card.id }}" />
<input name="title" type="hidden" value="{{ card.title }}" />
<input name="isbn" type="hidden" value="{{ card.isbn }}" />
<input name="price" type="hidden" value="{{ card.price }}" />
<input name="authors" type="hidden" value="{{ card.authors }}" />
<input name="cover-url" type="hidden" value="{{ card.cover-url }}"/>
<input name="publisher" type="hidden" value="{{ card.publisher }}" />
<input type="submit" class="button" value="+1">
</form>
{% endblock card_button_row %}
</div>
</div>
</div>
</article>
</div>
{% endfor %}
{% endblock %}
| 5,253 | Common Lisp | .l | 128 | 32.585938 | 145 | 0.528731 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 9662b9c80d8428bcef11ef550e16e94d772f7bf0b726402ed54fc38212ff7c19 | 4,643 | [
-1
] |
4,644 | no-nav-base.html | OpenBookStore_openbookstore/src/web/templates/no-nav-base.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<!-- Our CSS: -->
<!-- <link rel="stylesheet" type="text/css" href="../css/admin.css"> -->
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/AIO/notiflix-aio-2.1.3.min.js"></script>
<title>{% block title %} OpenBookStore {% endblock %}</title>
</head>
<body>
{% block content %} {% endblock %}
</body>
</html>
| 863 | Common Lisp | .l | 18 | 41.055556 | 116 | 0.609727 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 7241a18054520d83b1baca28d4002724349f8a7dad5fdc624f1bc47701f52f9d | 4,644 | [
-1
] |
4,645 | history.html | OpenBookStore_openbookstore/src/web/templates/history.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<!-- Everything remains to be done:
- view history of a month
- view history of a day
- choose a day or month
- show total revenue
- undo a sell (not just a soldcard)
- show payments
- export results in CSV
- ...
-->
<div id="history-page">
<h3 class="is-size-3">
History • {{ min-date | date:(:short-month ", " :year) }}
<!-- there's long-month, but not translated. -->
</h3>
<!-- Here: add previous and next month buttons etc -->
<!-- <a href=""> {{ min-date | date:(:short-month ", " :year) }} </a> -->
<table class="table">
<thead>
<th> transaction </th>
<th> date </th>
<th> title </th>
<th> publisher </th>
<th> price sold </th>
<th> quantity sold </th>
<th> payment method </th>
</thead>
<tbody>
{% for sell/soldcard in data %}
<tr data-sell-id="{{ sell/soldcard.sell-id }}"
{% if sell/soldcard.item-group %}
style="background-color: white"
{% else %}
style="background-color: lightgrey"
{% endif %}
>
<td>
{% if sell/soldcard.first-sell-item %}
{{ sell/soldcard.sell-id }}
{% endif %}
</td>
<td>
{% if sell/soldcard.first-sell-item %}
{{ sell/soldcard.created-at | date:(:year "/" (:month 2) "/" (:day 2) " " (:hour 2) ":" (:min 2)) }}
{% endif %}
</td>
<td>
<a href="{{ sell/soldcard.soldcard.card | url }}"> {{ sell/soldcard.soldcard.card.title }} </a>
</td>
<td>
{{ sell/soldcard.soldcard.card.publisher }}
</td>
<td>
{{ sell/soldcard.soldcard.sold-price | price }}€
</td>
<td>
x{{ sell/soldcard.soldcard.quantity }}
</td>
<td>
{{ sell/soldcard.sell.payment-method-name }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</ div>
{% endblock %}
| 1,938 | Common Lisp | .l | 72 | 21.902778 | 106 | 0.543631 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 293f3fc960accde0fc5347d56dbdfc1795fb396fa5594e7bdb968c37d1ea12fd | 4,645 | [
-1
] |
4,646 | card-edit.html | OpenBookStore_openbookstore/src/web/templates/card-edit.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div class="container is-fullheight" style="margin-bottom: 10em">
<div class="section">
<div class="columns is-centered">
<div class="card-content column">
{% for msg in messages/status %}
<div class="notification {{ msg.class }}">
<button class="delete"></button>
{{ msg.message }}
</div>
{% endfor %}
<div class="box content">
<h3 class="h3"> Edit: {{ card.title }} </h3>
<form action="/card/update/{{ card.id }}" method="POST">
<div class="field">
<div class="control">
<label class="label"> Title* </label>
<input type="text" for="title" name="title" id="title"
value="{{ card.title }}"
placeholder="Title"
required="true"
class="input"/>
</div>
</div>
<div class="field">
<div class="control">
<label class="label"> ISBN </label>
<input type="text" for="isbn" name="isbn" id="isbn"
{% if card.isbn %}
value="{{ card.isbn }}"
{% endif %}
placeholder="title"
required="true"
class="input"/>
</div>
</div>
<div class="control">
<label class="label"> Authors </label>
<input type="text" for="authors" name="authors" id="authors"
{% if card.authors %}
value="{{ card.authors }}"
{% endif %}
class="input"
placeholder="authors"/>
</div>
<div class="control">
<label class="label"> Price </label>
<input type="text" for="price" name="price" id="price"
{% if card.price %}
value="{{ card.price | price }}"
{% endif %}
class="input"
pattern="[0-9].*"
placeholder="price" />
</div>
<div class="control">
<label class="label"> Shelf </label>
<div class="select">
<select id="shelf-id" name="shelf-id" for="shelf-id">
<option value=""> </option>
{% for shelf in shelves %}
{% if card.shelf.id == shelf.id %}
<option value="{{ shelf.id }}" selected> {{ shelf.name }} </option>
{% else %}
<option value="{{ shelf.id }}"> {{ shelf.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
<!-- <input type="text" for="title" name="title" id="title" placeholder="title"/> -->
<input type="submit" value="Save" class="button is-success" style="margin-top: 5px">
</form>
</div>
<!-- <div id="quantity"> -->
<!-- En stock: {{ card | quantity }} -->
<!-- </div> -->
<!-- <table id="place-copies-table" class="table"> -->
<!-- {% for place-copy in places-copies %} -->
<!-- <tr id="place-copy{{ place-copy.id }}"> -->
<!-- <td> -->
<!-- {{ place-copy | name }} -->
<!-- </td> -->
<!-- <td> -->
<!-- {{ place-copy | quantity }} -->
<!-- </td> -->
<!-- </tr> -->
<!-- {% endfor %} -->
<!-- </table> -->
<!-- {% block subinfo %} -->
<!-- TODO this is a bodge around no in boolean operator for if in djula -->
<!-- {% for role in current-user-roles %} -->
<!-- {% ifequal role "editor" %} -->
<!-- {% endifequal %} -->
<!-- {% endfor %} -->
<!-- {% endblock subinfo %} -->
</div>
</div>
</div>
</div>
{% block script %}
<script>
window.addEventListener('load', (event) => {
const quantityInput = document.getElementById('quantity-input');
quantityInput.focus();
quantityInput.setSelectionRange(0, -1);
});
document.addEventListener('DOMContentLoaded', () => {
(document.querySelectorAll('.notification .delete') || []).forEach(($delete) => {
$notification = $delete.parentNode;
$delete.addEventListener('click', () => {
$notification.parentNode.removeChild($notification);
});
});
});
</script>
{% endblock script %}
{% endblock %}
| 4,628 | Common Lisp | .l | 122 | 26.163934 | 97 | 0.446628 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | fe7350aa7b695caea604f56d578b3e6ce569ff8fe97b228a66382ef2f7e64d95 | 4,646 | [
-1
] |
4,647 | card-stock.html | OpenBookStore_openbookstore/src/web/templates/card-stock.html | {% extends "card-page.html" %}
{% block media_header %}
<button class="button" onclick="card_remove_one({{ card.id }})">-1</button>
<button class="button" onclick="card_add_one({{ card.id }})">+1</button>
{% endblock media_header %}
{% block subinfo %}
{% if raw == "t" %}
<pre>
{{ card | describe }}
</pre>
{% endif %}
<!-- TODO super tag doesn't seem to work
and now block.super doesn't seem to work either??
maybe I am making a silly mistake?-->
{{ block.super }}
{% endblock subinfo %}
{% block script %}
{{ block.super }}
<script>
async function card_add_one(id) {
// XXX: HTMX!
let data = new FormData();
data.set("id", id);
const resp = await fetch('/api/card/add', {
method: 'POST',
body: data
})
.then(data => console.log(data));
// either update the field...
/* let elt = document.getElementById("quantity"); */
/* here update the quantity */
/* elt.innerText = quantity; */
/* either do a page reload */
location.reload(); // nearly invisible
}
async function card_remove_one(id) {
let data = new FormData();
data.set("id", id);
const resp = await fetch('/api/card/remove', {
method: 'POST',
body: data
})
.then(data => console.log(data));
location.reload(); // nearly invisible
}
</script>
{% endblock script %}
| 1,384 | Common Lisp | .l | 47 | 25.085106 | 75 | 0.593539 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 3c3a21f75ca72ae38a5a9d0cec3871bde2f234873d8644bc74b51449e19918f9 | 4,647 | [
-1
] |
4,648 | receive-ws.html | OpenBookStore_openbookstore/src/web/templates/receive-ws.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div hx-ext="ws" ws-connect="ws://localhost:4432/echo">
<div id="body"></div>
WS notifications here:
<form id="form" ws-send>
<input name="chat_message">
</form>
<div id="notifications"></div>
<br>
<div id="id-livres"></div>
</div>
{% endblock %}
| 387 | Common Lisp | .l | 16 | 20.125 | 57 | 0.577348 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 2dacd04436085a4824cb4e6927a110765a44430680086d7703022d3a85406f2a | 4,648 | [
-1
] |
4,649 | dashboard.html | OpenBookStore_openbookstore/src/web/templates/dashboard.html | {% extends "base.html" %}
{% block content %}
<section class="hero is-info welcome is-small">
<div class="hero-body">
<div class="container">
<h1 class="title">
Hello, Admin.
</h1>
<h2 class="subtitle">
I hope you are having a great day!
</h2>
</div>
</div>
</section>
<section class="info-tiles">
<div class="tile is-ancestor has-text-centered">
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> {{ data.nb-titles }} </p>
<p class="subtitle"> Nombre de titres </p>
</article>
</div>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> {{ data.nb-books }} </p>
<p class="subtitle"> Nombre de livres </p>
</article>
</div>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> {{ data.nb-titles-negative }} </p>
<p class="subtitle"> Titres en stock négatif </p>
</article>
</div>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title"> Many </p>
<p class="subtitle"> cool things to do today </p>
</article>
</div>
</div>
</section>
<div class="columns">
<div class="column is-6">
<div class="card events-card">
<header class="card-header">
<p class="card-header-title">
Outdated loans ({{ data.nb-outdated-loans }})
</p>
<a href="#" class="card-header-icon" aria-label="more options">
<span class="icon">
<i class="fa fa-angle-down" aria-hidden="true"></i>
</span>
</a>
</header>
<div class="card-table">
<div class="content">
<table class="table is-fullwidth is-striped">
<tbody>
{% for loan in data.outdated-loans %}
<tr>
<td width="5%"><i class="fa fa-bell-o"></i></td>
<td>
<a href="/card/{{ loan.book-id }}">{{ loan.book-id | print-book }}
</a>
lended to {{ loan.contact-id | print-contact }}, due on {{ loan.due-date | date-hour-minute }} </td>
<td class="level-right"><a class="button is-small is-primary" href="#">Action</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<footer class="card-footer">
<a href="/stock/loans?outdated=t" class="card-footer-item">View All</a>
</footer>
</div>
</div>
<div class="column is-6">
<div class="card">
<header class="card-header">
<p class="card-header-title">
Quick search
</p>
<a href="#" class="card-header-icon" aria-label="more options">
<span class="icon">
<i class="fa fa-angle-down" aria-hidden="true"></i>
</span>
</a>
</header>
<div class="card-content">
<div class="content">
<form action="/search">
<div class="control has-icons-left has-icons-right">
<input class="input is-large" name="q" type="text" placeholder="Search by title, author and ISBN">
<span class="icon is-medium is-left">
<i class="fa fa-search"></i>
</span>
<span class="icon is-medium is-right">
<i class="fa fa-check"></i>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
| 3,583 | Common Lisp | .l | 109 | 24.275229 | 118 | 0.516734 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | b6af6c4e59a79aaf7575343e9e2007083640bfdb912cd8a7f80aed5d0899326e | 4,649 | [
-1
] |
4,650 | card-create.html | OpenBookStore_openbookstore/src/web/templates/card-create.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div class="container is-fullheight" style="margin-bottom: 10em">
<div class="section">
<div class="columns is-centered">
<div class="card-content column">
{% for msg in messages/status %}
<div class="notification {{ msg.class }}">
<button class="delete"></button>
{{ msg.message }}
</div>
{% endfor %}
<div class="box content">
<h3 class="h3"> Create a new book </h3>
<!-- <div> {{ card | describe }} </div> -->
<form action="/card/create" method="POST">
<div class="field">
<div class="control">
<label class="label"> Title* </label>
<input type="text" for="title" name="title" id="title"
{% if card.title %}
value="{{ card.title }}"
{% endif %}
placeholder="title"
required="true"
class="input"/>
</div>
</div>
<div class="field">
<div class="control">
<label class="label"> ISBN </label>
<input type="text" for="isbn" name="isbn" id="isbn"
minlength="4"
maxlength="13"
pattern="[0-9].*"
{% if card.isbn %}
value="{{ card.isbn }}"
{% endif %}
placeholder="ISBN"
class="input"/>
</div>
</div>
<div class="control">
<label class="label"> Authors </label>
<input type="text" for="authors" name="authors" id="authors"
{% if card.authors %}
value="{{ card.authors }}"
{% endif %}
class="input"
placeholder="authors"/>
</div>
<div class="control">
<label class="label"> Price </label>
<input type="text" for="price" name="price" id="price"
{% if card.price %}
value="{{ card.price }}"
{% endif %}
class="input"
placeholder="price"/>
</div>
<!-- Select an existing shelf -->
<div class="control">
<label class="label"> Shelf </label>
<div class="select">
<select id="shelf-id" name="shelf-id" for="shelf-id">
<option value=""> </option>
{% for shelf in shelves %}
{% if card.shelf.id == shelf.id %}
<option value="{{ shelf.id }}" selected> {{ shelf.name }} </option>
{% else %}
<option value="{{ shelf.id }}"> {{ shelf.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<!-- or create a new shelf by giving a new name -->
<div>
<label>
Or, create a new shelf:
</label>
<input type="text" for="new_shelf_name" name="new_shelf_name" id="new_shelf_name"
{% if more-form-data.new-shelf-name %}
value="{{ more-form-data.new-shelf-name }}"
{% endif %}
class="input"
placeholder="New shelf"/>
</div>
</div>
<!-- <input type="text" for="title" name="title" id="title" placeholder="title"/> -->
<input type="submit" value="Save" class="button">
</form>
</div>
<!-- <div id="quantity"> -->
<!-- En stock: {{ card | quantity }} -->
<!-- </div> -->
<!-- <table id="place-copies-table" class="table"> -->
<!-- {% for place-copy in places-copies %} -->
<!-- <tr id="place-copy{{ place-copy.id }}"> -->
<!-- <td> -->
<!-- {{ place-copy | name }} -->
<!-- </td> -->
<!-- <td> -->
<!-- {{ place-copy | quantity }} -->
<!-- </td> -->
<!-- </tr> -->
<!-- {% endfor %} -->
<!-- </table> -->
<!-- {% block subinfo %} -->
<!-- TODO this is a bodge around no in boolean operator for if in djula -->
<!-- {% for role in current-user-roles %} -->
<!-- {% ifequal role "editor" %} -->
<!-- {% endifequal %} -->
<!-- {% endfor %} -->
<!-- {% endblock subinfo %} -->
</div>
</div>
</div>
</div>
{% block script %}
<script>
window.addEventListener('load', (event) => {
const quantityInput = document.getElementById('quantity-input');
quantityInput.focus();
quantityInput.setSelectionRange(0, -1);
});
document.addEventListener('DOMContentLoaded', () => {
(document.querySelectorAll('.notification .delete') || []).forEach(($delete) => {
$notification = $delete.parentNode;
$delete.addEventListener('click', () => {
$notification.parentNode.removeChild($notification);
});
});
});
</script>
{% endblock script %}
{% endblock %}
| 5,356 | Common Lisp | .l | 139 | 25.589928 | 97 | 0.432266 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | ebbcdf854fb9fe3425115e24adaf1ebce1a1ac3270eae07f7580c68effb54e9b | 4,650 | [
-1
] |
4,651 | 404.html | OpenBookStore_openbookstore/src/web/templates/404.html | {% extends "base.html" %}
{% block content %}
<section class="hero is-light is-bold is-fullheight">
<div class="hero-body">
<div class="container">
<section class="section">
<div class="columns">
<div class="column is-8 is-offset-2">
<div class="content is-medium">
<h1 class="title">Not found</h1>
</div>
</div>
</div>
</section>
</div>
</div>
</section>
{% endblock %}
| 500 | Common Lisp | .l | 18 | 19.611111 | 53 | 0.509434 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | c91d1cfceccb72b2c24519df60122d3546f3795bd0cc8c3e4ed608760d4fe1e2 | 4,651 | [
-1
] |
4,652 | sell.html | OpenBookStore_openbookstore/src/web/templates/sell.html | {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div id="vue-sell">
<div class="title is-4"> Sell </div>
<div class="field has-addons">
<div class="control is-expanded">
<div class="columns">
<div class="column">
<b-field>
<b-datepicker v-model="sellDate" icon="calendar-today"></b-datepicker>
</b-field>
</div>
<div class="column">
<b-field>
<b-input disabled v-model="client" placeholder="Client" ></b-input>
</b-field>
</div>
</div>
<h3 class="title is-4"> {$ {{quantity}} $} titles selected. Total: {$ {{total}} $} €
</h3>
<b-field>
<b-autocomplete placeholder="Search by any ISBN or by keywords in your stock..."
id="default-input"
v-model="search"
field="title"
:data="suggestions"
:loading="isFetching"
@typing="getAsyncData"
@select="option => itemSelected(option)">
<template slot-scope="props">{$ {{ props.option.title }} $}</template>
</b-autocomplete>
</b-field>
<div class="buttons">
<b-field label="Validate with">
<button class="button is-success"
v-for="payment in paymentMethods"
@click="completeSale(payment.id)"
:value="payment.id">
{$ {{ payment.name }} $}
</button>
</b-field>
</div>
<div v-for="(book, index) in books" :key="index">
<div class="box content" v-if="book.show">
<div v-if="book.card" class="title is-6">
<a v-bind:href="book.url" target="_blank">
{$ {{ book.card.title }} $}
</a>
</div>
<div class="tile is-ancestor">
<div class="tile">
<b-field label="Input" v-if="book.error"
type="is-danger"
:message="book.error">
<b-input disabled :value="book.input"></b-input>
</b-field>
<b-field label="Input" v-else-if="book.input && !book.card">
<b-input disabled loading :value="book.input"></b-input>
</b-field>
</div>
<div class="tile" >
<b-field v-if="book.card">
<p class="control">
<b-button label="X" />
</p>
<b-numberinput v-model="book.quantity" controls-alignment="right" controls-position="compact"></b-numberinput>
</b-field>
</div>
<div class="tile" style="padding-left: 3em">
<b-field v-if="book.card">
<b-input v-model.number="book.price_sold"> </b-input>
</b-field>
<p class="control">
<b-button label="€" />
</p>
</div>
<div class="tile" style="padding-left: 3em">
<b-button type="is-danger" @click="removeBook(index)" outlined>
<span class="icon">
<i class="fas fa-times"></i>
</span>
</b-button>
</div>
</div>
</div>
</div>
<!-- <b-button @click="completeSale" >Submit</b-button> -->
<div>{$ {{ message }} $}</div>
</div>
</div>
</div>
{% endblock %}
| 3,765 | Common Lisp | .l | 95 | 24.715789 | 130 | 0.435391 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 8f851203525612e279967fb27b13e60d17c6e1efb516f2c33d38ff06bb769ac0 | 4,652 | [
-1
] |
4,653 | permission-denied.html | OpenBookStore_openbookstore/src/web/templates/permission-denied.html | {% extends "base.html" %}
{% block content %}
{% if current-user %}
<section class="hero is-warning">
<div class="hero-body">
<div class="container">
<h1 class="title" >Unauthorized</h1>
<h2>You do not have permission to view this page.</h2>
</div>
</div>
</section>
{% else %}
<section class="hero is-info">
<div class="hero-body">
<div class="container">
<h1 class="title" >You are logged out</h1>
<h2>You will need to login to access this page</h2>
</div>
</div>
</section>
{% endif %}
{% endblock %}
| 603 | Common Lisp | .l | 22 | 21.909091 | 66 | 0.569204 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | a9e14f2bacb04d7895f88522f2bffbdcdcd58c852bbaed320874cb572e1830b7 | 4,653 | [
-1
] |
4,654 | base.html | OpenBookStore_openbookstore/src/web/templates/base.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bulma, Buefy -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/buefy/dist/buefy.min.css">
<script src="https://unpkg.com/buefy/dist/buefy.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<!-- Icons for default Buefy theme -->
<link rel="stylesheet" href="https://cdn.materialdesignicons.com/5.3.45/css/materialdesignicons.min.css">
<!-- Notiflix: cool notification -->
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/AIO/notiflix-aio-2.1.3.min.js"></script>
<!-- HTMX -->
<!-- <script src="https://unpkg.com/[email protected]"></script> -->
<script src="https://unpkg.com/[email protected]" integrity="sha384-cZuAZ+ZbwkNRnrKi05G/fjBX+azI9DNOkNYysZ0I/X5ZFgsmMiBXgDZof30F5ofc" crossorigin="anonymous"></script>
<!-- WebSocket extension -->
<script src="https://unpkg.com/htmx.org/dist/ext/ws.js"></script>
<!-- stylo editor -->
<script type="module" src="https://unpkg.com/@papyrs/stylo@latest/dist/stylo/stylo.esm.js"></script>
<!-- Other JS and UI helpers -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<!-- The app JS (global. More JS can be loaded per page) -->
<script defer src="/static/openbookstore.js"></script>
<!-- The app CSS -->
<!-- <link rel="stylesheet" type="text/css" href="/static/css/admin.css"> -->
<title>{% block title %} OpenBookStore {% endblock %}</title>
</head>
<body>
<!-- START NAV -->
<nav class="navbar is-white">
<div class="container">
<div class="navbar-brand">
<a class="navbar-item brand-text" href="/"> OpenBookStore </a>
<div class="navbar-burger burger" data-target="navMenu">
<span></span>
<span></span>
<span></span>
</div>
</div>
<div id="navMenu" class="navbar-menu">
<div class="navbar-start">
<a class="navbar-item" href="/">
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">
Database
</a>
<div class="navbar-dropdown" hx-boost="true">
<a class="navbar-item" href="/card/create">
New book
</a>
<a class="navbar-item" href="/stock/loans?outdated=t">
Outdated loans
</a>
</div>
</div>
</a>
<div id ="quick-search" class="navbar-item field">
<p class="control has-icons-right">
<b-autocomplete placeholder="ISBN or Keywords..."
v-model="name"
field="title"
:data ="data"
:loading="isFetching"
@typing="getAsyncData"
@select="option => itemSelected(option)"
><template slot-scope="props">{$ {{ props.option.title }} $}</template>
</b-autocomplete>
<span class="icon is-small is-right">
</span>
</p>
</div>
</div>
</div>
<div class="navbar-end" >
<div class="navbar-item" >
{% if current-user %}
<div class="dropdown is-hoverable">
<div class="dropdown-trigger" >
<button class="button" aria-haspopup="true" aria-controls="profile-dropdown" >
<span class="icon is-small" >
<i class="fas fa-user" aria-hidden="true"></i>
</span>
<span>{{ current-user | user-name }}</span>
</button>
</div>
<div class="dropdown-menu" role="menu" id="profile-dropdown">
<div class="dropdown-content" >
<div class="dropdown-item" >
<form action="/logout" method="POST" >
<button class="button is-light">Logout</button>
</form>
</div>
</div>
</div>
</div>
{% else %}
<form action="/login" >
<input name="referer-route" type="hidden" value="{{ request-uri }}"/>
<button class="button is-light" >Login</button>
</form>
{% endif %}
</div>
</div>
</nav>
<!-- END NAV -->
<!-- START MENU -->
<div class="container">
<div class="columns">
<div class="column is-2">
<aside class="menu is-hidden-mobile">
<p class="menu-label">
General
</p>
<ul class="menu-list">
<li>
<a hx-boost="true" {% if route == "/stock" %} class="is-active" {% endif %} href="/stock">
Stock
</a>
</li>
<li>
<span hx-boost="true">
<a {% if route == "/search" %} class="is-active" {% endif %} href="/search">
Search
</a>
</span>
</li>
<li>
<a {% if route == "/sell" %} class="is-active" {% endif %} href="/sell">
Sell
</a>
</li>
<li>
<span hx-boost="true">
<a {% if route == "/history" %} class="is-active" {% endif %} href="/history">
History
</a>
</span>
</li>
<li>
<a {% if route == "/receive" %} class="is-active" {% endif %} href="/receive">
Receive
</a>
</li>
</ul>
</aside>
</div>
<div class="column is-9">
{% block content %} {% endblock %}
</div>
</div>
</div>
<footer class="footer" style="margin-top: 15em">
<div class="content has-text-centered">
<p>
<strong>OpenBookStore</strong> version <a href="#"> 0.01</a>. The <a href="https://github.com/OpenBookStore/openbookstore"> source code </a> is licensed under the GPLv3. <a href="https://github.com/sponsors/vindarel/"> We need your support! </a>
</p>
</div>
</footer>
</body>
<script>
// bulma.js: hamburger toggle for mobile.
(function() {
var burger = document.querySelector('.burger');
var menu = document.querySelector('#'+burger.dataset.target);
burger.addEventListener('click', function() {
burger.classList.toggle('is-active');
menu.classList.toggle('is-active');
});
})();
</script>
</html>
| 7,398 | Common Lisp | .l | 177 | 29.355932 | 255 | 0.49611 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 23bc0d4358ee0a6a55f7cc1dd25cf774abbe2d8191ce027f584559bb41802f37 | 4,654 | [
-1
] |
4,655 | stock.html | OpenBookStore_openbookstore/src/web/templates/stock.html | {% extends "search.html" %}
<!-- The loop over results is factorized with the search.html template, but
the search form and the card presentation are different. So… not much
in common (any more).
-->
{% block search_form %}
<form id="search-form" action="{{ route }}" style="margin-bottom: 3em;" hx-target="results">
<div class="field">
<label class="label"> Search </label>
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" name="q" type="text" {% if q %} value="{{ q }}" {% else %} placeholder="Search by title, author and ISBN" {% endif %}>
</div>
<div class="control">
<button type="submit" class="button is-primary"> Search </button>
</div>
</div>
</div>
<div class="field is-grouped is-grouped-multiline">
<div class="field has-addons">
<div hidden="true" data-shelves="{{ shelves }}"></div>
<div class="select is-link">
<select id="shelf" name="shelf"
onkeypress="if (event.keyCode == 13) {
let form = document.getElementById('search-form');
form.submit();
}"
>
<option value="-1" selected> Select shelf </option>
{% for shelf in shelves %}
{% if shelf.id == form-shelf.id %}
<option value="{{ shelf.name-ascii }}" selected> {{ shelf.name }} </option>
{% else %}
<option value="{{ shelf.name-ascii }}"> {{ shelf.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<!-- Add grouped controls here
<p class="control">
<a class="button">
One
</a>
</p>
-->
</div>
</div>
{% if q and nb-results == 0 %}
<div class="columns is-centered">
<div class="is-half">
<p class="is-primary">
No results
</p>
</div>
</div>
{% endif %}
</form>
{% endblock search_form %}
{% block card_content %}
<!-- search results -->
<div class="content">
<a href="{{ card | url }}">
<h4> {{ card.title }} </h4>
</a>
<p>
<span> {{ card.authors }} </span>
<span> {{ card.isbn }} </span>
{% if card.shelf %}
<span class="tag">
<a color="black"
title="Search your stock"
href="/stock?shelf={{ card.shelf.name-ascii }}">
{{ card.shelf.name }}
</a>
</span>
{% endif %}
<span> {{ card.publisher | capfirst }} </span>
</p>
</div>
{% endblock card_content %}
| 2,601 | Common Lisp | .l | 80 | 24.9 | 147 | 0.521791 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 3f38676ce240edf46a61ef1da7796c6b76f5823e3bff7c5816035fc2c52d8830 | 4,655 | [
-1
] |
4,658 | build.yaml | OpenBookStore_openbookstore/.github/workflows/build.yaml | # Build a Ubuntu and Windows binary.
#
# https://github.com/melusina-org/make-common-lisp-program/actions/runs/6415297009/workflow
name: 'Windows build'
# Takes 13min to install QL dependencies…
# windows: Unable to load foreign library (READLINE).
# Error opening shared object "libreadline.dll":
on:
workflow_dispatch:
push:
branches-ignore:
- v1
tags-ignore:
- v1.*
jobs:
build-on-tier-1-platforms:
strategy:
matrix:
implementation: ['sbcl']
# there is also 'ubuntu-latest', 'macos-latest'
os: ['windows-latest']
runs-on: '${{ matrix.os }}'
name: 'Build on Tier 1 Platform (Windows for now)'
timeout-minutes: 20
steps:
# Clone our repository.
- uses: actions/checkout@v4
# - name: 'Install MacPorts'
# if: runner.os == 'macOS'
# uses: melusina-org/setup-macports@v1
- name: 'Setup Common Lisp'
uses: melusina-org/setup-common-lisp@v1
with:
implementation: '${{ matrix.implementation }}'
- name: 'Setup Quicklisp'
uses: melusina-org/setup-quicklisp@v1
id: quicklisp
with:
implementation: '${{ matrix.implementation }}'
# - name: 'Install CL-GITHUB-ACTIONS'
# uses: actions/checkout@v4
# with:
# repository: melusina-org/cl-github-actions
# path: ${{ steps.quicklisp.outputs.quicklisp-local-projects }}/cl-github-actions
# - name: 'Run unit tests'
# uses: melusina-org/run-common-lisp-program@v1
# with:
# implementation: '${{ matrix.implementation }}'
# system: 'org.melusina.github-action.make-common-lisp-program/testsuite'
# entrypoint: 'unit-tests'
# Build:
- name: 'Build OpenBookStore'
run: make build
id: make
# with:
# implementation: '${{ matrix.implementation }}'
# system: 'org.melusina.reference-utility/executable'
# Publish:
# does this work?
- name: 'Upload binary'
uses: actions/upload-artifact@v3
with:
name: openbookstore binary ${{ matrix.implementation }} ${{ runner.os }} ${{ runner.arch }}
path: ${{ steps.make.outputs.build-pathname }}
# or just say bin/* ?
if-no-files-found: error
| 2,329 | Common Lisp | .l | 66 | 28.469697 | 101 | 0.614736 | OpenBookStore/openbookstore | 34 | 5 | 0 | AGPL-3.0 | 9/19/2024, 11:26:19 AM (Europe/Amsterdam) | 147be65c1f184eaf36f0cf38457d7fbde9faebf3bf5985c9bf192cdea349de84 | 4,658 | [
-1
] |
4,677 | compile.lisp | informatimago_lisp/compile.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: compile.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Compile all the libraries with ASDF.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-01 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load #P"~/quicklisp/setup.lisp")
(let ((path (merge-pathnames
(make-pathname :directory '(:relative "TOOLS")
:name "INIT-ASDF" :type "LISP" :case :common)
*load-pathname*)))
#+abcl (setf path (pathname (string-downcase (namestring path))))
(format t "~&;;;;; Loading ~S~%" path)
(load path :verbose t))
;; Add all the subdirectories containing a .asd file to
;; asdf:*central-registry*.
(setf asdf:*central-registry*
(append (remove-duplicates
(mapcar (lambda (path)
(make-pathname :name nil :type nil :version nil :defaults path))
(directory "**/*.asd"))
:test (function equalp))
asdf:*central-registry*))
(asdf-load :cl-ppcre)
#-abcl
(asdf-load :com.informatimago.common-lisp)
#-abcl
(asdf-load :com.informatimago.clmisc)
#-(or abcl ccl cmu ecl sbcl)
(asdf-load :com.informatimago.clext)
;; #+sbcl
;; (asdf-load :com.informatimago.sbcl)
#+clisp
(asdf-load :com.informatimago.clisp)
#+clisp
(asdf-load :com.informatimago.susv3)
;;;; THE END ;;;;
| 2,570 | Common Lisp | .lisp | 66 | 35.257576 | 89 | 0.599277 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 39aa85ca793c6dddbcf27b44342104c2928f8217dddcfc74ba1fc98bdab7a929 | 4,677 | [
-1
] |
4,678 | systems-for-quicklisp.sexp | informatimago_lisp/systems-for-quicklisp.sexp | (
"com.informatimago.clext"
"com.informatimago.clext.association"
"com.informatimago.clisp"
"com.informatimago.clmisc"
"com.informatimago.common-lisp"
"com.informatimago.common-lisp.apple-file"
"com.informatimago.common-lisp.arithmetic"
"com.informatimago.common-lisp.bank"
"com.informatimago.common-lisp.cesarum"
"com.informatimago.common-lisp.csv"
"com.informatimago.common-lisp.data-encoding"
"com.informatimago.common-lisp.diagram"
"com.informatimago.common-lisp.ed"
"com.informatimago.common-lisp.graphviz"
"com.informatimago.common-lisp.heap"
"com.informatimago.common-lisp.html-base"
"com.informatimago.common-lisp.html-generator"
"com.informatimago.common-lisp.html-parser"
"com.informatimago.common-lisp.http"
"com.informatimago.common-lisp.interactive"
"com.informatimago.common-lisp.invoice"
"com.informatimago.common-lisp.lisp"
"com.informatimago.common-lisp.lisp-reader"
"com.informatimago.common-lisp.lisp-sexp"
"com.informatimago.common-lisp.lisp-text"
"com.informatimago.common-lisp.lisp.ibcl"
"com.informatimago.common-lisp.lisp.stepper"
"com.informatimago.common-lisp.parser"
"com.informatimago.common-lisp.picture"
"com.informatimago.common-lisp.regexp"
"com.informatimago.common-lisp.rfc2822"
"com.informatimago.common-lisp.rfc3548"
"com.informatimago.common-lisp.telnet"
"com.informatimago.common-lisp.unix"
"com.informatimago.languages.cxx"
"com.informatimago.languages.lua"
"com.informatimago.linc"
"com.informatimago.lispdoc"
"com.informatimago.objcl"
"com.informatimago.rdp"
"com.informatimago.rdp.basic"
"com.informatimago.rdp.example"
"com.informatimago.susv3"
"com.informatimago.tools"
"com.informatimago.tools.check-asdf"
"com.informatimago.tools.make-depends"
"com.informatimago.tools.manifest"
"com.informatimago.tools.pathname"
"com.informatimago.tools.quicklisp"
"com.informatimago.tools.symbol"
"com.informatimago.xcode"
)
| 1,857 | Common Lisp | .lisp | 53 | 34.037736 | 46 | 0.840355 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bd4c51664f864f35d5ab5f198e2c6d951da83747ecd071a9ebe8a1b193d43233 | 4,678 | [
-1
] |
4,679 | test-all-systems.lisp | informatimago_lisp/test-all-systems.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: test-all-systems.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A script loading all my systems verbosely, to check they all compile.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-06-20 <PJB> Recently created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal. Bourguignon 2013 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(ql:register-local-projects)
(defparameter *systems*
'(
:com.informatimago.xcode
:com.informatimago.rdp.example
:com.informatimago.rdp.basic.example
:com.informatimago.rdp.basic
:com.informatimago.rdp
:com.informatimago.lispdoc
:com.informatimago.linc
:com.informatimago.languages.lua
:com.informatimago.languages.cxx
:com.informatimago.common-lisp.unix
:com.informatimago.common-lisp.tools.make-depends
:com.informatimago.common-lisp.telnet
:com.informatimago.common-lisp.rfc3548
:com.informatimago.common-lisp.rfc2822
:com.informatimago.common-lisp.regexp
:com.informatimago.common-lisp.picture
:com.informatimago.common-lisp.parser
:com.informatimago.common-lisp.lisp.stepper
:com.informatimago.common-lisp.lisp.ibcl
:com.informatimago.common-lisp.lisp-text
:com.informatimago.common-lisp.lisp-sexp
:com.informatimago.common-lisp.lisp-reader
:com.informatimago.common-lisp.lisp
:com.informatimago.common-lisp.invoice
:com.informatimago.common-lisp.interactive
:com.informatimago.common-lisp.http
:com.informatimago.common-lisp.html-parser
:com.informatimago.common-lisp.html-generator
:com.informatimago.common-lisp.html-base
:com.informatimago.common-lisp.heap
:com.informatimago.common-lisp.graphviz
:com.informatimago.common-lisp.ed
:com.informatimago.common-lisp.diagram
:com.informatimago.common-lisp.data-encoding
:com.informatimago.common-lisp.csv
:com.informatimago.common-lisp.cesarum
:com.informatimago.common-lisp.bank
:com.informatimago.common-lisp.arithmetic
:com.informatimago.common-lisp.apple-file
:com.informatimago.common-lisp
:com.informatimago.clmisc
#-sbcl :com.informatimago.clext
#+clisp :com.informatimago.susv3
#+clisp :com.informatimago.clisp
#+(and ccl darwin) :com.informatimago.objcl ; macosx even.
#+(and ccl darwin) :com.informatimago.cocoa-playground ; macosx even.
))
(dolist (sys *systems*)
(handler-case
(ql:quickload sys :verbose t)
(error (err)
(format t "~2%Error while loading system ~A~%~A~%" sys err))))
| 3,706 | Common Lisp | .lisp | 90 | 37.844444 | 83 | 0.680321 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 1d0c37b2db366dd1a5872bc64521829f6f81c16d401847a258115e30c602f94d | 4,679 | [
-1
] |
4,680 | post-clisp.awk | informatimago_lisp/post-clisp.awk | BEGIN{
"pwd"|getline pwd
# "/usr/local/bin/clisp -q -norc -ansi -x \"(princ(namestring (truename \\\"$(pwd)/\\\")))\""|getline pwd
}
/Compiling file /{
file=$4;
if(substr(file,0,length(pwd))==pwd){
file=substr(file,1+length(pwd));
}
next;
}
/; *Loading file /{
file=$4;
if(substr(file,0,length(pwd))==pwd){
file=substr(file,1+length(pwd));
}
next;
}
/WARNING in.*in lines/{
start=index($0,"WARNING in ")+length("WARNING in ");
fn=substr($0,start,index($0," in lines ")-start);
start=index($0," in lines ")+length(" in lines ");
lines=substr($0,start,index(substr($0,start)," ")-1);
split(lines,n,"\\.");
w="WARNING";
next;
}
/ERROR.*in lines/{
start=index($0,"ERROR in ")+length("WARNING in ");
fn=substr($0,start,index($0," in lines ")-start);
start=index($0," in lines ")+length(" in lines ");
lines=substr($0,start,index(substr($0,start)," ")-1);
split(lines,n,"\\.");
w="ERROR";
next;
}
{
if(w!=""){
printf "%s:%s:1:\n%s:%s:2:%s in %s: %s\n",file,n[1],file,n[3],w,fn,$0;
w="";
}else{
print $0;
}
}
| 1,155 | Common Lisp | .lisp | 44 | 21.772727 | 109 | 0.547016 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 2545a359133fb447f2c6a604a523ef5403db3f200038ea1d4b3242367fc5ea85 | 4,680 | [
-1
] |
4,681 | tools.lisp | informatimago_lisp/susv3/tools.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: tools.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Utilities for implementing SUSV3 API.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2005-04-04 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2005 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages)
(also-use-packages "FFI"))
(defpackage "COM.INFORMATIMAGO.SUSV3.TOOLS"
(:documentation
"Utilities for implementing SUSV3 API.")
(:use "COMMON-LISP")
(:export
"DEFINE-FFI-COPIERS"))
(in-package "COM.INFORMATIMAGO.SUSV3.TOOLS")
(defmacro define-ffi-copiers (&rest arguments)
"
ARGUMENTS:
(define-ffi-copiers (lisp-structure ffi-struct to-name from-name) slot...)
(define-ffi-copiers lisp-structure ffi-struct slot...)
SLOT:
(lisp-slot ffi-slot) ; for simple types.
((lisp-slot lisp-structure) (ffi-slot ffi-structure) ; for structure types.
DO: Generates two macros, named TO-NAME and FROM-NAME,
or {LIST-STRUCTURE}->{FFI-STRUCT} and {FFI-STRUCT}->{LIST-STRUCTURE}
to copy between LISP and FFI structures.
For slots that are simple, SETF is used.
For slots that are structures, the names {LIST-STRUCTURE}->{FFI-STRUCT}
and {FFI-STRUCT}->{LIST-STRUCTURE} built from the types given with
the slot are used.
NOTE: It's advised to keep the l->f and f->l format for TO-NAME and FROM-NAME,
to be able to use l and f as slot type...
"
(let (lisp-structure ffi-struct slots to-name from-name)
(if (listp (car arguments))
(setf lisp-structure (first (car arguments))
ffi-struct (second (car arguments))
to-name (third (car arguments))
from-name (fourth (car arguments))
slots (cdr arguments))
(progn
(setf lisp-structure (car arguments)
ffi-struct (cadr arguments)
slots (cddr arguments))
(setf to-name (intern (with-standard-io-syntax
(format nil "~A->~A"
lisp-structure ffi-struct))
(symbol-package lisp-structure))
from-name (intern (with-standard-io-syntax
(format nil "~A->~A"
ffi-struct lisp-structure))
(symbol-package lisp-structure)))))
(let ((complex-slots (remove-if (lambda (slot) (atom (first slot))) slots))
(simple-slots (remove-if (lambda (slot) (not (atom (first slot))))
slots)))
`(progn
(defmacro ,to-name (src dst)
`(progn
,,@(mapcar
(lambda (slot)
(list
'list
(list 'quote (intern (with-standard-io-syntax
(format nil "~A->~A"
(second (first slot))
(second (second slot))))
(symbol-package (second (first slot)))))
(list 'list (list 'quote (first (first slot))) 'src)
(list 'list ''ffi:slot 'dst
(list 'quote (list 'quote (first (second slot)))))))
complex-slots)
(setf ,,@(mapcan
(lambda (slot)
(list
(list 'list ''ffi:slot 'dst
(list 'quote (list 'quote (second slot))))
(list 'list (list 'quote (first slot)) 'src)))
simple-slots))
,dst))
(defmacro ,from-name (src dst)
`(progn
,,@(mapcar
(lambda (slot)
(list
'list
(list 'quote (intern (with-standard-io-syntax
(format nil "~A->~A"
(second (second slot))
(second (first slot))))
(symbol-package (second (first slot)))))
(list 'list ''ffi:slot 'src
(list 'quote (list 'quote (first (second slot)))))
(list 'list (list 'quote (first (first slot))) 'dst)))
complex-slots)
(setf ,,@(mapcan
(lambda (slot)
(list
(list 'list (list 'quote (first slot)) 'dst)
(list 'list ''ffi:slot 'src
(list 'quote (list 'quote (second slot))))))
simple-slots))
,dst))))))
;;;; THE END ;;;;
| 6,214 | Common Lisp | .lisp | 133 | 33.022556 | 83 | 0.482152 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e66f23dabdea5a277c55dc5060351e3b8af714644eb5380a8f855b80bc38d8fa | 4,681 | [
-1
] |
4,682 | process.lisp | informatimago_lisp/susv3/process.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: process.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: clisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Multiprocessing for clisp.
;;;;
;;;; This package doesn't implement threads like in other Common-Lisp
;;;; implementations. Rather it uses plain unix processes.
;;;; This has sever implications for IPC: there is no shared memory,
;;;; all inter-process communication must go thru pipes or sockets.
;;;;
;;;; http://www.franz.com/support/documentation/7.0/doc/multiprocessing.htm
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-11-23 <PJB> Added MAKE-PIPE.
;;;; 2004-09-23 <PJB> Added MAKE-XTERM-IO-STREAM.
;;;; 2004-08-03 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages)
(also-use-packages "LINUX"
"COM.INFORMATIMAGO.CLISP.RAW-MEMORY"))
(defpackage "COM.INFORMATIMAGO.SUSV3.PROCESS"
(:documentation "Implement a multiprocessing API for clisp.")
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.HEAP.HEAP"
"COM.INFORMATIMAGO.COMMON-LISP.HEAP.MEMORY"
"COM.INFORMATIMAGO.SUSV3.IPC")
(:export ))
(in-package "COM.INFORMATIMAGO.SUSV3.PROCESS")
(defclass scheduler-object ()
())
(defclass process (scheduler-object)
(
(name
:accessor process-name
:initarg :name
:type string
:initform nil)
(reset-action
:accessor process-reset-action
:initarg :reset-action
:type string
:initform nil)
(run-reasons
:accessor process-run-reasons
:initarg :run-reasons
:type string
:initform nil
:documentation "This function returns the list of run-reasons for
process. The list can be changed with setf or
related macros and this function or with
process-add-run-reason. Any Lisp object can be on
the list. A process will not run unless it has at
least one run reason and no arrest reasons (see
process-arrest-reasons).")
(arrest-reasons
:accessor process-arrest-reasons
:initarg :arrest-reasons
:type string
:initform nil
:documentation "This function returns the list of arrest-reasons
for process. The list can be changed with setf or
related macros and this function or with
process-add-arrest-reason. Any Lisp object can be
on the list. A process will not run unless it has
at least one run reason (see process-run-reasons)
and no arrest reasons.")
(priority
:accessor process-priority
:initarg :priority
:type string
:initform nil
:documentation "
This function returns the priority of process. It defaults to 0
and may be set to any fixnum with setf.
Returns the priority of process, which must be an instance of
PROCESS. Priority may be any real number. It defaults to 0. It
may be reset with setf and this function.
"
;;
;; IMPLEMENTATION:
;; So, real or fixnum?
;; We could use it to set the nice level.
;;
)
(quantum
:accessor process-quantum
:initarg :quantum
:type string
:initform nil
:documentation "
This function returns the quantum for process.
The quantum may be specified when the process is created; it
defaults to the value of *default-process-quantum* and may be set
to any real value between 0.1 and 20 with setf.
")
(initial-bindings
:accessor process-initial-bindings
:initarg :initial-bindings
:type string
:initform nil
:documentation "This slot of a process stores an alist of initial
special bindings which are established in a process
when it is started. The value may be set with setf.")
(message-interrupt-function
:accessor process-message-interrupt-function
:initarg :message-interrupt-function
:type string
:initform nil)
(stack-allocation
:accessor process-stack-allocation
:initarg :stack-allocation
:type string
:initform nil)
(run-immediately
:accessor process-run-immediately
:initarg :run-immediately
:type string
:initform nil)
;; ----------------------------------------
(property-list
:accessor process-property-list
:initarg :property-list
:type list
:initform nil
:documentation "The property-list slot of a process implements
a generalized property list as a convenient place
to store additional information about a process.")
(resume-hook
:accessor process-resume-hook
:initarg :resume-hook
:type (or null function)
:initform nil
:documentation "It is normal for execution of a process to be
interrupted many times. This is transparent to
the process and usually it is not necessary for
the process to know when its execution is
suspended and resumed. However, if these slots
are non-nil, they should be functions of no
arguments which are called on the process'
stack-group or thread each time the execution is
suspended or resumed (but not when the process is
first started or when it is killed).")
(suspend-hook
:accessor process-suspend-hook
:initarg :suspend-hook
:type (or null function)
:initform nil
:documentation "See documentation of RESUME-HOOK.")
(thread
:accessor process-thread
:initform nil
:documentation "The thread associated with process.")
(running :initform :idle)
(pid :accessor process-pid :initform 0 :type integer ))
(:documentation "")) ;;process
(defun symeval-in-process (symbol process)
"
This function returns two values. The first is the value of the
special symbol in the given thread (which may be the current
thread). It only looks for actual bindings on the thread; if the
symbol has a global value but is not bound on the thread, the global
value is not returned.
The second returned value describes the status of the binding. t is
returned if the symbol is bound on the thread, nil if the symbol has
no binding, and :unbound if there is a binding which has been
subjected to makunbound. In the latter two cases, the first returned
value is nil.
"
;;
;; IMPLEMENTATION:
;; If the process is self, evaluate the symbol here
;; Otherwise:
;; process-1 scheduler process-2
;; |-------(symeval-req)----->| |
;; | |-------(symeval-req)-------->|
;; | |<------(symeval-res)---------|
;; |<------(symeval-res)------| |
;;
(declare (ignore symbol process))
(error "not implemented yet")) ;;symeval-in-process
(defun profile-process-p (process)
"
This function returns the value of the profile-process-p flag for
the thread specified by process. If the value of the flag is
non-nil, then the space and time runtime analyzers will collect
samples when this process is executing.
"
;;
;; IMPLEMENTATION:
;; The scheduler can send periodically
;; a (progn (room t) (get-runt-time))-req to the profiled process.
;; (and perhaps backtrace too!)
;; We need the API to start the profiler and to collect statistics.
;;
(declare (ignore process))
(error "not implemented yet")) ;;profile-process-p
(defparameter *all-processes* nil
"
The value of this variable is a list of all processes that have ever
been created and have never completed or been killed.
The scheduler does not use this list; it is for debugging.
") ;;*all-processes*
;; IMPLEMENTATION:
;; The scheduler keeps an authoritative list of all processes.
;; *all-processes* is a symbol-macro that check the length of the list
;; and delete or create new process proxy objects as needed.
;;
;; 1- The process data is kept in shared memory pages and the processes
;; proxies just read this data.
;;
;; 2- The *all-processes* symbol-macro sends a request to the scheduler
;; and gets back process data to update the proxies.
;;
;; 1 is better, but implies a shared memory mechanisms (with FFI
;; or print/readabbly).
;;
(defparameter *default-process-quantum* 100
"
Default quantum given to each process.
This is not significant in the current implemetantion
where the underlying OS does the actual scheduling.
") ;;*default-process-quantum*
;; IMPLEMENTATION: Not significant.
(defun start-scheduler ()
"
Start the scheduler process and initialize multiprocessing.
Multiprocessing is not automatically started in the default
environment.
This function starts multiprocessing, which is also started
automatically the first time a process is started by
process-reset, directly or indirectly (as by
process-run-function).
"
(error "not implemented yet")) ;;start-scheduler
;; IMPLEMENTATION:
;; The initial process forks a child process that continues
;; and becomes the scheduler.
;; The child processes should ignore SIGINTR SIGTERM, etc, and let the
;; scheduler receive them and forward them to the children.
(defun make-process (&key (name "Anonymous")
(class 'process)
(reset-action nil) (run-reasons '()) (arrest-reasons '())
(resume-hook nil) (suspend-hook nil) (initial-bindings nil)
;; not useful:
(priority 0) (quantum 2) run-immediately
message-interrupt-function stack-allocation)
"
This function returns a new process object, but does nothing about
making it runnable.
"
;; IMPLEMENTATION:
;; process-1 scheduler process-2
;; |-------(newproc-req)----->| |
;; | |-----------(fork)----------->|
;; |<------(newproc-rep)------| |
;;
(declare (ignore name class reset-action run-reasons arrest-reasons resume-hook suspend-hook initial-bindings priority quantum run-immediately message-interrupt-function stack-allocation))
(error "not implemented yet")
#-(and)
(let ((pid (linux:|fork|)))
(cond
((= 0 pid) ;; child
(setf *current-process* (make-process :pid (linux:|getpid|)
:name name))
(push *current-process* *process-list*)
(funcall function)
(ext:exit *process-status*))
((< pid 0)
(error "cannot fork, errno=~D" linux:|errno|))
(t ;; parent
(push (make-process :pid pid :name name) *process-list*)
(car *process-list*))))) ;;make-process
(defparameter *current-process* #-(and)(make-process :pid (linux:|getpid|))
"
The value of this variable is the process which is currently running.
After the process module is loaded (either automatically, or because
(require :process) is evaluated), the value will be non-nil.
This should be treated as a read-only variable.
") ;;*current-process*
(defun process-run-function (name-or-keywords function &rest args)
"
This function does a make-process, then presets the new process
with function and args. The first argument is either a string,
which is the name of the process, or is a list of keyword
arguments accepted by make-process. The new process is
returned. By default, the process is killed when and if it
completes.
"
(declare (ignore name-or-keywords function args))
(error "not implemented yet")) ;;process-run-function
(defun process-run-restartable-function (name-or-keywords function &rest args)
"
This function is just like process-run-function (just above), but
automatically provides a :reset-action argument of t. The process
thus started will restart if it is reset or completes.
"
(declare (ignore name-or-keywords function args))
(error "not implemented yet")) ;;process-run-restartable-function
(defun process-enable (process)
"
Makes process active by removing all its run and arrest reasons,
then giving it a single run reason of :enable.
"
(declare (ignore process))
(error "not implemented yet")) ;;process-enable
(defun process-disable (process)
"
This function makes process inactive by revoking all its run and
arrest reasons. The effect is immediate if a process disables itself.
"
(declare (ignore process))
(error "not implemented yet")) ;;process-disable
(defun process-reset (process &optional no-unwind kill)
"
This function causes process when it next runs to throw out to its
present computation, if any, then apply its initial function to
its initial argument. The no-unwind argument controls what happens
to process' present computation, if it has one. nil (the default)
or :unless-current cause the process to be unwound unless it is
the current process. t unconditionally skips the unwind. Any other
value is equivalent to t, causing an unconditional unwind, which
will throw out of the caller even if the process being reset is
current.
The argument kill must be nil. (It is maintained only for backward
compatibility). An error is signaled if it is not.
"
;; IMPLEMENTATION:
;; I don't think we will be able to accept no-unwind t
(declare (ignore process no-unwind kill))
(error "not implemented yet")) ;;process-reset
(defun process-preset (process function &rest arguments)
"
This function sets the initial function and arguments of process,
then resets any computation in progress in it. This does not make
process active if it was not already active.
"
(declare (ignore process function arguments))
(error "not implemented yet")) ;;process-preset
(defun process-kill (process &key wait)
"
This function resets the process to unwind it, then removes it
from consideration for sunning and from the *all-processes* list.
If the wait keyword argument is non-nil, the calling process waits
until the killed process is really gone. process-kill signals an
error if the process to be killed is an active immigrant. An
inactive immigrant is one that was created to handle a lisp call
from a foreign thread, and has returned from the topmost lisp call
back into the foreign regime. The thread may still be processing,
but it has no lisp state. This will kill the lisp process
associated with that foreign thread, but will not kill the foreign
thread itself. If it later calls into lisp, a new immigrant
process will be created for it.
"
(declare (ignore process wait))
(error "not implemented yet")) ;;process-kill
(defun process-interrupt (process function &rest args)
"
This function forces process to apply function to args when it
next executes. When function returns, the original computation of
process continues. If process is waiting when interrupted, it runs
the interrupt function and then continues waiting. If process is
not active, PROCESS-INTERRUPT makes it active for the interrupt
function, then makes it inactive again. If additional interrupts
are posted to a process when one is already posted, they are all
run, but in undetermined order.
In order for process-interrupt to work as described, function must
return normally. It cannot execute a non-local exit (via, for
example, throw). If function does exit in a non-local manner,
process will not continue its computation.
Processing an interrupt function can be interrupted by additional
process interrupts that occur before the current one has finished
executing.
"
;;
;; IMPLEMENTATION:
;; We won't be able to allow an interrupt function to be interrupted
;; unless we use a different signal. We could use a range of real-time signals.
;;
(declare (ignore process function args))
(error "not implemented yet")) ;;process-interrupt
(defun process-name-to-process (name &key abbrev (error t))
"
This function returns the process whose process-name is name. name
must be a string or a symbol, in which case the print-name is
used. If the abbrev keyword argument is specified true, then name
is matched to the beginning of each process-name to find a
match. The abbrev argument defaults to nil.
If no process is found whose name is name (or, if abbrev is true,
whose name begins with name), an error is signaled if error is
unspecified or true, and nil is returned if error is specified nil.
"
(declare (ignore name abbrev error))
(error "process-name-to-process not implemented yet")
) ;;process-name-to-process
(defun process-initial-form (process)
"
This function returns a cons of the initial function of process
and its argument list.
"
(declare (ignore process))
(error "process-initial-form not implemented yet")) ;;process-initial-form
(defun process-wait-function (process)
"
This function returns the function used to determine when a
waiting process becomes runnable. The function is the one
specified to the currently active call to process-wait on
process. Wait functions are fully described in the
process-waitdescription. (If process is not waiting,
process-wait-function returns nil.)
"
(declare (ignore process))
(error "process-wait-function not implemented yet")) ;;process-wait-function
(defun process-wait-args (process)
"
This function returns the list of arguments passed to the wait
function (see process-wait-function) when determining when a
waiting process becomes runnable. See process-wait.
"
(declare (ignore process))
(error "process-wait-args not implemented yet")) ;;process-wait-args
(defun process-add-run-reason (process object)
"
This function adds object to the list of run-reasons for process.
"
(declare (ignore process object))
(error "process-add-run-reason not implemented yet")) ;;process-add-run-reason
(defun process-add-arrest-reason (process object)
"
This function adds object to the list of arrest-reasons for process.
"
(declare (ignore process object))
(error "process-add-arrest-reason not implemented yet")
) ;;process-add-arrest-reason
(defun process-revoke-run-reason (process object)
"
This function removes object from the list of run reasons for process.
"
(declare (ignore process object))
(error "process-revoke-run-reason not implemented yet")
) ;;process-revoke-run-reason
(defun process-revoke-arrest-reason (process object)
"
This function removes object from the list of arrest reasons for process.
"
(declare (ignore process object))
(error "process-revoke-arrest-reason not implemented yet")
) ;;process-revoke-arrest-reason
(defun process-runnable-p (process)
"
These functions return t if, respectively, process is runnable or
active. A process is active if it has been reset and not yet
completed, and has at least one run reason and no arrest
reasons. It is runnable if it is active and not waiting.
"
(declare (ignore process))
(error "process-runnable-p not implemented yet")) ;;process-runnable-p
(defun process-active-p (process)
"
These functions return t if, respectively, process is runnable or
active. A process is active if it has been reset and not yet
completed, and has at least one run reason and no arrest
reasons. It is runnable if it is active and not waiting.
"
(declare (ignore process))
(error "process-active-p not implemented yet")) ;;process-active-p
#|| attributes:
(defun process-priority (process)
(error "process-priority not implemented yet"));;process-priority
(defun process-quantum (process)
(error "process-quantum not implemented yet"));;process-quantum
||#
(defun process-whostate (process)
"
This function returns the current who-line string of process. This
string can be used by a window system, for example, as a prompt or
to indicate something about the status of the process. May be set
with setf.
"
(declare (ignore process))
(error "process-whostate not implemented yet")) ;;process-whostate
(defmacro without-scheduling (&body body)
"
This macro inhibits the system from suspending a process
involuntarily (asynchronously) during the execution of
body. However, the system will run another process if the current
process blocks, waits, or executes a process-allow-schedule. Note
that without-scheduling returns a single value, not multiple
values. without-scheduling is intended to be used around short
critical sections of code, and perhaps to be called frequently, so
possible overhead of allocating multiple returns is avoided by
returning a single value.
"
;; IMPLEMENTATION;
;; We cannot know when the process will block for another reason
;; (like waitting for input). Otherwise, we can block the other processes.
(declare (ignore body))
(error "without-scheduling not implemented yet")) ;;without-scheduling
(defmacro without-interrupts (&body body)
"
This macro executes body, protecting against any handling of
asynchronous interrupts. Execution of body is guaranteed to
complete without any other process running, or any asynchronous
interrupt being dispatched, unless the process does something to
block or otherwise explicitly yield to the scheduler (e.g. with
PROCESS-ALLOW-SCHEDULE).
without-interrupts is implemented very efficiently and so may be
executed frequently. It is generally bad style to wrap a
without-interrupts around a body of code that takes a significant
amount of time to execute because that may impose inappropriate
high interrupt latency on other (possibly unrelated) interrupt
handlers. without-interrupts is intended to be used around short
critical sections of code; use of a process-lock may be more
appropriate for protecting long bodies of code.
In native threads (:os-threads) implementations of
multiprocessing, a lisp process calling a foreign function can
release control of the lisp environment so that another lisp
process can run. Any attempt to perform such a heap-releasing call
within the scope of a without-interrupts block signals an error
and does not release the heap. Whether error processing overrides
the without-interrupts block depends on the coding of the
particular application.
"
(declare (ignore body))
(error "without-interrupts not implemented yet")) ;;without-interrupts
(defparameter *disallow-scheduling* t
"
This special variable is bound to t whenever multiprocessing
scheduling is disabled. For example, the system binds this
variable to t during the execution of the forms within a
without-scheduling form.
This variable should be treated as read-only and should never be
set or bound by user code.
") ;;*disallow-scheduling*
(defun process-sleep (seconds &optional whostate)
"
process-sleep suspends the current process for at least the number
of seconds specified. That number may be any non-negative,
non-complex number. While the process sleeps, other processes are
allowed to run.)
The whostate (default ''Sleep'') is a string which temporarily
replaces the process' whostate during the sleep.
When multiprocessing is initialized, Common Lisp function sleep is
changed to be equivalent to process-sleep. Instead of causing the
entire Lisp world to suspend execution for the indicated time,
only the executing process is suspended.)
This is usually the desired action.
"
;; IMPLEMENTATION:
;; This can be merely SLEEP, but with the temporary binding of the whostate.
(declare (ignore seconds whostate))
(error "process-sleep not implemented yet")) ;;process-sleep
(defun process-wait (whostate function &rest arguments)
"
This function suspends the current process (the value of
*current-process*) until applying function to arguments yields
true. The whostate argument must be a string which temporarily
replaces the process' whostate for the duration of the wait.)
This function returns nil.
See the discussion under the headings Section 4.3 Waiting for
input from a stream and Section 4.3.1 PROCESS-WAIT vs
WAIT-FOR-INPUT-AVAILABLE.
"
;; IMPLEMENTATION:
;; The waiting process will wait (select, socket-status) or will read
;; the scheduler message queue.
;; gate-open-p --> scheduler sends message when gate opens.
;; read-no-hang-p --> socket:socket-status (if possible)
;; write-no-hang-p --> socket:socket-status (if possible)
;; stream-listen --> socket:socket-status (if possible)
;; other --> scheduler sends periodic messages to
;; the waiting process.
;; TO CHECK: whether socket-status works on message queue?
(declare (ignore whostate function arguments))
(error "process-wait not implemented yet")) ;;process-wait
(defun process-wait-with-timeout (whostate seconds function &rest args)
"
This function is similar to process-wait, but with a timeout. The
units of time are seconds. The value of seconds may be any real
number. Negative values are treated the same as 0.)
The wait will timeout if function does not return true before the
timeout period expires.
"
;; IMPLEMENTATION:
;; Same as process-wait, but the scheduler will send a timeout message.
(declare (ignore whostate seconds function args))
(error "process-wait-with-timeout not implemented yet")
) ;;process-wait-with-timeout
(defun wait-for-input-available (streams &key wait-function whostate timeout)
"
This lower-level function extends the capabilities of process-wait
and process-wait-with-timeout to allow a process to wait for input
from multiple streams and to wait for input from a file.
"
;; IMPLEMENTATION:
;; socket:socket-status should do it.
;; TO CHECK: whether socket-status works on message queue?
(declare (ignore streams wait-function whostate timeout))
(error "wait-for-input-available not implemented yet")
) ;;wait-for-input-available
(defmacro with-timeout ((seconds . timeout-forms) &body body)
"
This macro evaluates the body as a progn body. If the evaluation
of body does not complete within the specified interval, execution
throws out of the body and the timeout-forms are evaluated as a
progn body, returning the result of the last form.) The
timeout-forms are not evaluated if the body completes within
seconds.
"
;; IMPLEMENTATION:
;; We can use either alarm(2) and SIGALRM or ask the scheduler.
;; What could happen if SIGALRM occurs at a wrong time vs. the scheduler?
(declare (ignore seconds timeout-forms body))
(error "with-timeout not implemented yet")) ;;with-timeout
(defun process-allow-schedule (&optional other-process)
"
This function resumes multiprocessing, allowing other processes to
run. All other processes of equal or higher priority will have a
chance to run before the executing process is next run. If the
optional argument is provided, it should be another process.
"
(declare (ignore other-process))
(error "process-allow-schedule not implemented yet")) ;;process-allow-schedule
;;----------------------------------------------------------------------
(defclass gate (scheduler-object)
()
(:documentation "A two-state object that can be
process-waitted efficiently."))
;; IMPLEMENTATION:
;; The simpliest will be to make it only a proxy for a gate
;; in the scheduler.
(defun make-gate (open)
"
Allocates and returns a gate object. The gate's initial state will
be open if open is true and closed if open is nil.
"
(declare (ignore open))
(error "make-gate not implemented yet")) ;;make-gate
(defun open-gate (gate)
"
The gate argument must have been allocated with make-gate.
Makes the state of gate open.
"
(declare (ignore gate))
(error "open-gate not implemented yet")) ;;open-gate
(defun close-gate (gate)
"
The gate argument must have been allocated with make-gate.
Makes the state of gate closed.
"
(declare (ignore gate))
(error "close-gate not implemented yet")) ;;close-gate
(defun gate-open-p (gate)
"
The gate argument must have been allocated with make-gate. Returns
true if gate's state is open and returns nil if it is closed.
As described in the documentation for gates linked to below,
gate-open-p is handled specially by process-wait, and so code which
uses gates runs more efficiently. The speedup can be significant if
the process often waits.
"
(declare (ignore gate))
(error "gate-open-p not implemented yet")) ;;gate-open-p
;;----------------------------------------------------------------------
(defclass queue (scheduler-object)
()
(:documentation "A FIFO. ENQUEUE and DEQUEUE are atomic."))
(defmethod enqueue ((self queue) object)
"
"
(declare (ignore self object))
(error "enqueue not implemented yet")) ;;gate-open-p
(defmethod dequeue ((self queue) object)
"
Dequeuing is provided with a waiting facility, so a process that
tries to dequeue an object from a queue will (optionally) wait, if
the queue is empty, until something is placed on it.
"
(declare (ignore self object))
(error "dequeue not implemented yet")) ;;dequeue
;;----------------------------------------------------------------------
(defclass process-lock (scheduler-object)
()
(:documentation
"
A process-lock is a defstruct which provides a mechanism for
interlocking process execution. Lock objects are created with
make-process-lock. A process-lock is either free or it is seized
by exactly one process. When a process is seized, a non-nil value
is stored in the lock object (in the slot named locker). Usually
this is the process which seized the lock, but can be any Lisp
object other than nil. Any process which tries to seize the lock
before it is released will block. This includes the process which
has seized the lock; the with-process-lock macro protects against
such recursion.
")) ;;process-lock
;; IMPLEMENTATION:
;; The simpliest will be to make it only a proxy for a process lock
;; in the scheduler.
(defun make-process-lock (&key name)
"
This function creates a new lock object. The value of the :name
keyword argument should be a string which is used for
documentation and in the whostate of processes waiting for the
lock. (There are additional keyword argument for internal use not
listed. They should not be set by user code.)
"
(declare (ignore name))
(error "make-process-lock not implemented yet")) ;;make-process-lock
(defmethod process-lock ((lock process-lock)
&optional lock-value whostate timeout)
"
This function seizes lock with the value lock-value (which must be non-nil).
"
(declare (ignore lock lock-value whostate timeout))
(error "process-lock not implemented yet")) ;;process-lock
(defmethod process-unlock ((lock process-lock) &optional lock-value)
"
This function unlocks lock, setting the value in the locker slot to nil.)
The value of the locker slot of the lock must be the same as the
lock-value argument. If it is not, an error is signaled.
"
(declare (ignore lock lock-value))
(error "process-unlock not implemented yet")) ;;process-unlock
(defmethod process-lock-locker ((lock process-lock))
"
This function returns the value of the locker slot of lock.
This value is usually the process holding the lock, but can be
any Lisp value. If the value is nil, the lock is not locked.
"
(declare (ignore lock))
(error "process-lock-locker not implemented yet")) ;;process-lock-locker
(defmethod process-lock-p ((object t))
"
Returns true if object is a lock (as returned by make-process-lock)
and returns nil otherwise.
"
(declare (ignore object))
nil) ;;process-lock-p
(defmethod process-lock-p ((object process-lock))
"
Returns true if object is a lock (as returned by make-process-lock)
and returns nil otherwise.
"
(declare (ignore object))
t) ;;process-lock-p
(defmacro with-process-lock ((lock &key norecursive) &body body)
"
This macro executes the body with lock seized.
"
(declare (ignore lock norecursive body))
(error "with-process-lock not implemented yet")) ;;with-process-lock
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (defparameter forks (make-circular
;; (loop for i from 0 below 5 collect (make-lock))))
;;
;; (defparameter philosophers
;; (loop
;; for i from 0 below 5
;; for prev = (car forks) then next
;; for next in (cdr forks)
;; collect
;; (make-process
;; (let ((left prev) (rigth next))
;; (lambda ()
;; (loop
;; (when (with-lock-held (left 5)
;; (format t "philosopher ~D took left fork.~%" i)
;; (force-output)
;; (when (with-lock-held (right 5)
;; (format t "philosopher ~D took right fork.~%" i)
;; (force-output)
;; (format t "philosopher ~D is eating~%" i)
;; (force-output)
;; (sleep (random 5))
;; t)
;; (format t "philosopher ~D drop right fork.~%" i))
;; (force-output)
;; t)
;; (format t "philosopher ~D drop left fork.~%" i)
;; (force-output))
;; (format t "philosopher ~D philosofies.~%" i)
;; (force-output)))))));;philosophers
;;;;; (defclass process () ())
;;;;; (defun make-process (function &key name))
;;;;; (defgeneric destroy-process (process))
;;;;; (defgeneric suspend-process (process))
;;;;; (defgeneric resume-process (process))
;;;;;
;;;;;
;;;;;
;;;;; (defvar *ALL-PROCESSES* '()
;;;;; "A list of all alive processes.")
;;;;;
;;;;; (defvar *CURRENT-PROCESS* nil
;;;;; "The current process")
;;;;;
;;;;; *CURRENT-STACK-GROUP*
;;;;; *INITIAL-STACK-GROUP*
;;;;; *MULTI-PROCESSING*
;;;;;
;;;;; (defun ALL-PROCESSES ()
;;;;; "Return a list of all the live processes.")
;;;;;
;;;;; (defmacro ATOMIC-DECF (place &option increment)
;;;;; "Decrements the reference by delta in a single atomic operation")
;;;;;
;;;;; (defmacro ATOMIC-INCF (place &option increment)
;;;;; "Increaments the reference by delta in a single atomic operation")
;;;;;
;;;;; (defmacro ATOMIC-POP (place)
;;;;; "Atomically pop place.")
;;;;;
;;;;; (defmacro ATOMIC-PUSH (element place)
;;;;; "Atomically push object onto place.")
;;;;;
;;;;; (defun CURRENT-PROCESS ()
;;;;; "Returns the current process.")
;;;;;
;;;;; (defun DESTROY-PROCESS (process)
;;;;; "Destroy a process. The process is sent a interrupt which throws to
;;;;; the end of the process allowing it to unwind gracefully.")
;;;;;
;;;;; (defun DISABLE-PROCESS (process)
;;;;; "Disable process from being runnable until enabled.")
;;;;;
;;;;; (defun ENABLE-PROCESS (process)
;;;;; "Allow process to become runnable again after it has been disabled.")
;;;;;
;;;;; INIT-STACK-GROUPS
;;;;;
;;;;; (defclass LOCK () ())
;;;;;
;;;;; (defun MAKE-LOCK (...))
;;;;;
;;;;; MAKE-PROCESS
;;;;; "Make a process which will run FUNCTION when it starts up. By
;;;;; default the process is created in a runnable (active) state.
;;;;; If FUNCTION is NIL, the process is started in a killed state; it may
;;;;; be restarted later with process-preset.
;;;;;
;;;;; :NAME
;;;;; A name for the process displayed in process listings.
;;;;;
;;;;; :RUN-REASONS
;;;;; Initial value for process-run-reasons; defaults to (:ENABLE). A
;;;;; process needs a at least one run reason to be runnable. Together with
;;;;; arrest reasons, run reasons provide an alternative to process-wait for
;;;;; controling whether or not a process is runnable. To get the default
;;;;; behavior of MAKE-PROCESS in Allegro Common Lisp, which is to create a
;;;;; process which is active but not runnable, initialize RUN-REASONS to
;;;;; NIL.
;;;;;
;;;;; :ARREST-REASONS
;;;;; Initial value for process-arrest-reasons; defaults to NIL. A
;;;;; process must have no arrest reasons in order to be runnable.
;;;;;
;;;;; :INITIAL-BINDINGS
;;;;; An alist of initial special bindings for the process. At
;;;;; startup the new process has a fresh set of special bindings
;;;;; with a default binding of *package* setup to the CL-USER
;;;;; package. INITIAL-BINDINGS specifies additional bindings for
;;;;; the process. The cdr of each alist element is evaluated in
;;;;; the fresh dynamic environment and then bound to the car of the
;;;;; element."
;;;;; NIL
;;;;; MAKE-STACK-GROUP
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-ACTIVE-P
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-ADD-ARREST-REASON
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-ADD-RUN-REASON
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-ALIVE-P
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-ARREST-REASONS
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-IDLE-TIME
;;;;; "Return the real time elapsed since the given process was last
;;;;; descheduled. The returned time is a double-float in seconds."
;;;;; NIL
;;;;; PROCESS-INTERRUPT
;;;;; "Interrupt process and cause it to evaluate function."
;;;;; NIL
;;;;; PROCESS-NAME
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-PRESET
;;;;; "Restart process, unwinding it to its initial state and calls
;;;;; function with args."
;;;;; NIL
;;;;; PROCESS-PROPERTY-LIST
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-REAL-TIME
;;;;; "Return the accrued real time elapsed while the given process was
;;;;; scheduled. The returned time is a double-float in seconds."
;;;;; NIL
;;;;; PROCESS-REVOKE-ARREST-REASON
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-REVOKE-RUN-REASON
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-RUN-REASONS
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-RUN-TIME
;;;;; "Return the accrued run time elapsed for the given process. The returned
;;;;; time is a double-float in seconds."
;;;;; NIL
;;;;; PROCESS-STATE
;;;;; NIL
;;;;; NIL
;;;;; PROCESS-WAIT
;;;;; "Causes the process to wait until predicate returns True. Processes
;;;;; can only call process-wait when scheduling is enabled, and the predicate
;;;;; can not call process-wait. Since the predicate may be evaluated may
;;;;; times by the scheduler it should be relative fast native compiled code.
;;;;; The single True predicate value is returned."
;;;;; NIL
;;;;; PROCESS-WAIT-UNTIL-FD-USABLE
;;;;; "Wait until FD is usable for DIRECTION and return True. DIRECTION should be
;;;;; either :INPUT or :OUTPUT. TIMEOUT, if supplied, is the number of seconds to
;;;;; wait before giving up and returing NIL."
;;;;; NIL
;;;;; PROCESS-WAIT-WITH-TIMEOUT
;;;;; "Causes the process to wait until predicate returns True, or the
;;;;; number of seconds specified by timeout has elapsed. The timeout may
;;;;; be a fixnum or a float in seconds. The single True predicate value is
;;;;; returned, or NIL if the timeout was reached."
;;;;; NIL
;;;;; PROCESS-WHOSTATE
;;;;; "Return the process state which is either Run, Killed, or a wait reason."
;;;;; NIL
;;;;; PROCESS-YIELD
;;;;; "Allow other processes to run."
;;;;; NIL
;;;;; PROCESSP
;;;;; NIL
;;;;; NIL
;;;;; RESTART-PROCESS
;;;;; "Restart process by unwinding it to its initial state and calling its
;;;;; initial function."
;;;;; NIL
;;;;; SHOW-PROCESSES
;;;;; "Show the all the processes, their whostate, and state. If the optional
;;;;; verbose argument is true then the run, real, and idle times are also
;;;;; shown."
;;;;; NIL
;;;;; STACK-GROUP-RESUME
;;;;; NIL
;;;;; NIL
;;;;; WITH-LOCK-HELD
;;;;; "Execute the body with the lock held. If the lock is held by another
;;;;; process then the current process waits until the lock is released or
;;;;; an optional timeout is reached. The optional wait timeout is a time in
;;;;; seconds acceptable to process-wait-with-timeout. The results of the
;;;;; body are return upon success and NIL is return if the timeout is
;;;;; reached. When the wait key is NIL and the lock is held by another
;;;;; process then NIL is return immediately without processing the body."
;;;;; NIL
;;;;; WITH-TIMEOUT
;;;;; "Executes body and returns the values of the last form in body. However, if
;;;;; the execution takes longer than timeout seconds, abort it and evaluate
;;;;; timeout-forms, returning the values of last form."
;;;;; NIL
;;;;; WITHOUT-SCHEDULING
;;;;; "Execute the body the scheduling disabled."
;;;;; NIL
;;;;; NIL
;;;;; *
"
Process for clisp
clisp cannot handle thread (yet), but it has linux:|fork|, (or FFI
fork on unix). Hence the proposition to implement a PROCESS API for
clisp based on unix processes.
Communication between threads is done with shared variables (a common
address space), and conditions and mutex for synchronization.
Communication between (unix) processes can be done with:
* shared memory (only a part of the address space) (mmap and SVID shm)
+ connection can be established after forking.
+ no copying need (if the data could be allocated into
the shared memory).
- no embeded synchronization.
* process messaging (SVID msg)
+ connection can be established after forking.
+ synchronization (reader may blocks untin a message is received).
* sockets
+ connection can be established after forking.
+ connection can be established between distributed processes.
+ synchronization (reader may blocks untin a message is received).
- point to point.
- uses network resources.
* named pipes
+ connection can be established after forking.
+ synchronization (reader may blocks untin a message is received).
- mainly point to point.
* pipes
+ synchronization (reader may blocks untin a message is received).
- pipes must be established before forking.
- mainly point to point.
Synchronization between processes can be done with:
* semaphores (SVID sem)
* signals (asynchronously).
"
"
start-scheduler
The first process becomes the scheduler (and forks immediately
a main process).
The scheduler is a server that manages the processes, the locks,
the shared variables. It communicates with its children thru SVID
messages, and signals.
Shared variables are stored as a byte sequence in a shared
memory. Only values that are printable readably can be stored in
a shared variable, and only if their types were defined before
forking the processes. The value is therefore copied deeply. No
object. No structure defined after a fork (clisp structures are
printable readably).
It seems we cannot have a symbol-macro at the same time as a
special variable... So we'll need a special API.
For other values, such as PROCESS or LOCK objects, the main
objects are stored in the heap of the scheduler, and the processes
hold proxies that synchronize their state with their master in the
scheduler.
File descriptors? Forking doen't duplicates the file structure,
include the file _marker_.
==> creation of shared variables,
represented with a symbol macro,
implemented as shared memory (mmap or shm?)
==> creation of locks
represented with objects,
implemented as semaphores.
- fork (for this is the only multiprocessing primitive available in clisp).
- processes use pipe to communicate between them.
(alternatively, they could use socket if distribution over serveral hosts
was needed)
- 1-parent/multiple-children.
"
;; (with-open-file (out "/tmp/test" :direction :output :if-does-not-exist :create :if-exists :supersede) (format out "abcdefghijk") (force-output out) (let ((pid (linux:|fork|))) (if (zerop pid) (format out "ABCDEFGHIJK") (format out "0123456789")) (force-output out) (when (zerop pid) (sleep 4) (format t "child quits~%") (force-output) (ext:quit))))
"
make-process
process:fork
process:
- queued messages
-
make-process function &key name
process-interrupt process function
functions can't be passed as function,
it must be a _symbol_ denoting a function.
(because functions are not printable readably).
destroy-process process
current-process
all-processes
processp object
process-name process
process-state process
process-wait reason predicate
process-wait-with-timeout reason timeout predicate
predicate can be evaluated
but no sharing of memory ==> IPC must change state.
without-scheduling &body body
free from interruptions, thru PM, ok, but otherwise needless
since there's not memory sharing.
process-yield
there is no way to really _yield_ the CPU in unix
pause(2) waits for a signal, we could ask the MP to do some scheduling...
disable-process process
kill -STOP
enable-process process
kill -CONT
but master could still communicate with the process, signaling messages.
restart-process process
"
"
atomic-incf reference
atomic-decf reference
no memory sharing, but the mp could forward global values.
each fork ==> duplication of file descriptors (and other resources).
==> problem with destructors (database, protocols, etc).
make-lock &optional name
with-lock-held (place &optional state) &body body
We would need the list of global variables that are modified
and that should be synchronized.
Shallow references cannot be transmitted, only a deep copy.
And only objects printable readably!
"
;; (ffi:def-call-out unix-read (:name "read")
;; (:arguments (fd ffi:int) (buf ffi:c-pointer) (nbytes linux:|size_t|))
;; (:return-type linux:|ssize_t|)
;; (:library "/lib/libc.so.6")
;; (:language :stdc))
;;
;;
;; (ffi:def-call-out unix-write (:name "write")
;; (:arguments (fd ffi:int) (buf ffi:c-pointer) (nbytes linux:|size_t|))
;; (:return-type linux:|ssize_t|)
;; (:library "/lib/libc.so.6")
;; (:language :stdc))
;;
;;
;; (defun test-unix-pipe-io ()
;; (multiple-value-bind (res fds) (linux:|pipe|)
;; (ffi:with-foreign-string (fstr flen fsiz "Hello")
;; (print `(wrote ,(unix-write (aref fds 1) fstr fsiz)))
;; (ffi:with-foreign-object (buf '(ffi:c-array ffi:uchar 512))
;; (let ((rlen (unix-read (aref fds 0) buf 512)))
;; (print `(read ,rlen))
;; (dotimes (i rlen)
;; (princ (code-char (ffi:element (ffi:foreign-value buf)
;; i)))))))));;test-unix-pipe-io
;;
;; (TEST-UNIX-PIPE-IO)
;;
;; (print `(read ,rlen))
;; (dotimes (i rlen)
;; (princ (code-char (ffi:element (ffi:foreign-value buf)
;; i))))
;;
;;
;; (defun copy-from-c-buffer (buffer buflen sequence start)
;; (typecase sequence
;; (cons (let ((current (nthcdr start sequence)))
;; (dotimes (i buflen)
;; (setf (car current) (ffi:element (ffi:foreign-value buffer) i)
;; current (cdr current)))))
;; (string (warn "You should give a string to UNIX-READ-SEQUENCE!")
;; (
;; (vector sequence)
;; (setf
;; )))));;copy-from-c-buffer
(defun valid-operator-name-p (string)
"Test if STRING names a function, macro, or special-operator."
(let ((symbol (let ((*read-eval* nil)) (read-from-string string))))
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)))) ;;valid-operator-name-p
;; (or (ignore-errors (return (ext:arglist fname))))
(defconstant +pipe-buffer-size+ 4096)
(defvar fd)
(defun unix-read (&rest args)
(declare (ignore args))
(error "unix-read Not implemented yet"))
(defun copy-from-c-buffer (&rest args)
(declare (ignore args))
(error "copy-from-c-buffer Not implemented yet"))
(defun unix-read-sequence (sequence &key (start 0) (end nil))
(let ((count (if end (- end start) (length sequence))))
(when (zerop count)
(return-from unix-read-sequence (values 0 sequence)))
(ffi:with-foreign-object (buffer
'(ffi:c-array ffi:uchar +pipe-buffer-size+))
(loop named :reader do
(let ((rlen (unix-read fd buffer (min count +pipe-buffer-size+))))
(cond
((< 0 rlen)
(return-from :reader
(values rlen (copy-from-c-buffer buffer rlen sequence start))))
((= 0 rlen)
(return-from :reader (values rlen sequence)))
(t (case linux:|errno|
((linux:|EAGAIN| linux:|EINTR|))
((linux:|EPIPE|) (return-from :reader nil)) ; EOF
(otherwise
(error "unix read: ~A" (linux:|strerror| linux:|errno|))
))))))))) ;;unix-read-sequence
;; (EXT:MAKE-BUFFERED-INPUT-STREAM function mode)
;;
;; returns a buffered input STREAM. function is a FUNCTION of 0
;; arguments that returns either NIL (stands for end-of-stream) or up to
;; three values string, start, end. READ-CHAR returns the CHARACTERs of
;; the current string one after another, as delimited by start and end,
;; which default to 0 and NIL, respectively. When the string is consumed,
;; function is called again. The string returned by function should not
;; be changed, otherwise function should copy the string with COPY-SEQ or
;; SUBSEQ beforehand. mode determines the behavior of LISTEN when the
;; current string buffer is empty:
;; NIL the stream acts like a FILE-STREAM, i.e. function is called
;;
;; T the stream acts like an interactive stream without
;; end-of-stream, i.e. one can assume that further characters will always
;; arrive, without calling function FUNCTION this FUNCTION tells, upon
;; call, if further non-empty strings are to be expected.
;;
;; CLEAR-INPUT discards the rest of the current string, so function
;; will be called upon the next READ-CHAR operation.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun clisp-version ()
"Return the major and minor of clisp version as a floating point number."
(let* ((v (lisp-implementation-version))
(p (position (character ".") v))
(p (position-if (complement (function digit-char-p)) v :start (1+ p))))
(read-from-string v nil nil :end p))))
(defun make-unix-pipe (&key (element-type 'character)
(external-format custom:*foreign-encoding*)
(buffered t))
(multiple-value-bind (res fds) (linux:|pipe|)
(unless (= 0 res)
(error "unix pipe: ~A" (linux:|strerror| linux:|errno|)))
(let ((inp (ext:make-buffered-input-stream
(lambda ()
(aref fds 0)
:direction :input
:element-type element-type
:external-format external-format
:buffered buffered)
#+#.(cl:when (cl:<= 2.33 (com.informatimago.susv3.process::clisp-version))
:clisp)
t))
(out (ext:make-stream (aref fds 1)
:direction :output
:element-type element-type
:external-format external-format
:buffered buffered)))
;;(print (list (aref fds 0) inp (aref fds 1) out))
;;(linux:|close| (aref fds 0))
;;(linux:|close| (aref fds 1))
(values inp out))))
;; (EXT:MAKE-BUFFERED-OUTPUT-STREAM function)
;;
;; returns a buffered output STREAM. function is a FUNCTION expecting
;; one argument, a SIMPLE-STRING. WRITE-CHAR collects the CHARACTERs in a
;; STRING, until a newline character is written or
;; FORCE-OUTPUT/FINISH-OUTPUT is called. Then function is called with a
;; SIMPLE-STRING as argument, that contains the characters collected so
;; far. CLEAR-OUTPUT dicards the characters collected so far.
(defun make-unix-pipe/does-not-work (&key (element-type 'character)
(external-format custom:*foreign-encoding*)
(buffered t))
(multiple-value-bind (res fds) (linux:|pipe|)
(unless (= 0 res)
(error "unix pipe: ~A" (linux:|strerror| linux:|errno|)))
(let ((inp (ext:make-stream (aref fds 0)
:direction :input
:element-type element-type
:external-format external-format
:buffered buffered))
(out (ext:make-stream (aref fds 1)
:direction :output
:element-type element-type
:external-format external-format
:buffered buffered)))
;;(print (list (aref fds 0) inp (aref fds 1) out))
;;(linux:|close| (aref fds 0))
;;(linux:|close| (aref fds 1))
(values inp out)))) ;;make-unix-pipe/does-not-work
#||
(defparameter *out* nil)
(defparameter *inp* nil)
(multiple-value-setq (*inp* *out*) (make-unix-pipe))
(when (zerop (linux:|fork|))
(print :child)(force-output)
(loop for i = (read *inp*) while (< i 10)
do (format t "~%got ~D~%" i) (force-output))
(ext:quit))
(loop for i from 0 to 10 do (print i *out*)(force-output *out*)(princ "."))
(loop :repeat 2 :do
(linux:set-signal-handler
linux:SIGUSR1
(lambda (signal) (princ " Got signal ") (throw :hot-potatoe signal)))
(catch :hot-potatoe
(princ " Looping ")
(loop do (sleep 5) (princ ".")))
(princ " Caught "))
(linux:set-signal-handler linux:SIGALRM
(let ((i 0)) (lambda (signal)
(princ ".") (print (incf i) *out*) (force-output *out*))))
(linux:ualarm 1000000 1000000)
||#
#||
(defclass process ()
((name :reader name
:type string
:initform "Unnamed"
:initarg :name)
(pid :reader pid
:type integer
:initform 0
:initarg :pid))
(:documentation "A process proxy."));;process
(defparameter *parent*
(make-instance 'process :name "parent" :pid (linux:getppid)))
(defun parent ()
"
RETURN: The parent process.
"
*parent*);;parent
||#
(defun make-xterm-io-stream (&key display)
(declare (ignore display))
(error "~S: Implemented in com.informatimago.clisp" 'make-xterm-io-stream))
(defun register-worker (pid)
(declare (ignore pid))
(error "~S: not implemented yet." 'register-worker))
(defun parse-one-command (pid)
(declare (ignore pid))
(error "~S: not implemented yet." 'parse-one-command))
(defun server-main (&key display)
(if (or display (find-package "SWANK"))
(let* ((xterm-io (make-xterm-io-stream :display display))
(*standard-output* xterm-io)
(*standard-input* xterm-io)
(*error-output* xterm-io)
(*terminal-io* xterm-io)
(*query-io* xterm-io)
(*debug-io* xterm-io))
(iotask-enqueue *standard-input*
(make-buffered-discipline (function server-input))
"xterm")
(configuration-repl-start)
(iotask-poll-loop))
(ext:with-keyboard
(let ((*standard-input* ext:*keyboard-input*))
(iotask-enqueue ext:*keyboard-input*
(make-keyboard-discipline (function server-input))
"keyboard")
(configuration-repl-start)
(iotask-poll-loop))))) ;;server-main
(defvar *pipe-format* (ext:make-encoding
:charset 'charset:utf-8
:line-terminator :unix))
(defparameter +server-port+ 15000)
(defun server ()
(let ((lsock (socket:socket-server +server-port+)))
(unwind-protect
(loop
(when (socket:socket-wait lsock 0)
(let ((remote (socket:socket-accept lsock
:element-type 'character
;; :external-format
:buffered t
:timeout 1)))
(when remote
;; got an incoming connection, let's fork a worker
;; but first, create a socket and connect to it to be
;; able to communicate with this worker.
(let ((pid (linux:fork)))
(cond
((< pid 0) ;; error
(error "Could not fork a worker."))
((= pid 0) ;; child
)
(t ;; parent
(register-worker pid)
(format t "~& "))))
))))
(close lsock)))) ;;server
(defun list-insert-separator (list separator)
"
RETURN: A list composed of all the elements in `list'
with `separator' in-between.
EXAMPLE: (list-insert-separator '(a b (d e f) c) 'x)
==> (a x b x (d e f) x c)
"
(do ((result (if list (list (car list))))
(list (cdr list) (cdr list)))
((null list) (nreverse result))
(push separator result)
(push (car list) result)))
(defun char-or-string-p (object)
(or (characterp object) (stringp object)))
(defun pjb-unsplit-string (string-list &optional (separator " "))
"Does the inverse than pjb-split-string. If no separator is provided
then a simple space is used."
(check-type separator (or string char))
(apply 'concatenate 'string
(mapcar (lambda (object)
(if (stringp object)
object
(format nil "~A" object)))
(list-insert-separator string-list separator))))
(defun pjb-split-string (string &optional separators)
"
note: current implementation only accepts as separators
a string containing only one character.
"
(setq separators (or separators " ")
string (string string))
(let ((sep (aref separators 0))
(chunks '())
(position 0)
(nextpos 0)
(strlen (length string)) )
(while (<= position strlen)
(while (and (< nextpos strlen)
(char/= sep (aref string nextpos)))
(setq nextpos (1+ nextpos)))
(setq chunks (cons (subseq string position nextpos) chunks))
(setq position (1+ nextpos))
(setq nextpos position) )
(nreverse chunks))) ;;PJB-SPLIT-STRING
(defun ipv4-address-p (address)
"
PRE: (or (string address) (symbol address))
RETURN: Whether ADDRESS as the aaa.bbb.ccc.ddd IPv4 address format.
"
(let ((bytes (pjb-split-string (string address) ".")))
(and (= 4 (length bytes))
(block :convert
(nreverse
(mapcar (lambda (byte)
(multiple-value-bind (val eaten) (read-from-string byte)
(if (and (= eaten (length byte)) (integerp val)
(<= 0 val 255))
val
(return-from :convert nil))))
(pjb-split-string address "."))))))) ;;IPV4-ADDRESS-P
(defun server-repl ()
(do ((hist 1 (1+ hist))
(+eof+ (gensym)))
(nil)
(format t "~%~A[~D]> " (package-name *package*) hist)
(handling-errors
(setf +++ ++ ++ + + - - (read *standard-input* nil +eof+))
(when (or (eq - +eof+)
(member - '((quit)(exit)(continue)) :test (function equal)))
(return-from server-repl))
(setf /// // // / / (multiple-value-list (eval -)))
(setf *** ** ** * * (first /))
(format t "~& --> ~{~S~^ ;~% ~}~%" /)))) ;;server-repl
(defvar +eof+ (gensym))
(defvar *debugging* nil)
(defvar *prompt* "> ")
(defun configuration-repl (&key (debugging *debugging*))
(catch :configuration-repl-exit
(loop
(format t "~&~A " *prompt*) (finish-output)
(let ((sexp (read *standard-input* nil +eof+)))
(if sexp
(if debugging
(parse-one-command sexp)
(handler-case (parse-one-command sexp)
(error (err)
(apply (function format) *error-output*
(simple-condition-format-control err)
(simple-condition-format-arguments err)))))
(throw :configuration-repl-exit nil)))))) ;;configuration-repl
(defun configuration-repl-start ()
(format t "~&~A " *prompt*)
(finish-output))
(defun configuration-repl-input (line)
(let ((sexp (read-from-string line nil +eof+)))
(unless (eq +eof+ sexp)
(if *debugging*
(parse-one-command sexp)
(handler-case (parse-one-command sexp)
(error (err)
(apply (function format) *error-output*
(simple-condition-format-control err)
(simple-condition-format-arguments err)))))
(configuration-repl-start)))) ;;configuration-repl-input
#+(or)(progn
(load "loader.lisp")
(configuration-repl :debugging t)
(filter append allow "127.0.0.1")
(filter append deny all)
(connections max-number 40)
(connections enable)
(configuration save "/tmp/server.conf")
(repl)
)
(defstruct iotask stream process-event name)
(defparameter *iotasks* '())
(defparameter *bon-grain* '()
"Sublist of *iotask* which can be handled by socket:socket-wait.")
(defparameter *ivray* '()
"Sublist of *iotask* which cannot be handled by socket:socket-wait.")
(defun iotask-enqueue (stream process-event &optional name)
(let ((task (make-iotask :stream stream
:process-event process-event
:name name)))
(push task *iotasks*)
(handler-case (socket:socket-status (iotask-stream task) 0)
(error () (push task *ivray*))
(:no-error (s n) (declare (ignore s n)) (push task *bon-grain*)))
)) ;;iotask-enqueue
(defun iotask-dequeue (task)
(setf *iotasks* (delete task *iotasks*))
(setf *bon-grain* (delete task *bon-grain*))
(setf *ivray* (delete task *ivray*)))
(defun iotask-poll-loop ()
(loop ;; each 0.1 seconds, see second argument of socket-status.
(when (null *iotasks*) (return))
(map nil
(lambda (task status)
(when status (funcall (iotask-process-event task) task status)))
*ivray*
(mapcar (lambda (task)
(let ((stream (iotask-stream task)))
(cond
((input-stream-p stream)
(if (listen stream)
:input
(if (output-stream-p stream) :output nil)))
((output-stream-p stream) :output)
(t nil))))
*ivray*))
(map nil
(lambda (task status)
(when status (funcall (iotask-process-event task) task status)))
*bon-grain*
(socket:socket-status
(mapcar (function iotask-stream) *bon-grain*) 0.1))))
(defun make-buffered-discipline (process-input)
(lambda (task event)
(when (member event '(:input :error))
(funcall process-input task (read-line (iotask-stream task))))))
;; (DEFCONSTANT ALLOW
;; (DEFCONSTANT DENY
;; (DEFCONSTANT ALL
;; (DEFCONSTANT MAX-NUMBER
;; (DEFCONSTANT ENABLE
;; (DEFCONSTANT SAVE
(defconstant +cr+ 13)
(defconstant +bs+ 8)
(defconstant +del+ 127)
(defun make-keyboard-discipline (process-input)
(let ((buffer (make-array '(128) :element-type 'character :fill-pointer 0)))
(lambda (task event)
(when (eq :input event)
(let* ((ich (read-char (iotask-stream task)))
(ch (system::input-character-char ich)))
(cond
((null ch))
((= (char-code ch) +cr+)
(terpri)
(funcall process-input
task (subseq buffer 0 (fill-pointer buffer)))
(setf (fill-pointer buffer) 0))
((or (= (char-code ch) +bs+) (= (char-code ch) +del+))
(when (< 0 (fill-pointer buffer))
(princ (code-char +bs+))
(princ " ")
(princ (code-char +bs+))
(decf (fill-pointer buffer))))
(t
(princ ch)
(vector-push ch buffer))))
(finish-output))))) ;;make-keyboard-discipline
(defun server-input (task line)
(if (string-equal "(QUIT)" line)
(iotask-dequeue task)
(configuration-repl-input line))) ;;server-input
#||
(progn (ext:with-keyboard
(socket:socket-status (list ext:*keyboard-input*) nil)
(unread-char (system::input-character-char
(read-char ext:*keyboard-input*))
*standard-input*))
(print (read-line)))
||#
#||
(defun child.send (sexp)
(print sexp child.pipe)
(linux:|kill| child.pid linux:|SIGUSR1|))
(child.send '(throw :exit 1))
(child.send '(print test1))
;; set-signal-handler --> ONE signal is queued and processed when the handler exists.
(defmessage symeval-req (symbol process))
(defmessage symeval-res (symbol process status value))
(defmessage profile-req ())
(defmessage profile-res (status profile-data))
(defmessage newproc-req (name class reset-action run-reasons arrest-reasons
resume-hook suspend-hook initial-bindings))
(defmessage newproc-res (process status))
(defmessage setproc-req (process attribute value))
(defmessage setproc-res (process status))
(defmessage preset-req (process function args))
(defmessage preset-res (process status))
(defmessage reset-req (process))
(defmessage reset-res (process status))
(defmessage killproc-req (process wait))
(defmessage killproc-req (process status))
(defmessage interrupt-req (process function args))
(defmessage interrupt-res (process status value))
(defmessage disallow-interrupts-req ())
(defmessage disallow-interrupts-res (status))
(defmessage allow-interrupts-req ())
(defmessage allow-interrupts-res (status))
(defmessage disallow-scheduling-req ())
(defmessage disallow-scheduling-res (status))
(defmessage allow-scheduling-req ())
(defmessage allow-scheduling-res (status))
(defmessage start-wait-req (gate period timeout))
(defmessage start-wait-res (status gate counter))
(defmessage stop-wait-req ())
(defmessage stop-wait-res (status))
(defmessage timeout-req (timeout))
(defmessage timeout-res (status)) ;; immediate ; interrupt when timeout.
(defmessage lock-req (lock value timeout))
(defmessage lock-res (status))
(defmessage unlock-req (lock value))
(defmessage unlock-res (status))
||#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; defmessage
;; scheduler
(defmacro with-timeout ((seconds &body timeout-forms) &body body)
;; implement with alarm and
(declare (ignore seconds timeout-forms body))
#+(or)(with-signal-handler linux:|SIGALRM|)
(error "not implemented yet")
;; or implement with the scheduler when it's started.
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 69,252 | Common Lisp | .lisp | 1,641 | 36.725168 | 351 | 0.655237 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 633f0a3fb541b1179272a16a38141bc2418aae478633040f525461fdc7a73d94 | 4,682 | [
-1
] |
4,683 | dirent.lisp | informatimago_lisp/susv3/dirent.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: dirent.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; SUSv3 dirent functions.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2005-04-04 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2005 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(declaim (declaration also-use-packages)
(also-use-packages "FFI"))
;; TODO: This nicknaming should be done outside of the sources.
#-mocl
(eval-when (:compile-toplevel :load-toplevel :execute)
(com.informatimago.common-lisp.cesarum.package:add-nickname
"COM.INFORMATIMAGO.CLISP.SUSV3" "SUSV3")
(com.informatimago.common-lisp.cesarum.package:add-nickname
"COM.INFORMATIMAGO.CLISP.SUSV3-XSI" "SUSV3-XSI"))
(defpackage "COM.INFORMATIMAGO.SUSV3.DIRENT"
(:documentation
"An API over SUSV3 and SUSV3-XSI dirent API.")
(:use "COMMON-LISP"
;; "COM.INFORMATIMAGO.CLISP.RAW-MEMORY"
"COM.INFORMATIMAGO.SUSV3.TOOLS"
"FFI")
(:import-from "COM.INFORMATIMAGO.CLISP.SUSV3"
"CHECK-ERRNO" "CHECK-POINTER")
(:export "DIR" "DIRENT" "DIRENT-INO" "DIRENT-NAME"
"OPENDIR" "CLOSEDIR" "READDIR" "REWINDDIR"
;; XSI:
"SEEKDIR" "TELLDIR" ))
(in-package "COM.INFORMATIMAGO.SUSV3.DIRENT")
(deftype dir ()
"A type representing a directory stream."
`t)
(defstruct dirent
(ino 0 :type integer) ;; File serial number
(name "" :type string)) ;; Name of entry [NAME-MAX]
(declaim
(ftype (function (dir) integer) closedir)
(ftype (function (string) (or null dir)) opendir)
(ftype (function (dir) (or null dirent)) readdir)
(ftype (function (dir) nil) rewinddir))
(declaim ;; XSI
(ftype (function (dir integer) nil) seekdir)
(ftype (function (dir) integer) telldir))
(define-ffi-copiers (dirent susv3:dirent dirent->c-dirent c-dirent->dirent)
(dirent-ino susv3::dirent-d_ino)
(dirent-name susv3::dirent-d_name))
(defun opendir (path) (check-pointer (susv3:opendir path)
:function 'susv3:opendir
:arguments (list path)
:caller 'opendir))
(defun closedir (dir-stream) (check-errno (susv3:closedir dir-stream)
:function 'susv3:closedir
:arguments (list dir-stream)
:caller 'closedir))
(defun readdir (dir-stream)
(setf susv3:errno 0)
(let ((c-dirent (check-pointer (susv3:readdir dir-stream)
:function 'susv3:readdir
:arguments (list dir-stream)
:caller 'readdir)))
;; :no-error (list susv3:ENOENT))))
(unless (zerop c-dirent)
(let* ((ino (deref (cast (foreign-value c-dirent) '(pointer uint32))))
(name (coerce (loop
:for dirent = (cast (foreign-value c-dirent) '(pointer uchar))
:for i :from 11
:for code = (element (foreign-value dirent) i)
:until (zerop code)
:collect (code-char code)) 'string)))
(make-dirent :ino ino :name name)))))
(defun rewinddir (dir-stream) (susv3:rewinddir dir-stream))
(defun seekdir (dir-stream position)
(check-errno (susv3:seekdir dir-stream position)
:function 'susv3:seekdir
:arguments (list dir-stream position)
:caller 'seekdir))
(defun telldir (dir-stream)
(check-errno (susv3:telldir dir-stream)
:function 'susv3:telldir
:arguments (list dir-stream)
:caller 'telldir))
(defun dirent-test ()
(do* ((dir-stream (opendir "/tmp"))
(entry (readdir dir-stream) (readdir dir-stream)))
((null entry))
(format t "entry: ~8D ~S~%" (dirent-ino entry) (dirent-name entry))))
;;;; THE END ;;;;
| 5,276 | Common Lisp | .lisp | 117 | 37.025641 | 92 | 0.569953 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f568ed26bd3e2495024f6c79556b1f9ca1ee876581a18c195e6771d3391d7da2 | 4,683 | [
-1
] |
4,684 | ipc.lisp | informatimago_lisp/susv3/ipc.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: ipc.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; An API over SUSV3-XSI IPC.
;;;;
;;;; Note: The number of queues in a system is limited.
;;;; An application could use the message type as a recipient address.
;;;;
;;;; cliini: There's always another way to achieve the same thing.
;;;; But it's the lisp way to offer nice and intuitive interfaces
;;;; to achieve the stuff, otherwise we might all be using assembler.
;;;; [2005-01-02 20:30:53]
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-11-29 <PJB> Created.
;;;;BUGS
;;;; +MESSAGE-SIZE-LIMIT+ should be got dynamically from the system!
;;;;
;;;; This package should not use FFI at all, the SUSV3-XSI package should
;;;; export pure lisp.
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
;; TODO: This nicknaming should be done outside of the sources.
#-mocl
(eval-when (:compile-toplevel :load-toplevel :execute)
(com.informatimago.common-lisp.cesarum.package:add-nickname
"COM.INFORMATIMAGO.CLISP.SUSV3" "SUSV3")
(com.informatimago.common-lisp.cesarum.package:add-nickname
"COM.INFORMATIMAGO.CLISP.SUSV3-XSI" "SUSV3-XSI"))
(defpackage "COM.INFORMATIMAGO.SUSV3.IPC"
(:documentation
"An API over SUSV3-XSI IPC (msgget/msgctl/msgsnd/msgrcv).")
(:use "COMMON-LISP" "FFI"
"COM.INFORMATIMAGO.SUSV3.TOOLS"
"COM.INFORMATIMAGO.CLISP.SUSV3")
(:export
;; ipc:
"IPC-PERMISSIONS" "IPC-PERMISSIONS-KEY" "IPC-PERMISSIONS-UID"
"IPC-PERMISSIONS-GID" "IPC-PERMISSIONS-CUID" "IPC-PERMISSIONS-CGID"
"IPC-PERMISSIONS-MODE" "IPC-PERMISSIONS-SEQ"
"MAKE-KEY"
;; msg:
"MSGDESC" "MSGDESC-PERMISSIONS" "MSGDESC-SEND-TIME"
"MSGDESC-RECEIVE-TIME" "MSGDESC-CHANGE-TIME"
"MSGDESC-CURRENT-BYTES" "MSGDESC-MESSAGE-COUNT"
"MSGDESC-MAXIMUM-BYTES" "MSGDESC-LAST-SEND-PID"
"MSGDESC-LAST-RECEIVE-PID"
"MESSAGE-GET" "MESSAGE-STATISTICS" "MESSAGE-MODIFY"
"MESSAGE-REMOVE" "MESSAGE-SEND" "MESSAGE-RECEIVE" "MESSAGE-SEND-SEXP"
"MESSAGE-RECEIVE-SEXP"
;; shm:
"SHMDESC" "SHMDESC-PERMISSIONS" "SHMDESC-SEGMENT-SIZE"
"SHMDESC-ATTACH-TIME" "SHMDESC-DETACH-TIME" "SHMDESC-CHANGE-TIME"
"SHMDESC-CREATOR-PID" "SHMDESC-LAST-OPERATION-PID"
"SHMDESC-ATTACH-COUNT"
"MEMORY-GET" "MEMORY-STATISTICS"
"MEMORY-MODIFY" "MEMORY-REMOVE" "MEMORY-LOCK" "MEMORY-UNLOCK"
"MEMORY-PAGE-SIZE" "MEMORY-ATTACH" "MEMORY-DETACH"
;; sem:
"SEMDESC" "SEMDESC-PERMISSIONS" "SEMDESC-NUMBER-OF-SEMAPHORES"
"SEMDESC-OPERATION-TIME" "SEMDESC-CHANGE-TIME"
"SEMAPHORE-GET" "SEMAPHORE-STATISTICS" "SEMAPHORE-MODIFY"
"SEMAPHORE-REMOVE" "SEMAPHORE-GET-PID" "SEMAPHORE-GET-VALUE"
"SEMAPHORE-GET-ALL-VALUES" "SEMAPHORE-NUMBER-WAITING-FOR-INCREASE"
"SEMAPHORE-NUMBER-WAITING-FOR-ZERO" "SEMAPHORE-SET-VALUE"
"SEMAPHORE-SET-ALL-VALUES" "SEMAPHORE-OPERATE" ))
(in-package "COM.INFORMATIMAGO.SUSV3.IPC")
(defun make-key (pathname project-id)
"Converts a pathname and a project identifier to a System V IPC key."
(declare (type pathname pathname)
(type (integer project-id))) ;; not zerop!
(let ((path (namestring (truename pathname))))
(check-errno (susv3-xsi:ftok path project-id)
:function 'susv3-xsi:ftok
:arguments (list path project-id)
:caller 'make-key)))
(defstruct ipc-permissions
(key 0 :type integer) ; Key.
(uid 0 :type integer) ; Owner's user ID.
(gid 0 :type integer) ; Owner's group ID.
(cuid 0 :type integer) ; Creator's user ID.
(cgid 0 :type integer) ; Creator's group ID.
(mode 0 :type integer) ; Read/write permissions. rwxrwxrwx
(seq 0 :type integer)) ; Sequence number.
(define-ffi-copiers ipc-permissions susv3-xsi:ipc_perm
(ipc-permissions-key susv3-xsi::key)
(ipc-permissions-uid susv3-xsi::uid)
(ipc-permissions-gid susv3-xsi::gid)
(ipc-permissions-cuid susv3-xsi::cuid)
(ipc-permissions-cgid susv3-xsi::cgid)
(ipc-permissions-mode susv3-xsi::mode)
(ipc-permissions-seq susv3-xsi::seq))
;;----------------------------------------------------------------------
;; msg
;;----------------------------------------------------------------------
(defun message-get (key &key (create nil) (private nil) (exclusive nil)
(access-rights #o600))
"Returns the message queue identifier associated with the value
of the key argument."
(let ((flags (+ (if create susv3-xsi:ipc_creat 0)
(if private susv3-xsi:ipc_private 0)
(if exclusive susv3-xsi:ipc_excl 0)
(ldb (byte 9 0) access-rights))))
(check-errno (susv3-xsi:msgget key flags)
:function 'susv3-xsi:msgget
:arguments (list key flags)
:caller 'message-get)))
(defstruct msgdesc
(permissions (make-ipc-permissions) :type ipc-permissions)
(send-time 0 :type integer) ; time of last msgsnd command
(receive-time 0 :type integer) ; time of last msgrcv command
(change-time 0 :type integer) ; time of last change
(current-bytes 0 :type integer) ; current number of bytes on queue
(message-count 0 :type integer) ; number of messages currently on queue
(maximum-bytes 0 :type integer) ; max number of bytes allowed on queue
(last-send-pid 0 :type integer) ; pid of last msgsnd()
(last-receive-pid 0 :type integer)) ; pid of last msgrcv()
(define-ffi-copiers msgdesc susv3-xsi:msqid_ds
((msgdesc-permissions ipc-permissions) (susv3-xsi::msg_perm ipc_perm))
(msgdesc-send-time susv3-xsi::msg_stime)
(msgdesc-receive-time susv3-xsi::msg_rtime)
(msgdesc-change-time susv3-xsi::msg_ctime)
(msgdesc-current-bytes susv3-xsi::msg_cbytes)
(msgdesc-message-count susv3-xsi::msg_qnum)
(msgdesc-maximum-bytes susv3-xsi::msg_qbytes)
(msgdesc-last-send-pid susv3-xsi::msg_lspid)
(msgdesc-last-receive-pid susv3-xsi::msg_lrpid))
(defun message-statistics (queue)
"Returns a MSGDESC structure, containing a copy of the information
from the message queue data structure associated with the msqid QUEUE.
The caller must have read permission on the message queue."
(ffi:with-c-var (d 'susv3-xsi:msqid_ds)
(check-errno (susv3-xsi:msgctl queue susv3-xsi:ipc_stat
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:msgctl
:arguments (list queue 'susv3-xsi:ipc_stat 'susv3-xsi:msqid_ds)
:caller 'message-statistics)
(let ((result (make-msgdesc)))
(msqid_ds->msgdesc d result)
result)))
(defun message-modify (queue msgdesc)
"
Write the values of some members of the msqid_ds structure
to the message queue data structure, updating also its msg_ctime member.
The following members of the structure can be updated:
msg_perm.uid, msg_perm.gid, msg_perm.mode (only lowest 9-bits), msg_qbytes.
"
(ffi:with-c-var (d 'susv3-xsi:msqid_ds)
(msgdesc->msqid_ds msgdesc d)
(check-errno (susv3-xsi:msgctl queue susv3-xsi:ipc_set
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:msgctl
:arguments (list queue 'susv3-xsi:ipc_set msgdesc)
:caller 'message-modify))) ;;message-modify
(defun message-remove (queue)
"
Immediately remove the message queue and its associated
data structure, awakening all waiting reader and writer
processes (with an error return and errno set to EIDRM).
The calling process must have appropriate (probably, root)
privileges or its effective user-ID must be either that of
the creator or owner of the message queue.
"
(check-errno (susv3-xsi:msgctl queue susv3-xsi:ipc_rmid 0)
:function 'susv3-xsi:msgctl
:arguments (list queue 'susv3-xsi:ipc_rmid 0)
:caller 'message-remove)) ;;message-remove
(defun message-send (queue message-type message-text
&key (no-wait nil))
(ffi:with-c-var (msg `(ffi:c-struct susv3-xsi:msgbuf
(susv3-xsi::mtype ffi:long)
(susv3-xsi::mtext
(ffi:c-array ffi:uint8
,(length message-text))))
(susv3-xsi:make-msgbuf :mtype message-type
:mtext message-text))
(check-errno (susv3-xsi:msgsnd queue
(ffi:foreign-address-unsigned
(ffi:c-var-address msg))
(length message-text)
(if no-wait susv3-xsi:ipc_nowait 0))
:function 'susv3-xsi:msgsnd
:arguments (list queue 'msg
(length message-text)
(if no-wait susv3-xsi:ipc_nowait 0))
:caller 'message-send))) ;;message-send
(defun message-receive (queue message-type message-size
&key (no-wait nil) (no-error nil) (except nil))
(ffi:with-c-var (msg `(ffi:c-struct susv3-xsi:msgbuf
(susv3-xsi::mtype ffi:long)
(susv3-xsi::mtext
(ffi:c-array ffi:uint8 ,message-size))))
(let ((size (check-errno
(susv3-xsi:msgrcv queue
(ffi:foreign-address-unsigned
(ffi:c-var-address msg))
message-size
message-type
(+ (if no-wait susv3-xsi:ipc_nowait 0)
(if no-error susv3-xsi:msg_noerror 0)
(if except susv3-xsi:msg_except 0)))
:function 'susv3-xsi:msgsnd
:arguments (list queue 'msg
message-size
message-type
(+ (if no-wait susv3-xsi:ipc_nowait 0)
(if no-error susv3-xsi:msg_noerror 0)
(if except susv3-xsi:msg_except 0)))
:caller 'message-receive)))
(let ((slice (make-array (list size)
:element-type '(unsigned-byte 8)
:displaced-to (susv3-xsi:msgbuf-mtext msg))))
(values (make-array (list size)
:element-type '(unsigned-byte 8)
:initial-contents slice)
(susv3-xsi:msgbuf-mtype msg)))))) ;;message-receive
(defparameter +message-size-limit+ 8188
"BUG: We should get dynamically the limit from the system!")
(defun message-send-sexp (queue message-type sexp &key (no-wait nil))
(let ((mtext (ext:convert-string-to-bytes
(format nil "~S" sexp) charset:iso-8859-1)))
(when (< +message-size-limit+ (length mtext))
(error "S-expression too big to be sent thru a message queue."))
(tagbody
:again
(handler-case
(return-from message-send-sexp
(print (message-send queue message-type mtext :no-wait no-wait)))
(unix-error (err) (print err)
(if (= susv3:eintr (unix-error-number err))
(go :again)
(error err))))))) ;;message-send-sexp
(defun message-receive-sexp (queue message-type &key (no-wait nil) (except nil))
(multiple-value-bind (mtext mtype)
(block :receive
(tagbody
:again
(handler-case
(return-from :receive
(message-receive queue message-type +message-size-limit+
:no-wait no-wait :except except))
(unix-error (err) (if (= susv3:eintr (unix-error-number err))
(go :again)
(error err))))))
(values (let ((*read-eval* nil))
(read-from-string
(ext:convert-string-from-bytes mtext charset:iso-8859-1)))
mtype))) ;;message-receive-sexp
;;----------------------------------------------------------------------
;; shm
;;----------------------------------------------------------------------
(defun memory-get (key size
&key (create nil) (exclusive nil) (access-rights #o600))
"returns the identifier of the shared memory segment
associated with the value of the argument key. A new shared mem
ory segment, with size equal to the value of size rounded up to a
multiple of PAGE_SIZE, is created if key has the value IPC_PRI
VATE or key isn't IPC_PRIVATE, no shared memory segment corre
sponding to key exists, and IPC_CREAT is asserted in shmflg (i.e.
shmflg&IPC_CREAT isn't zero)."
(let ((flags (+ (if create susv3-xsi:ipc_creat 0)
(if exclusive susv3-xsi:ipc_excl 0)
(ldb (byte 9 0) access-rights))))
(check-errno (susv3-xsi:shmget key size flags)
:function 'susv3-xsi:shmget
:arguments (list key size flags)
:caller 'memory-get))) ;;memory-get
(defstruct shmdesc
;; Data structure describing a shared memory segment.
(permissions (make-ipc-permissions) :type ipc-permissions)
(segment-size 0 :type integer) ; size of segment in bytes
(attach-time 0 :type integer) ; time of last shmat()
(detach-time 0 :type integer) ; time of last shmdt()
(change-time 0 :type integer) ; time of last change by shmctl()
(creator-pid 0 :type integer) ; pid of creator
(last-operation-pid 0 :type integer) ; pid of last shmop
(attach-count 0 :type integer)) ; number of current attaches
(define-ffi-copiers shmdesc susv3-xsi:shmid_ds
((shmdesc-permissions ipc-permissions) (susv3-xsi::shm_perm ipc_perm))
(shmdesc-segment-size susv3-xsi::shm_segsz)
(shmdesc-attach-time susv3-xsi::shm_atime)
(shmdesc-detach-time susv3-xsi::shm_dtime)
(shmdesc-change-time susv3-xsi::shm_ctime)
(shmdesc-creator-pid susv3-xsi::shm_cpid)
(shmdesc-last-operation-pid susv3-xsi::shm_lpid)
(shmdesc-attach-count susv3-xsi::shm_nattch)) ;;shmdesc
(defun memory-statistics (memory)
"copy the information about the shared memory
segment into the buffer buf. The user must have
read access to the shared memory segment."
(ffi:with-c-var (d 'susv3-xsi:shmid_ds)
(check-errno (susv3-xsi:shmctl memory susv3-xsi:ipc_stat
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:shmctl
:arguments (list memory 'susv3-xsi:ipc_stat
'susv3-xsi:shmid_ds)
:caller 'memory-statistics)
(let ((result (make-shmdesc)))
(shmid_ds->shmdesc d result)
result))) ;;memory-statistics
(defun memory-modify (memory shmdesc)
"apply the changes the user has made to the
uid, gid, or mode members of the shm_perms field.
Only the lowest 9 bits of mode are used. The
shm_ctime member is also updated. The user must be
the owner, creator, or the super-user."
(ffi:with-c-var (d 'susv3-xsi:shmid_ds)
(shmdesc->shmid_ds shmdesc d)
(check-errno (susv3-xsi:shmctl memory susv3-xsi:ipc_set
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:shmctl
:arguments (list memory 'susv3-xsi:ipc_set shmdesc)
:caller 'memory-modify))) ;;memory-modify
(defun memory-remove (memory)
"Mark the segment as destroyed. It will
actually be destroyed after the last detach. (I.e.,
when the shm_nattch member of the associated struc
ture shmid_ds is zero.) The user must be the owner,
creator, or the super-user."
(check-errno (susv3-xsi:shmctl memory susv3-xsi:ipc_rmid 0)
:function 'susv3-xsi:shmctl
:arguments (list memory 'susv3-xsi:ipc_rmid 0)
:caller 'memory-remove)) ;;memory-remove
(defun memory-lock (memory)
"prevents swapping of a shared memory segment. The
user must fault in any pages that are required to be
present after locking is enabled."
(check-errno (susv3-xsi:shmctl memory susv3-xsi:shm_lock 0)
:function 'susv3-xsi:shmctl
:arguments (list memory 'susv3-xsi:shm_lock 0)
:caller 'memory-remove)) ;;memory-lock
(defun memory-unlock (memory)
"allows the shared memory segment to be swapped out."
(check-errno (susv3-xsi:shmctl memory susv3-xsi:shm_lock 0)
:function 'susv3-xsi:shmctl
:arguments (list memory 'susv3-xsi:shm_lock 0)
:caller 'memory-remove)) ;;memory-unlock
(defun memory-page-size ()
"Return the page size, to which the shared memory page addresses
must be rounded."
(susv3-xsi:shmlba))
(defun memory-attach (memory address &key (round nil) (read-only nil)
(remap nil))
;; remap is linux specific
"allows the shared memory segment to be swapped out."
(check-errno (susv3-xsi:shmat memory address
(+ (if round susv3-xsi:shm_rnd 0)
(if read-only susv3-xsi:shm_rdonly 0)
(if remap susv3-xsi:shm_remap 0)))
:function 'susv3-xsi:shmat
:arguments (list memory address
(+ (if round susv3-xsi:shm_rnd 0)
(if read-only susv3-xsi:shm_rdonly 0)
(if remap susv3-xsi:shm_remap 0)))
:caller 'memory-attach)) ;;memory-attach
(defun memory-detach (address)
"detaches the shared memory segment located at
the address specified by shmaddr from the address space of the
calling process. The to-be-detached segment must be currently
attached with shmaddr equal to the value returned by the its
attaching shmat call."
(check-errno (susv3-xsi:shmdt address)
:function 'susv3-xsi:shmdt
:arguments (list address)
:caller 'memory-detach)) ;;memory-detach
;;----------------------------------------------------------------------
;; sem
;;----------------------------------------------------------------------
(defun semaphore-get (key number-of-semaphores
&key (create nil) (exclusive nil) (access-rights #o600))
"Returns the semaphore set identifier associated
with the argument key. A new set of nsems semaphores is created
if key has the value IPC_PRIVATE or if no existing semaphore set
is associated to key and IPC_CREAT is asserted in semflg (i.e.
semflg & IPC_CREAT isn't zero)."
(let ((flags (+ (if create susv3-xsi:ipc_creat 0)
(if exclusive susv3-xsi:ipc_excl 0)
(ldb (byte 9 0) access-rights))))
(check-errno (susv3-xsi:semget key number-of-semaphores flags)
:function 'susv3-xsi:semget
:arguments (list key number-of-semaphores flags)
:caller 'semaphore-get))) ;;semaphore-get
(defstruct semdesc
;; Data structure describing a set of semaphores.
(permissions (make-ipc-permissions) :type ipc-permissions)
(number-of-semaphores 0 :type integer)
(operation-time 0 :type integer) ; time of last semop().
(change-time 0 :type integer)) ; time of last change by semctl())
(define-ffi-copiers semdesc susv3-xsi:semid_ds
((semdesc-permissions ipc-permissions) (susv3-xsi::sem_perm ipc_perm))
(semdesc-number-of-semaphores susv3-xsi::sem_nsems)
(semdesc-operation-time susv3-xsi::sem_otime)
(semdesc-change-time susv3-xsi::sem_ctime)) ;;semdesc
(defun semaphore-statistics (semaphore)
"Copy info from the semaphore set data structure into
the structure pointed to by arg.buf. The argument
semnum is ignored. The calling process must have
read access privileges on the semaphore set."
(ffi:with-c-var (d 'susv3-xsi:semid_ds)
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:ipc_stat
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:ipc_stat
'susv3-xsi:semid_ds)
:caller 'semaphore-statistics)
(let ((result (make-semdesc)))
(semid_ds->semdesc d result)
result))) ;;semaphore-statistics
(defun semaphore-modify (semaphore semdesc)
"Apply the changes the user has made to the
uid, gid, or mode members of the sem_perms field.
Only the lowest 9 bits of mode are used. The
sem_ctime member is also updated. The user must be
the owner, creator, or the super-user."
(ffi:with-c-var (d 'susv3-xsi:semid_ds)
(semdesc->semid_ds semdesc d)
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:ipc_set
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:ipc_set semdesc)
:caller 'semaphore-modify))) ;;semaphore-modify
(defun semaphore-remove (semaphore)
"Mark the segment as destroyed. It will
actually be destroyed after the last detach. (I.e.,
when the sem_nattch member of the associated struc
ture semid_ds is zero.) The user must be the owner,
creator, or the super-user."
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:ipc_rmid 0)
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:ipc_rmid 0)
:caller 'semaphore-remove)) ;;semaphore-remove
(defun semaphore-get-pid (semaphore)
"The system call returns the value of sempid for the
semnum-th semaphore of the set (i.e. the pid of the
process that executed the last semop call for the
semnum-th semaphore of the set). The calling process
must have read access privileges on the semaphore
set."
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:getpid 0)
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:getpid 0)
:caller 'semaphore-get-pid)) ;;semaphore-get-pid
(defun semaphore-get-value (semaphore index)
"The system call returns the value of semval for the
semnum-th semaphore of the set. The calling process
must have read access privileges on the semaphore
set."
(check-errno (susv3-xsi:semctl semaphore index susv3-xsi:getval 0)
:function 'susv3-xsi:semctl
:arguments (list semaphore index 'susv3-xsi:getval 0)
:caller 'semaphore-get-value)) ;;semaphore-get-value
(defun semaphore-get-all-values (semaphore)
"Return semval for all semaphores of the set into
arg.array. The argument semnum is ignored. The
calling process must have read access privileges on
the semaphore set."
(let ((semnum (semdesc-number-of-semaphores
(semaphore-statistics semaphore))))
(ffi:with-c-var (d `(ffi:c-array ffi:ushort ,semnum))
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:getall
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:getall 'values)
:caller 'semaphore-get-all-values)
(let ((result (make-array (list semnum)
:element-type '(unsigned-byte 16)
:initial-element 0)))
(dotimes (i semnum)
(setf (aref result i) (ffi:element d i)))
result)))) ;;semaphore-get-all-values
(defun semaphore-number-waiting-for-increase (semaphore index)
"The system call returns the value of semncnt for the
semnum-th semaphore of the set (i.e. the number of
processes waiting for an increase of semval for the
semnum-th semaphore of the set). The calling process
must have read access privileges on the semaphore
set."
(check-errno (susv3-xsi:semctl semaphore index susv3-xsi:getncnt 0)
:function 'susv3-xsi:semctl
:arguments (list semaphore index 'susv3-xsi:getncnt 0)
:caller 'semaphore-number-waiting-for-increase))
(defun semaphore-number-waiting-for-zero (semaphore index)
"The system call returns the value of semzcnt for the
semnum-th semaphore of the set (i.e. the number of
processes waiting for semval of the semnum-th
semaphore of the set to become 0). The calling pro
cess must have read access privileges on the
semaphore set."
(check-errno (susv3-xsi:semctl semaphore index susv3-xsi:getzcnt 0)
:function 'susv3-xsi:semctl
:arguments (list semaphore index 'susv3-xsi:getzcnt 0)
:caller 'semaphore-number-waiting-for-zero))
(defun semaphore-set-value (semaphore index value)
"Set the value of semval to arg.val for the semnum-th
semaphore of the set, updating also the sem_ctime
member of the semid_ds structure associated to the
set. Undo entries are cleared for altered semaphores
in all processes. Processes sleeping on the wait
queue are awakened if semval becomes 0 or increases.
The calling process must have alter access privileges
on the semaphore set."
(check-errno (susv3-xsi:semctl semaphore index susv3-xsi:setval value)
:function 'susv3-xsi:semctl
:arguments (list semaphore index 'susv3-xsi:setval value)
:caller 'semaphore-set-value)) ;;semaphore-set-value
(defun semaphore-set-all-values (semaphore values)
"Set semval for all semaphores of the set using
arg.array, updating also the sem_ctime member of the
semid_ds structure associated to the set. Undo
entries are cleared for altered semaphores in all
processes. Processes sleeping on the wait queue are
awakened if some semval becomes 0 or increases. The
argument semnum is ignored. The calling process must
have alter access privileges on the semaphore set."
(let ((semnum (semdesc-number-of-semaphores
(semaphore-statistics semaphore))))
(assert (= (length values) semnum))
(ffi:with-c-var (d `(ffi:c-array ffi:ushort ,semnum) values)
(check-errno (susv3-xsi:semctl semaphore 0 susv3-xsi:setall
(ffi:foreign-address-unsigned
(ffi:c-var-address d)))
:function 'susv3-xsi:semctl
:arguments (list semaphore 0 'susv3-xsi:setall 'values)
:caller 'semaphore-set-all-values))))
(defun semaphore-operate (semaphore operations &key (no-error '()))
"
OPERATION: a list of (sem_num sem_op [:no-wait] [:undo])
"
(ffi:with-c-var (d `(ffi:c-array susv3-xsi:sembuf ,(length operations)))
(do ((ops operations (cdr ops))
(i 0 (1+ i)))
((null ops))
(setf (ffi:slot (ffi:element d i) 'susv3-xsi::sem_num) (first (car ops))
(ffi:slot (ffi:element d i) 'susv3-xsi::sem_op) (second (car ops))
(ffi:slot (ffi:element d i) 'susv3-xsi::sem_flg)
(+ (if (member :no-wait (cddr (car ops))) susv3-xsi:ipc_nowait 0)
(if (member :undo (cddr (car ops))) susv3-xsi:sem_undo 0))))
(check-errno (susv3-xsi:semop semaphore
(ffi:foreign-address-unsigned
(ffi:c-var-address d))
(length operations))
:no-error (if (listp no-error) no-error (list no-error))
:function 'susv3-xsi:semctl
:arguments (list semaphore operations (length operations))
:caller 'semaphore-operate)))
;; (defun operate (sem op undo nowait)
;; (with-slots (val adj zcnt ncnt wait-for-zero-q wait-for-increase-q) sem
;; (cond
;; ((plusp op) (incf val op) (if undo (decf adj op)))
;; ((zerop op) (cond
;; ((zerop val))
;; (nowait
;; (error EAGAIN))
;; (t (incf zcnt)
;; (enqueue wait-for-zero-q *current-process*))))
;; ((minusp op) (cond
;; ((< (- op) val)
;; (incf val op) (if undo (decf adj op)))
;; (nowait
;; (error EAGAIN))
;; (t (incf ncnt)
;; (enqueue wait-for-increase-q *current-process*)))))))
;; (defun p (sem undo) (operate sem -1 undo nil))
;; (defun v (sem undo) (operate sem 1 undo nil))
;; If sem_op is a positive integer, the operation adds this value to
;; the semaphore value (semval). Furthermore, if SEM_UNDO is
;; asserted for this operation, the system updates the process undo
;; count (semadj) for this semaphore. This operation can always
;; proceed - it never forces a process to wait. The calling process
;; must have alter permission on the semaphore set.
;;----
;; If sem_op is zero, the process must have read access permission
;; on the semaphore set. This is a "wait-for-zero" operation: if
;; semval is zero, the operation can immediately proceed. Other
;; wise, if IPC_NOWAIT is asserted in sem_flg, the system call fails
;; with errno set to EAGAIN (and none of the operations in sops is
;; performed). Otherwise semzcnt (the count of processes waiting
;; until this semaphore's value becomes zero) is incremented by one
;; and the process sleeps until one of the following occurs:
;;
;; · semval becomes 0, at which time the value of semzcnt is
;; decremented.
;;
;; · The semaphore set is removed: the system call fails, with
;; errno set to EIDRM.
;;
;; · The calling process catches a signal: the value of semzcnt
;; is decremented and the system call fails, with errno set
;; to EINTR.
;;----
;; If sem_op is less than zero, the process must have alter permis
;; sion on the semaphore set. If semval is greater than or equal to
;; the absolute value of sem_op, the operation can proceed immedi
;; ately: the absolute value of sem_op is subtracted from semval,
;; and, if SEM_UNDO is asserted for this operation, the system
;; updates the process undo count (semadj) for this semaphore. If
;; the absolute value of sem_op is greater than semval, and
;; IPC_NOWAIT is asserted in sem_flg, the system call fails, with
;; errno set to EAGAIN (and none of the operations in sops is per
;; formed). Otherwise semncnt (the counter of processes waiting for
;; this semaphore's value to increase) is incremented by one and the
;; process sleeps until one of the following occurs:
;;
;; · semval becomes greater than or equal to the absolute value
;; of sem_op, at which time the value of semncnt is decre
;; mented, the absolute value of sem_op is subtracted from
;; semval and, if SEM_UNDO is asserted for this operation,
;; the system updates the process undo count (semadj) for
;; this semaphore.
;;
;; · The semaphore set is removed from the system: the system
;; call fails with errno set to EIDRM.
;;
;; · The calling process catches a signal: the value of semncnt
;; is decremented and the system call fails with errno set to
;; EINTR.
;;;; ipc.lisp -- -- ;;;;
| 33,913 | Common Lisp | .lisp | 651 | 43.222734 | 83 | 0.602896 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | ac97fa410e328ce5749722dc84b13c9d2c7452df696447aaf56c90d6627cf6f5 | 4,684 | [
-1
] |
4,685 | post-clisp.awk | informatimago_lisp/susv3/post-clisp.awk | BEGIN{
"/usr/local/bin/clisp -q -norc -ansi -x \"(princ(namestring (truename \\\"$(pwd)/\\\")))\""|getline pwd
}
/Compiling file /{
file=$4;
if(substr(file,0,length(pwd))==pwd){
file=substr(file,1+length(pwd));
}
next;
}
/; *Loading file /{
file=$4;
if(substr(file,0,length(pwd))==pwd){
file=substr(file,1+length(pwd));
}
next;
}
/WARNING in.*in lines/{
start=index($0,"WARNING in ")+length("WARNING in ");
fn=substr($0,start,index($0," in lines ")-start);
start=index($0," in lines ")+length(" in lines ");
lines=substr($0,start,index(substr($0,start)," ")-1);
split(lines,n,"\\.");
w="WARNING";
next;
}
/ERROR.*in lines/{
start=index($0,"ERROR in ")+length("WARNING in ");
fn=substr($0,start,index($0," in lines ")-start);
start=index($0," in lines ")+length(" in lines ");
lines=substr($0,start,index(substr($0,start)," ")-1);
split(lines,n,"\\.");
w="ERROR";
next;
}
{
if(w!=""){
printf "%s:%s:1:\n%s:%s:2:%s in %s: %s\n",file,n[1],file,n[3],w,fn,$0;
w="";
}else{
print $0;
}
}
| 1,131 | Common Lisp | .lisp | 43 | 21.837209 | 107 | 0.54663 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a89da41bdcca72b03242b1484ead369a79b91465f94d0faae47b6d537f84fbaf | 4,685 | [
-1
] |
4,686 | init.lisp | informatimago_lisp/susv3/init.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: init.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Initialization for susv3 packages.
;;;;
;;;; This files remove some specificities from the lisp environment
;;;; (to make it more Common-Lisp),
;;;; loads the package COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PACKAGE,
;;;; and add logical pathname translations to help find the other packages.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-01-20 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(setq *load-verbose* t)
;; clean the imported packages:
(mapc (lambda (used) (unuse-package used "COMMON-LISP-USER"))
(remove (find-package "COMMON-LISP")
(copy-seq (package-use-list "COMMON-LISP-USER"))))
(progn
(defvar *directories* '())
(defun get-directory (key &optional (subpath ""))
(unless *directories*
(with-open-file (dirs (make-pathname :name "DIRECTORIES" :type "TXT"
:version nil :case :common
:defaults (user-homedir-pathname)))
(loop
:for k = (read dirs nil dirs)
:until (eq k dirs)
:do (push (string-trim " " (read-line dirs)) *directories*)
:do (push (intern (substitute #\- #\_ (string k))
"KEYWORD") *directories*))))
(unless (getf *directories* key)
(error "~S: No directory keyed ~S" 'get-directory key))
(merge-pathnames subpath (getf *directories* key) nil)))
#+clisp
(when (string= (lisp-implementation-version) "2.33.83"
:end1 (min (length (lisp-implementation-version)) 7))
(ext:without-package-lock ("COMMON-LISP")
(let ((oldload (function cl:load)))
(fmakunbound 'cl:load)
(defun cl:load (filespec &key (verbose *load-verbose*)
(print *load-print*)
(if-does-not-exist t)
(external-format :default))
(handler-case (funcall oldload filespec :verbose verbose
:print print :if-does-not-exist if-does-not-exist
:external-format external-format)
(system::simple-parse-error
()
(funcall oldload (translate-logical-pathname filespec)
:verbose verbose
:print print :if-does-not-exist if-does-not-exist
:external-format external-format)))))))
;; COM.INFORMATIMAGO.CLISP packages depend on themselves, from
;; the current directory, and on COM.INFORMATIMAGO.COMMON-LISP
;; packages from the repository.
(setf (logical-pathname-translations "PACKAGES") nil
(logical-pathname-translations "PACKAGES")
(list
(list "PACKAGES:**;*"
(get-directory :share-lisp "packages/**/*"))
(list "PACKAGES:**;*.*"
(get-directory :share-lisp "packages/**/*.*"))
(list "PACKAGES:**;*.*.*"
(get-directory :share-lisp "packages/**/*.*.*"))))
(handler-case (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE")
(t () (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE.LISP")))
;; Import DEFINE-PACKAGE, and add translations:
(import 'package:define-package)
;;----------------------------------------------------------------------
(package:add-translations
(list "PACKAGES:COM;INFORMATIMAGO;SUSV3;**;*.*.*" "**/*.*.*"))
;;;; init.lisp -- -- ;;;;
| 4,673 | Common Lisp | .lisp | 100 | 40.01 | 83 | 0.573778 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e54105d943a1255746ff3826a40de73061ee91be07bc4f8ebc78b8f112b87a59 | 4,686 | [
-1
] |
4,687 | unicode.lisp | informatimago_lisp/future/unicode.lisp | (defparameter *combining-ranges*
'((#x0300 #x036f diacritical-marks (1.0 4.1))
(#x1ab0 #x1aff diacritical-marks-extended 7.0)
(#x1dc0 #x1dff diacritical-marks-supplement (4.1 5.2))
(#x20d0 #x20ff diacritical-marks-for-symbols (1.0 5.1))
(#xfe20 #xfe2f half-marks (1.0 8.0))
(#x3099 dakuten)
(#x309a handkuten)
;; etc other blocks contain combining codes
))
(defun combining-codepoint-p (codepoint)
(loop
:for (min max . nil) :in *combining-ranges*
:thereis (if (integerp max)
(<= min codepoint max)
(= min codepoint))))
(deftype codepoint () `(integer 0 1114111))
(defclass unicode-character ()
((codepoints :initarg :codepoints
:reader unicode-character-codepoints
:type vector)))
(defmethod unicode-char= ((a unicode-character) (b unicode-character))
(equalp (unicode-character-codepoints a)
(unicode-character-codepoints b)))
(defclass unicode-string ()
((characters :initarg :characters
:reader unicode-string-characters
:type vector)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun list-of-codepoint (object)
(and (consp object)
(typep (car object) 'codepoint)
(or (null (cdr object))
(list-of-codepoint (cdr object))))
(and (listp object)))
(defun vector-of-codepoint (object)
(and (vectorp object)
(every (lambda (element)
(typep element 'codepoint))
object)))
(defun vector-of-unicode-character (object)
(and (vectorp object)
(every (lambda (element)
(typep element 'unicode-character))
object))))
(deftype list-of (element-type) `(and list (satisfies ,(intern (format nil "LIST-OF-~A" element-type)))))
(deftype vector-of (element-type) `(and vector (satisfies ,(intern (format nil "VECTOR-OF-~A" element-type)))))
(defmethod print-object ((uchar unicode-character) stream)
(when *print-readably*
(format stream "#\\"))
(format stream "~A" (map 'string 'code-char (unicode-character-codepoints uchar)))
uchar)
(defun make-unicode-character (codepoint &rest codepoints)
(let ((cpoints (if (consp codepoint)
(coerce codepoint 'vector)
(coerce (cons codepoint codepoints) 'vector))))
(unless (every (lambda (codepoint) (typep codepoint 'codepoint)) cpoints)
(error 'type-error :datum cpoints :expected-type 'vector-of-codepoint))
(make-instance 'unicode-character :codepoints cpoints)))
(defmethod print-object ((ustring unicode-string) stream)
(if *print-readably*
(loop
:with escape := (make-unicode-character (char-code #\\))
:with dquote := (make-unicode-character (char-code #\"))
:for uchar :across (unicode-string-characters ustring)
:initially (format stream "\"")
:if (or (unicode-char= escape uchar)
(unicode-char= dquote uchar))
:do (format stream "\\")
:end
:do (princ uchar stream)
:finally (format stream "\""))
(loop :for uchar :across (unicode-string-characters ustring)
:do (princ uchar stream)))
ustring)
(defun codepoints-to-string (vector-of-codepoints)
(loop
:with characters := '()
:with current-character := '()
:for codepoint :across vector-of-codepoints
:do (cond
((combining-codepoint-p codepoint)
(push codepoint current-character))
(current-character
(push (make-unicode-character (nreverse current-character)) characters)
(setf current-character (list codepoint)))
(t
(setf current-character (list codepoint))))
:finally (when current-character
(push (make-unicode-character (nreverse current-character)) characters))
(return (make-instance 'unicode-string :characters (coerce (nreverse characters) 'vector)))))
(defmethod make-unicode-string ((initial-contents string))
(codepoints-to-string (map 'vector 'char-code initial-contents)))
(make-unicode-character (cons 97 (loop :for codepoint :from #x0300 :to #x036f :collect codepoint)))
;; --> à̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ͘͜͟͢͝͞͠͡
(defmethod unicode-length ((string unicode-string))
(length (unicode-string-characters string)))
(defmethod unicode-subseq ((string unicode-string) start end)
;; O(- end start)
(make-instance 'unicode-string
:characters (subseq (unicode-string-characters string) start end)))
(make-instance 'unicode-string
:characters (coerce (loop
:for ch :from 97 to (+ 97 25)
:collect (apply (function make-unicode-character)
ch
(loop :repeat (random 4)
:collect (+ #x0300 (random (- #x036f #x0300)))))) 'vector))
;; ab̂̃͘cd͗e̋f̶g̋hͬi̥͉͎ǰ͚ͭḵ̏̈́l̳m̭ṉ̵̰o̮̳pq̻r̦͕̿ș̐͞t͓͝͡u̼̔͋v̞̝w̓xy̿̽zͣ
;; abc̝d̬͎͝e̠f̥̀͠g̭̫͐h̶i͚j͔̐ͅk̀l̨̄͡ṃ̂n̢̺o͛p̲̩q̿ͤ͜r͛ͫ͠s͜t̓͌uv͍w̬̙̃x̻̪y̸z
;; a͉̿̀b͌c̢̏d̟͙̺e̳ͭ͂fg͎̾̆hijk̈́ͫlm͇̮̂nͮͅǫ́p̹͐qr͖̝̔ṡ͂͑t̟̀u̜̲͝v̽wxy̳ͣz͉ͨ̅
(unicode-subseq
(make-instance 'unicode-string
:characters (coerce (loop
:for ch :from 97 to (+ 97 25)
:collect (apply (function make-unicode-character)
ch
(loop :repeat (random 4)
:collect (+ #x0300 (random (- #x036f #x0300)))))) 'vector))
5 15)
;; f̅gͥh̎î͍̻j͙̠̿ķ̢̏ḻ̉̽mn̞̜͘o̳͌̄
;; f̷̙̍g͍̻ͅȟ̜̰i͛͢jķ͇ḷ̂m̪̼̿n͝ȯ
;; f̀̒͆g̩h͇͑ị̕͜j̅k̬͆l̝̖ͦm͂͆n̤̅o
(rotate (length))
(apropos "ROTATE")
(defun nrotate-vector (n vector &optional (start 0) end)
(let* ((end (or end (length vector)))
(len (- end start))
(n (mod n len)))
(when (plusp n)
;; 0 start start+n end (length vector)
;; |-------|-----------|----|---------|
(let ((temp (make-array n :element-type (array-element-type vector))))
(replace temp vector :start2 start :end2 (+ start n))
(replace vector vector :start1 start :start2 (+ start n) :end2 end)
(replace vector temp :start1 (+ start (- len n)))))
vector))
(defun test/nrotate-vector ()
(assert (string= " World!Hello"
(nrotate-vector 5 (copy-seq "Hello World!"))))
(assert (string= "Hello ldWor!"
(nrotate-vector 3 (copy-seq "Hello World!") 6 11)))
(assert (string= "Hello World!"
(nrotate-vector 0 (copy-seq "Hello World!") 3 10)))
:success)
(nrotate-vector 1 "z͉ͨ̅" 1)
;; --> "z͉̅ͨ"
(let ((string (make-unicode-string "hi z͉ͨ̅ cool")))
(values (nrotate-vector 1 (unicode-character-codepoints (aref (unicode-string-characters string) 3)) 1)
string))
;; --> #(122 841 773 872)
;; "hi z͉̅ͨ cool"
(let ((string (make-unicode-string "a͉̿̀b͌c̢̏d̟͙̺e̳ͭ͂fg͎̾̆hijk̈́ͫlm͇̮̂nͮͅǫ́p̹͐qr͖̝̔ṡ͂͑t̟̀u̜̲͝v̽wxy̳ͣz͉ͨ̅")))
(values (unicode-length string)
(copy-seq (unicode-string-characters string))
(nrotate-vector 3 (unicode-string-characters string) 5 21)))
;; --> 26
;; #(a͉̿̀ b͌ c̢̏ d̟͙̺ e̳ͭ͂ f g͎̾̆ h i j k̈́ͫ l m͇̮̂ nͮͅ ǫ́ p̹͐ q r͖̝̔ ṡ͂͑ t̟̀ u̜̲͝ v̽ w x y̳ͣ z͉ͨ̅)
;; #(a͉̿̀ b͌ c̢̏ d̟͙̺ e̳ͭ͂ i j k̈́ͫ l m͇̮̂ nͮͅ ǫ́ p̹͐ q r͖̝̔ ṡ͂͑ t̟̀ u̜̲͝ f g͎̾̆ h v̽ w x y̳ͣ z͉ͨ̅)
(let ((string "a͉̿̀b͌c̢̏d̟͙̺e̳ͭ͂fg͎̾̆hijk̈́ͫlm͇̮̂nͮͅǫ́p̹͐qr͖̝̔ṡ͂͑t̟̀u̜̲͝v̽wxy̳ͣz͉ͨ̅"))
(values (length string)
(copy-seq string)
(nrotate-vector 3 string 5 21)))
;; --> 69
;; "a͉̿̀b͌c̢̏d̟͙̺e̳ͭ͂fg͎̾̆hijk̈́ͫlm͇̮̂nͮͅǫ́p̹͐qr͖̝̔ṡ͂͑t̟̀u̜̲͝v̽wxy̳ͣz͉ͨ̅"
;; "a͉̿̀b̏d̟͙̺e̳ͭ͂fg͎̾͌c̢̆hijk̈́ͫlm͇̮̂nͮͅǫ́p̹͐qr͖̝̔ṡ͂͑t̟̀u̜̲͝v̽wxy̳ͣz͉ͨ̅"
| 8,529 | Common Lisp | .lisp | 166 | 39.403614 | 120 | 0.55769 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 348afbf99c22e3844c67dccb52d5b2bc880cb84a02e808e4f19cfdb571e44470 | 4,687 | [
-1
] |
4,688 | special-operators.lisp | informatimago_lisp/future/special-operators.lisp |
(define-special-operator (function name)
(cl:function name))
(define-special-operator (quote literal)
(cl:quote literal))
(define-special-operator (if test then &optional (else nil elsep))
(cl:if (expression test) (expression then) (expression else)))
(define-special-operator (block name &body body)
(cl:block name (unsplice-progn-body body)))
(define-special-operator (return-from name &optional result)
(cl:return-from name (expression result)))
(define-special-operator (catch object &body body)
(cl:catch (expression object) (unspliace-progn-body body)))
(define-special-operator (throw object result)
(cl:throw (expression object) (expression result)))
p
(define-special-operator (unwind-protect protected &body cleanup)
(cl:unwind-protect (expression protected)
(unsplice-progn-body cleanup)))
(define-special-operator (tagbody &body body)
(cl:tagbody (unsplice-tagbody body)))
(define-special-operator (go tag)
(cl:go tag))
(define-special-operator (flet (&rest bindings) &body body)
(cl:flet
(map bindings (name lambda-list &body body)
(name lambda-list (unsplice-lambda-body body)))
(unsplice-locally-body body)))
(define-special-operator (labels (&rest bindings) &body body)
(cl:labels
(map bindings (name lambda-list &body body)
(name lambda-list (unsplice-lambda-body body)))
(unsplice-locally-body body)))
(define-special-operator (setq var val &rest pairs)
(cl:progn
(cl:setq var (expression val))
(map pairs (var val)
(cl:setq var (expression val)))))
(define-special-operator (let (&rest bindings) &body body)
(cl:let
(map bindings (or (var val)
(var)
var)
(var (expression (or val nil))))
(unsplice-locally-body body)))
(define-special-operator (let* (&rest bindings) &body body)
(cl:let*
(map bindings (or (var val)
(var)
var)
(var (expression (or val nil))))
(unsplice-locally-body body)))
(define-special-operator (multiple-value-call function-form &rest arguments) (&whole form &environment env)
(simple-step
`(apply ,(step-expression function-form env)
(append ,@(mapcar (cl:lambda (argument)
`(cl:multiple-value-list ,(step-expression argument env)))
arguments)))
form))
(define-special-operator (multiple-value-prog1 result-form &body body) (&whole form &environment env)
(cl:let ((result (gensym)))
(simple-step
`(cl:let ((,result (cl:multiple-value-list ,(step-expression result-form env))))
,@(step-body :progn body env)
(values-list ,result))
form)))
(define-special-operator (progn &body body) (&environment env)
;; We must preserve toplevelness.
`(cl:progn
,@(step-body :progn body env)))
(define-special-operator (progv symbols values &body body) (&whole form &environment env)
(cl:let ((vsym (gensym))
(vval (gensym)))
(simple-step `(cl:let ((,vsym ,(step-expression symbols env))
(,vval ,(step-expression values env)))
(cl:progv ,vsym ,vval
(mapc (cl:function did-bind) ,vsym ,vval)
,@(step-body :progn body env)))
form)))
(define-special-operator (locally &body body) (&whole form &environment env)
(multiple-value-bind (ds declarations real-body) (parse-body :locally body)
(declare (ignore ds real-body))
(cl:if (stepper-disabled-p declarations)
`(cl:locally ,@(rest form))
(simple-step `(cl:locally
,@(step-body :locally body env))
form))))
(define-special-operator (the value-type expression) (&environment env)
;; TODO: Check the semantics of (the (values t) (values 1 2 3))
;; --> It seems (values t) == (VALUES INTEGER &REST T)
;; TODO: Handle (values &rest) in value-type.
(cl:let ((results (gensym))
(temp (gensym)))
(simple-step
`(cl:let ((,results (cl:multiple-value-list ,(step-expression expression env))))
,(cl:if (and (listp value-type)
(eq 'values (first value-type)))
`(cl:let ((,temp ,results))
,@(mapcar (cl:lambda (value-type)
`(check-type (pop ,temp) ,value-type))
(rest value-type)))
`(check-type ,(first results) ,value-type))
(cl:the ,value-type (values-list ,results)))
`(the ,value-type ,expression))))
(define-special-operator (eval-when (&rest situations) &body body) (&environment env)
;; We must preserve toplevelness.
`(cl:eval-when (,@situations)
,@(step-body :progn body env)))
(define-special-operator (symbol-macrolet (&rest bindings) &body body) (&whole form &environment env)
(multiple-value-bind (ds declarations real-body) (parse-body :locally body)
(declare (ignore ds real-body))
(cl:if (stepper-disabled-p declarations)
`(cl:symbol-macrolet ,@(rest form))
(simple-step `(cl:symbol-macrolet ,bindings
,@(step-body :locally body env))
form))))
(define-special-operator (macrolet (&rest bindings) &body body) (&whole form &environment env)
(multiple-value-bind (ds declarations real-body) (parse-body :locally body)
(declare (ignore ds real-body))
(cl:if (stepper-disabled-p declarations)
`(cl:macrolet ,@(rest form))
(simple-step `(cl:macrolet ,bindings
,@(step-body :locally body env))
form))))
(define-special-operator (load-time-value expression &optional read-only-p) (&whole form &environment env)
(simple-step `(cl:load-time-value ,(step-expression expression env) ,read-only-p)
form))
| 5,968 | Common Lisp | .lisp | 126 | 38.515873 | 108 | 0.622606 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 3f717c8a3890b5f3070702649c3f628c8935b88c2697c39c52c6a97b1f45cfd3 | 4,688 | [
-1
] |
4,689 | simple-parse-uri.lisp | informatimago_lisp/future/simple-parse-uri.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: simple-parse-uri.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a simple uri parsing function.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2018-04-12 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2018 - 2018
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
#|
RFC-3986 says:
pct-encoded = "%" HEXDIG HEXDIG
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
hier-part = "//" authority path-abempty
/ path-absolute
/ path-rootless
/ path-empty
scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
authority = [ userinfo "@" ] host [ ":" port ]
userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
host = IP-literal / IPv4address / reg-name
IP-literal = "[" ( IPv6address / IPvFuture ) "]"
IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
IPv6address = 6( h16 ":" ) ls32
/ "::" 5( h16 ":" ) ls32
/ [ h16 ] "::" 4( h16 ":" ) ls32
/ [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
/ [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
/ [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
/ [ *4( h16 ":" ) h16 ] "::" ls32
/ [ *5( h16 ":" ) h16 ] "::" h16
/ [ *6( h16 ":" ) h16 ] "::"
ls32 = ( h16 ":" h16 ) / IPv4address
; least-significant 32 bits of address
h16 = 1*4HEXDIG
; 16 bits of address represented in hexadecimal
IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
dec-octet = DIGIT ; 0-9
/ %x31-39 DIGIT ; 10-99
/ "1" 2DIGIT ; 100-199
/ "2" %x30-34 DIGIT ; 200-249
/ "25" %x30-35 ; 250-255
reg-name = *( unreserved / pct-encoded / sub-delims )
port = *DIGIT
path = path-abempty ; begins with "/" or is empty
/ path-absolute ; begins with "/" but not "//"
/ path-noscheme ; begins with a non-colon segment
/ path-rootless ; begins with a segment
/ path-empty ; zero characters
path-abempty = *( "/" segment )
path-absolute = "/" [ segment-nz *( "/" segment ) ]
path-noscheme = segment-nz-nc *( "/" segment )
path-rootless = segment-nz *( "/" segment )
path-empty = 0<pchar>
segment = *pchar
segment-nz = 1*pchar
segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
; non-zero-length segment without any colon ":"
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
query = *( pchar / "/" / "?" )
fragment = *( pchar / "/" / "?" )
URI-reference = URI / relative-ref
relative-ref = relative-part [ "?" query ] [ "#" fragment ]
relative-part = "//" authority path-abempty
/ path-absolute
/ path-noscheme
/ path-empty
absolute-URI = scheme ":" hier-part [ "?" query ]
The authority component is preceded by a double slash ("//") and is
terminated by the next slash ("/"), question mark ("?"), or number
sign ("#") character, or by the end of the URI.
|#
;; URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
(defclass uri ()
((scheme
:initarg :scheme
:accessor scheme
:initform nil)
(userinfo
:initarg :userinfo
:accessor userinfo
:initform nil)
(host
:initarg :host
:accessor host
:initform nil)
(port
:initarg :port
:accessor port
:initform nil)
(path
:initarg :path
:accessor path
:initform nil)
(query
:initarg :query
:accessor query
:initform nil)
(fragment
:initarg :fragment
:accessor fragment
:initform nil)))
(defclass url (uri)
())
(defmethod format-url ((uri uri) stream)
(format stream "~A:~*~:[~*~;//~2:*~@[~A@~]~A~@[:~A~]~]~A~@[?~A~]~@[#~A~]"
(scheme uri)
(userinfo uri)
(host uri)
(port uri)
(path uri)
(query uri)
(fragment uri)))
(defmethod print-object ((uri uri) stream)
(print-unreadable-object (uri stream :identity t :type t)
(format-url uri stream))
uri)
(defmethod urlstring ((uri uri))
(format-url uri nil))
(defmethod hostname ((uri uri)) (host uri))
(defmethod (setf hostname) (new-host (uri uri)) (setf (host uri) new-host))
(defmethod user ((uri uri))
(when (userinfo uri)
(subseq (userinfo uri) 0 (or (position #\: (userinfo uri))))))
(defmethod password ((uri uri))
(when (userinfo uri)
(let ((colon (position #\: (userinfo uri))))
(when colon
(subseq (userinfo uri) (1+ colon))))))
(defmethod (setf user) (new-user (uri uri))
(setf (userinfo uri) (format nil "~A~@[:~A~]" new-user (password uri)))
new-user)
(defmethod (setf password) (new-password (uri uri))
(setf (userinfo uri) (format nil "~A~@[:~A~]" (user uri) new-password))
new-password)
(defun merge-urls (url1 url2)
(let ((url1 (url url1))
(url2 (url url2)))
(make-instance 'url
:scheme (or (scheme url1)
(scheme url2))
:userinfo (or (userinfo url1)
(userinfo url2))
:host (or (host url1)
(host url2))
:port (or (port url1)
(port url2))
:path (or (path url1)
(path url2))
:query (or (query url1)
(query url2))
:fragment (or (fragment url1)
(fragment url2)))))
(defun simple-parse-uri (string)
(flet ((prefixp (prefix string) (and (<= (length prefix) (length string))
(string= prefix string :end2 (length prefix))))
(after (index) (when index (1+ index))))
(let* ((scheme-end (or (after (position #\: string))
(error "Only URI (RFC-3986) are accepted, not relative-refs.")))
(scheme (subseq string 0 (1- scheme-end)))
(without-scheme (subseq string scheme-end))
(authorityp (prefixp "//" without-scheme))
(abpath-start (if authorityp
(or (position #\/ without-scheme :start 2) (length without-scheme))
0))
(path-and-qf (subseq without-scheme abpath-start))
(sharp (position #\# path-and-qf :from-end t))
(query-end (or sharp (length path-and-qf)))
(fragment-start (after sharp))
(question (position #\? path-and-qf :end sharp))
(path-end (or question sharp (length path-and-qf)))
(query-start (after question))
(query (when query-start (subseq path-and-qf query-start query-end)))
(fragment (when fragment-start (subseq path-and-qf fragment-start)))
(path (subseq path-and-qf 0 path-end)))
(if authorityp
(let* ((authority (subseq without-scheme 2 abpath-start))
(userinfo-end (position #\@ authority))
(host-start (if userinfo-end (1+ userinfo-end) 0))
(colon (position #\: authority
:start (if (char= #\[ (aref authority host-start))
(after (position #\] authority :start host-start))
host-start)))
(port-start (or (after colon) (length authority)))
(userinfo (when userinfo-end
(subseq authority 0 userinfo-end)))
(host (subseq authority host-start colon))
(port-string (subseq authority port-start))
(port (when (plusp (length port-string))
(parse-integer port-string :junk-allowed nil))))
(make-instance 'uri
:scheme scheme
:userinfo userinfo
:host host
:port port
:path path
:query query
:fragment fragment))
(make-instance 'uri
:scheme scheme
:path path
:query query
:fragment fragment)))))
(defun test/simple-parse-uri ()
(map 'list (lambda (test)
(let* ((uri (simple-parse-uri (first test)))
(result (list (first test)
:scheme (scheme uri)
:userinfo (userinfo uri)
:host (host uri)
:port (port uri)
:path (path uri)
:query (query uri)
:fragment (fragment uri))))
(assert (equalp test result))
uri))
'(("ftp://ftp.is.co.za/rfc/rfc1808.txt" :scheme "ftp" :userinfo nil :host "ftp.is.co.za" :port nil :path "/rfc/rfc1808.txt" :query nil :fragment nil)
("ftp://[email protected]/rfc/rfc1808.txt" :scheme "ftp" :userinfo "user" :host "ftp.is.co.za" :port nil :path "/rfc/rfc1808.txt" :query nil :fragment nil)
("ftp://user:[email protected]/rfc/rfc1808.txt" :scheme "ftp" :userinfo "user:password" :host "ftp.is.co.za" :port nil :path "/rfc/rfc1808.txt" :query nil :fragment nil)
("http://www.ietf.org/rfc/rfc2396.txt" :scheme "http" :userinfo nil :host "www.ietf.org" :port nil :path "/rfc/rfc2396.txt" :query nil :fragment nil)
("http://www.ietf.org/rfc/rfc2396.txt#sect1" :scheme "http" :userinfo nil :host "www.ietf.org" :port nil :path "/rfc/rfc2396.txt" :query nil :fragment "sect1")
("http://www.ietf.org/rfc/rfc2396.txt?format=text" :scheme "http" :userinfo nil :host "www.ietf.org" :port nil :path "/rfc/rfc2396.txt" :query "format=text" :fragment nil)
("http://www.ietf.org/rfc/rfc2396.txt?format=text#sect1" :scheme "http" :userinfo nil :host "www.ietf.org" :port nil :path "/rfc/rfc2396.txt" :query "format=text" :fragment "sect1")
("ldap://[2001:db8::7]/c=GB?objectClass?one" :scheme "ldap" :userinfo nil :host "[2001:db8::7]" :port nil :path "/c=GB" :query "objectClass?one" :fragment nil)
("telnet://192.0.2.16:80/" :scheme "telnet" :userinfo nil :host "192.0.2.16" :port 80 :path "/" :query nil :fragment nil)
("mailto:[email protected]" :scheme "mailto" :userinfo nil :host nil :port nil :path "[email protected]" :query nil :fragment nil)
("news:comp.infosystems.www.servers.unix" :scheme "news" :userinfo nil :host nil :port nil :path "comp.infosystems.www.servers.unix" :query nil :fragment nil)
("tel:+1-816-555-1212" :scheme "tel" :userinfo nil :host nil :port nil :path "+1-816-555-1212" :query nil :fragment nil)
("urn:oasis:names:specification:docbook:dtd:xml:4.1.2" :scheme "urn" :userinfo nil :host nil :port nil :path "oasis:names:specification:docbook:dtd:xml:4.1.2" :query nil :fragment nil))))
#|
(test/simple-parse-uri)
(#<uri ftp://ftp.is.co.za/rfc/rfc1808.txt #x30200223E76D>
#<uri ftp://[email protected]/rfc/rfc1808.txt #x30200223E3DD>
#<uri ftp://user:[email protected]/rfc/rfc1808.txt #x30200223DFED>
#<uri http://www.ietf.org/rfc/rfc2396.txt #x30200223DCAD>
#<uri http://www.ietf.org/rfc/rfc2396.txt#sect1 #x30200223D91D>
#<uri http://www.ietf.org/rfc/rfc2396.txt?format=text #x30200223D53D>
#<uri http://www.ietf.org/rfc/rfc2396.txt?format=text#sect1 #x30200223D10D>
#<uri ldap://[2001:db8::7]/c=GB?objectClass?one #x30200223CD7D>
#<uri telnet://192.0.2.16:80/ #x30200223CAFD>
#<uri mailto:[email protected] #x30200223C84D>
#<uri news:comp.infosystems.www.servers.unix #x30200223C50D>
#<uri tel:+1-816-555-1212 #x30200223C28D>
#<uri urn:oasis:names:specification:docbook:dtd:xml:4.1.2 #x30200223BE8D>)
|#
(defun url (thing)
(if (stringp thing)
(simple-parse-uri thing)
thing))
| 15,090 | Common Lisp | .lisp | 278 | 43.154676 | 238 | 0.48245 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 4b7d65ffb818c8d747831de3ae8a02b077aab37b957fbed62afb793fffe38168 | 4,689 | [
-1
] |
4,690 | roman-calendar.lisp | informatimago_lisp/future/roman-calendar.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: roman-calendar.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a Roman Calendar as described in:
;;;; http://www.webexhibits.org/calendars/calendar-roman.html
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2014-04-26 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2014 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.ROMAN-CALENDAR"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DATE.UTILITY")
(:export)
(:documentation "
Defines the Roman calendar.
See also: COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DATE
COM.INFORMATIMAGO.COMMON-LISP.CESARUM.DATE.UTILITY
COM.INFORMATIMAGO.COMMON-LISP.GREGORIAN-CALENDAR
COM.INFORMATIMAGO.COMMON-LISP.JULIAN-CALENDAR
License:
AGPL3
Copyright Pascal J. Bourguignon 2014 - 2014
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program.
If not, see <http://www.gnu.org/licenses/>
"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.ROMAN-CALENDAR")
;; Romulus from -700
;; 10 months in 304 days plus 61 days year
(defvar *romulus-month-names* '("martius" "aprilis" "maius" "junius" "quintilis"
"sextilis" "september" "october" "november" "december"))
;; Numa Pompilius:
;; 355-day year
(defvar *numa-pompilius-month-names* '("january" "february" "mercedinus"
"martius" "aprilis" "maius" "junius" "quintilis"
"sextilis" "september" "october" "november" "december"))
;; mercedinus = 22 or 23 days, _inserted_ after february 23 or 24, every other year.
;; Julius Caesar, from -45 julian Calendar
;; 365 days + bisextile years every 4 years. extra day after february 23.
;; Kalend 1st day of the month
;; Nones 5th (or 7th) day
;; Ides 15th (or 13th) day.
;; Days after Ides are counted down toward the next month's Kalends.
(defun nundial-letter (nundial)
(aref "ABCDEFGHI" nundial))
(defun format-kalend (nundial kalend month)
(format nil "~A~A·~A·F" (nundial-letter nundial) kalend month))
(defun format-special (nundial feriae)
(format nil "~A~A·N" (nundial-letter nundial) feriae ))
(defun format-regular (nundial day)
(format nil "~A~A" (nundial-letter nundial) day))
(("F" "dies fasti" "legal action and public voting are permited")
("N" "dies nefasti" "no legal action or public voting allowed")
("EN" "endotercisus" "days between F or C where morning and afternnons have different designation")
("NP" "" "major holidays -- all records have disappeared")
("FP" "" "religious holidays -- no definition survives"))
full-moon Ides
(+ full-moon 1) .. (- first-quarter 1) Kalends
first-quarter Nones
| 4,516 | Common Lisp | .lisp | 94 | 44.425532 | 100 | 0.663558 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 54e74c944884bb8d4a29796bdb8c42c7d72d7247d4a4f34d932418cd174d2384 | 4,690 | [
-1
] |
4,691 | export.lisp | informatimago_lisp/future/export.lisp | (in-package "COMMON-LISP-USER")
(defun process-defuns (function form)
(cond
((atom form))
((member (car form) '(defun defmacro defgeneric defmethod))
(funcall function form))
(t
(process-defuns function (car form))
(process-defuns function (cdr form)))))
(defun defined-symbols (form)
(let ((result '()))
(flet ((collect (symbol) (push symbol result)))
(process-defuns (lambda (form)
(cond
((symbolp (second form))
(collect (second form)))
((and (consp (second form))
(eql 'setf (first (second form))))
(collect (second (second form))))))
(macroexpand-1 form))
(remove-duplicates result))))
(defun export-symbols (syms)
`(:export ,@(sort (mapcar (function string) syms) (function string<))))
| 930 | Common Lisp | .lisp | 23 | 29.086957 | 73 | 0.535477 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b7c84f16d8c5dae8fa95a940199d9cb226f630d338d2a8390929d4b7a550d3b6 | 4,691 | [
-1
] |
4,692 | docutils-patches.lisp | informatimago_lisp/future/markup/docutils-patches.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: docutils-patches.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Patches to docutils.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-04-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package :docutils)
;; (defmethod print-object((node field-name) stream)
;; (format stream "~A " (as-text node))
;; (print-unreadable-object (node stream :type t :identity t)
;; (format stream "~S ~@[line ~D ~]" (as-text node) (line node)))
;; node)
;;
;; (defmethod print-object((node field) stream)
;; (print-unreadable-object (node stream :type t :identity t)
;; (format stream "~S ~@[line ~D ~]"
;; (when (child node 0) (as-text (child node 0)))
;; (line node)))
;; node)
(defparameter *print-object-indent-bar* "|")
(defparameter *print-object-indent-stem* "+")
(setf *print-circle* nil
*print-pretty* nil)
(defmethod print-object ((node text) stream)
(format stream "~A-- ~A ~@[line ~D, ~] ~S~%"
*print-object-indent-stem*
(class-name (class-of node))
(line node)
(if (slot-boundp node 'text)
(let* ((text (slot-value node 'text))
(extract (subseq text 0 (min 20 (or (position #\newline text)
(length text))))))
(if (< (length extract) (length text))
(concatenate 'string extract "…")
extract))
"#<UNBOUND>"))
node)
(defmethod print-object ((node element) stream)
(setf *print-circle* nil)
(format stream "~A--+-- ~A ~@[~S ~]~@[line ~D, ~]~:[~;~D child~:[~;ren~]~]~%"
*print-object-indent-stem*
(class-name (class-of node))
(attribute node :name)
(line node)
(> (number-children node) 0)
(number-children node)
(< 1 (number-children node)))
(format stream "~A ~:[ ~;|~] ~:[()~;~:*~S~]~%"
*print-object-indent-bar*
(slot-value node 'children)
(slot-value node 'attributes))
(when (slot-value node 'children)
(let ((*print-object-indent-bar* (concatenate 'string *print-object-indent-bar* " |"))
(*print-object-indent-stem* (concatenate 'string *print-object-indent-bar* " +")))
(format stream "~{~A~}" (butlast (slot-value node 'children))))
(let ((*print-object-indent-bar* (concatenate 'string *print-object-indent-bar* " "))
(*print-object-indent-stem* (concatenate 'string *print-object-indent-bar* " +")))
(format stream "~A" (car (last (slot-value node 'children)))))
(format stream "~A~%" *print-object-indent-bar*))
node)
(defmethod print-object ((node evaluateable) stream)
(format stream "~A-- ~A ~@[~S ~]~@[line ~D, ~] ~S ~S ~S ~S~%"
*print-object-indent-stem*
(class-name (class-of node))
(attribute node :name)
(line node)
(evaluation-language node)
(output-format node)
(expression node)
(if (slot-boundp node 'result)
(slot-value node 'result)
'<not-computed-yet>))
node)
;;;; THE END ;;;;
| 4,408 | Common Lisp | .lisp | 103 | 37.009709 | 93 | 0.560345 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 90f3406e1b98a81008c19c6eb26b6092100f17bde629f895fd73d191ff79775b | 4,692 | [
-1
] |
4,693 | markups.lisp | informatimago_lisp/future/markup/markups.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: markups.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; XXX
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-04-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defparameter *contents*
'((no-markup "A string without newlines or markup.")
(markup-line "A string without newlines, with possibly markup.")
(multi-line "A string possibly with newlines and markup.")
(url "A string containing an URL.")))
;; markup ::= (item…) | compound .
;; item ::= STRING | content .
;; content ::= no-markup | markup-line | multi-line | url .
;; compound ::= (or markup…)
;; | (each-line markup)
;; | (lines markup…)
;; | (same-length content STRING) .
(defparameter *markups*
'(("AsciiDoc"
;; double operators ignore special characters
:bold (or ("*" markup-line "*") ("**" no-markup "**"))
:italic (or ("_" markup-line "_") ("__" no-markup "__"))
:monospace (or ("+" markup-line "+") ("++" no-markup "++"))
:header1 (or ("=" markup-line (optional "="))
(lines (markup-line)
(same-length markup-line "=")))
:header2 (or ("==" markup-line (optional "=="))
(lines (markup-line)
(same-length markup-line "-")))
:header3 (or ("===" markup-line (optional "==="))
(lines (markup-line)
(same-length markup-line "~")))
:link (or (url) (url "[" markup-line "]") ))
("BBCode"
:bold ("[b]" multi-line "[/b]")
:italic ("[i]" multi-line "[/i]")
:monospace ("[code]" multi-line "[/code]")
:link (or ("[url]" url "[/url]")
("[url=" url "]" markup-line "[/url]")))
("Creole"
;; Triple curly braces are for nowiki which is optionally
;; monospace in Creole (the choice of the implementor). Future
;; Creole additions may introduce double hash marks (##) for
;; monospace.
:bold ("**" markup-line "**")
:italic ("//" markup-line "//")
:monospace ("{{{" multi-line "}}}")
:header1 ("=" markup-line (optional "="))
:header2 ("==" markup-line (optional "=="))
:header3 ("===" markup-line (optional "==="))
:link (or ("[[" url "]]")
("[[" url "|" markup-line "]]")))
("deplate"
:bold ("{text style=bold: " multi-line "}")
:italic ("__" markup-line "__")
:monospace ("''" markup-line "''")
:header1 ("*" markup-line)
:header2 ("**" markup-line)
:header3 ("***" markup-line)
:link (or ("[[" url "]]")
("[[" url "][" markup-line "]]")))
("Markdown"
:bold ("**" markup-line "**")
:italic ("*" markup-line "*")
;; Monospace text is created by indenting that line 4 spaces or
;; one tab character, or enclosing text in backticks:
;; `monospaces`.
:monospace (or
("`" markup-line "`")
(each-line (" " markup-line)))
:header1 (or ("#" markup-line (optional "#"))
(lines (markup-line)
(same-length markup-line "=")))
:header2 (or ("##" markup-line (optional "##"))
(lines (markup-line)
(same-length markup-line "-")))
:header3 ("###" markup-line (optional "###"))
:header4 ("####" markup-line (optional "####"))
:header5 ("#####" markup-line (optional "#####"))
:header6 ("######" markup-line (optional "######"))
:link ("[" markup-line "](" url ")")
;; Also [link-text][linkref]
;; followed by [linkref]: url "title"
)
("MediaWiki"
:bold ("'''" markup-line "'''")
:italic ("''" markup-line "''")
:monospace ("<code>" markup-line "</code>")
:header1 ("=" markup-line)
:header2 ("==" markup-line)
:header3 ("===" markup-line)
:header4 ("====" markup-line)
:header5 ("=====" markup-line)
:header6 ("======" markup-line)
:link (or ("[[" url "]]")
("[[" url "|" markup-line "]]")))
("Org-mode"
:bold ("*" markup-line "*")
:italic ("/" markup-line "/")
:underlined ("_" markup-line "_")
:strike-through ("+" markup-line "+")
:monospace ("=" markup-line "=")
:verbatim ("~" markup-line "~")
:header1 ("*" markup-line)
:header2 ("**" markup-line)
:header3 ("***" markup-line)
:link (or ("[[" url "]]")
("[[" url "][" markup-line "]]")))
("PmWiki"
:bold ("'''" markup-line "'''")
:italic ("''" markup-line "''")
:monospace ("@@" markup-line "@@")
:header1 ("!" markup-line)
:header2 ("!!" markup-line)
:header3 ("!!!" markup-line)
:header4 ("!!!!" markup-line)
:header5 ("!!!!!" markup-line)
:header6 ("!!!!!!" markup-line)
:link (or ("[[" url "]]")
("[[" url "][" markup-line "]]")))
("POD"
:bold ("B<" markup-line ">")
:italic ("I<" markup-line ">")
:monospace (or
("C<" markup-line ">")
(each-line (" " markup-line)))
:header1 ("=head1 " markup-line)
:header2 ("=head2 " markup-line)
:link ("L<" url ">"))
("reStructuredText"
:bold ("**" markup-line "**")
:italic ("*" markup-line "*")
:monospace ("``" markup-line "``")
;; Any of the following characters can be used as the
;; "underline": = - ` : ' " ~ ^ _ * + # < >. The same character
;; must be used for the same indentation level and may not be
;; used for a new indentation level.
;; And the lines can also appear above and below, not just below.
:header1 (lines (markup-line)
(same-length markup-line "#"))
:header2 (lines (markup-line)
(same-length markup-line "="))
:header3 (lines (markup-line)
(same-length markup-line "-"))
:header4 (lines (markup-line)
(same-length markup-line "+"))
:header5 (lines (markup-line)
(same-length markup-line "~"))
:header6 (lines (markup-line)
(same-length markup-line "^"))
:link ("`" markup-line "<" url ">`_")
;; Also: Linkref_
;; followed by: .. _Linkref: url
)
("Setext"
:bold ("**" markup-line "**")
:italic ("~" markup-line "~"))
("Textile"
:bold (or ("*" markup-line "*") ("**" markup-line "**"))
:italic (or ("_" markup-line "_") ("__" markup-line "__"))
:monospace ("@" multi-line "@")
:header1 ("h1. " markup-line)
:header2 ("h2. " markup-line)
:header3 ("h3. " markup-line)
:header4 ("h4. " markup-line)
:header5 ("h5. " markup-line)
:header6 ("h6. " markup-line)
:link ("\"" markup-line "\":" url)
;; Also: "link text (optional title attribute)":url
;; Also: "link text":linkref
;; followed by : [linkref (optional title attribute)]url
)
("Texy!"
:bold ("**" markup-line "**")
:italic (or ("*" markup-line "*") ("//" markup-line "//"))
:monospace ("`" multi-line "`")
:header1 (or ("######" markup-line (optional "######"))
(lines (markup-line)
(same-length markup-line "#")))
:header2 (or ("#####" markup-line (optional "#####"))
(lines (markup-line)
(same-length markup-line "*")))
:header3 (or ("####" markup-line (optional "####"))
(lines (markup-line)
(same-length markup-line "=")))
:header4 (or ("###" markup-line (optional "###"))
(lines (markup-line)
(same-length markup-line "-")))
:header5 ("##" markup-line (optional "##"))
:header6 ("#" markup-line (optional "#"))
:link ("\"" markup-line "\":" url)
;; Also: "link text .(optional title attribute)[optional class or id]{optional style}":url
;; Also: "link text":linkref
;; followed by : [linkref]:url .(optional title attribute)[optional class or id]{optional style}]
)
("txt2tags"
:bold ("**" markup-line "**")
:italic ("//" markup-line "//")
:monospace ("``" multi-line "``")
:underlined ("__" markup-line "__")
:strike-through ("--" markup-line "--")
:header1 (or ("=" markup-line "=") ("+" markup-line "+"))
:header2 (or ("==" markup-line "==") ("++" markup-line "++"))
:header3 (or ("===" markup-line "===") ("+++" markup-line "+++"))
:header4 (or ("====" markup-line "====") ("++++" markup-line "++++"))
:header5 (or ("=====" markup-line "=====") ("+++++" markup-line "+++++"))
:header6 (or ("======" markup-line "======") ("++++++" markup-line "++++++"))
:link ("[" markup-line url "]"))))
(docutils:read-rst (com.informatimago.common-lisp.cesarum.file:text-file-contents
#p"/home/pjb/d/specifications.rst"))
;;;; THE END ;;;;
| 10,429 | Common Lisp | .lisp | 241 | 36.435685 | 102 | 0.489527 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 751056f95556246e8bee67801aea286e78c68c1c2bede817050cab2b1849b3ca | 4,693 | [
-1
] |
4,694 | map-sexps.lisp | informatimago_lisp/future/lisp-sexp/map-sexps.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: map-sexps.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; MAP-SEXPS can be used to filter lisp sources.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-06 <PJB> Translated from emacs lisp.
;;;; 2003-01-20 <PJB> Added walk-sexps, map-sexps, replace-sexps;
;;;; reimplemented get-sexps with walk-sexps.
;;;; 199?-??-?? <PJB> pjb-sources.el creation.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.LISP-SEXP.MAP"
(:use "COMMON-LISP")
(:export
"MAP-SEXPS"
"WALK-SEXPS")
(:documentation "
This package exports functions to apply a function to all the
sexps in a lisp source file.
Copyright Pascal J. Bourguignon 2003 - 2007
This package is provided under the GNU General Public License.
See the source file for details."))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.LISP-SEXP.SEXP-SOURCE")
;; ------------------------------------------------------------------------
;; map-sexps
;; ------------------------------------------------------------------------
;; Applies a function on all s-exps from a lisp source file.
;;
(defun skip-comments ()
"
DO: Move the point over spaces and lisp comments ( ;...\n or #| ... |# ),
in the current buffer.
RETURN: (not eof)
"
(interactive)
(let* ((data (header-comment-description-for-mode major-mode))
(comment-regexp (hcd-comment-regexp data))
(space-or-comment (format "\\(%s\\)\\|\\(%s\\)"
"[ \t\n\v\f\r]+"
comment-regexp)) )
(unless data
(error "Don't know how to handle this major mode %S." major-mode))
(while (looking-at space-or-comment)
(goto-char (match-end 0)))
(< (point) (point-max))))
(defparameter *source-readtable*
(when (fboundp 'copy-readtable)
(let ((rt (copy-readtable nil)))
(set-dispatch-macro-character (cl-char ?#) (cl-char ?+)
(lambda (stream subchar arg)
`('\#+ ,(read stream nil nil t)))
rt)
(set-dispatch-macro-character (cl-char ?#) (cl-char ?-)
(lambda (stream subchar arg)
`('\#- ,(read stream nil nil t)))
rt)
rt)))
(defvar *map-sexps-top-level* nil "Private")
(defvar *map-sexps-deeply* nil "Private")
(defvar *map-sexps-atoms* nil "Private")
(defvar *map-sexps-function* nil "Private")
(defvar *walk-sexps-end-marker* nil)
(defun walk-sexps (fun)
"
DO: Recursively scan sexps from (point) in current buffer up to
the end-of-file or until scan-sexps raises a scan-error.
Call fun on each sexps and each of their children etc.
fun: A function (sexp start end)
sexp: The sexp parsed from a source file.
start: The point starting the sexp.
end: The point ending the sexp.
NOTE: All positions are kept in markers, so modifying the buffer between
start and end should be OK.
However ' or ` are passed as (quote ...) or (backquote ...)
to the function fun without reparsing the sexp inside them.
Ie. if you modify such a source, (which can be detected looking at
the character at start position), you still get the original sexp.
"
(let ((quote-stack '())
(start-stack '())
(*walk-sexps-end-marker* (make-marker))
quote-depth
start-m sexp)
(skip-comments)
(when (/= (point) (point-max))
(when (member major-mode *lisp-modes*)
;; gather the quotes:
(while (looking-at "['`] *")
;; quote or backquote
;; NOT NEEDED ANYMORE WITH GNU Emacs 21.
;; --- (push (set-marker (make-marker) (point)) start-stack)
;; --- (push (if (= (char-after) ?') 'quote 'backquote) quote-stack)
(forward-char 1)
(skip-comments)))
;; get the sexp:
(setq start-m (set-marker (make-marker) (point)))
(forward-sexp 1)
(set-marker *walk-sexps-end-marker* (point))
;; (forward-sexp -1)
;; (assert (= (marker-position start-m) (point)) t)
(goto-char (marker-position start-m))
(setq sexp (cl-sexp-at-point))
;; push the quotes on the sexp:
(setq quote-depth (length quote-stack))
(while quote-stack
(setq sexp (cons (pop quote-stack) (list sexp))))
;; process the quotes:
(setq start-stack (nreverse start-stack))
(dotimes (i quote-depth)
(message "sexp = %S\nstart = %S\nend = %S\n" sexp (marker-position (car start-stack)) *walk-sexps-end-marker*)
(funcall fun sexp
(marker-position (car start-stack)) *walk-sexps-end-marker*)
(set-marker (pop start-stack) nil)
(setq sexp (cadr sexp)))
;; process the sexp:
(message "sexp = %S\nstart = %S\nend = %S\n" sexp (marker-position start-m) *walk-sexps-end-marker*)
(funcall fun sexp (marker-position start-m) *walk-sexps-end-marker*)
(when *map-sexps-deeply*
(when (= (char-syntax (char-after (marker-position start-m))) 40) ;; "("
;; then the subsexps:
(goto-char (marker-position start-m))
(down-list 1)
(loop
(condition-case nil
(walk-sexps fun)
(scan-error (return-from nil))))
(up-list 1)))
;; then go to the next sexp:
(goto-char (marker-position *walk-sexps-end-marker*))
(set-marker start-m nil)
(set-marker *walk-sexps-end-marker* nil)))
nil)
(defun map-sexps-filter (sexp start end)
(when (and (or *map-sexps-top-level* *map-sexps-deeply*)
(or *map-sexps-atoms* (not (atom sexp))))
(funcall *map-sexps-function* sexp start end))
(setq *map-sexps-top-level* nil))
(defun new-map-sexps (source-file fun &rest cl-keys)
"
DO: Scan all sexps in the source file.
(skipping spaces and comment between top-level sexps).
If the deeply flag is set,
then subsexps are also passed to the function fun, after the sexp,
else only the top-level sexps are
If the atoms flags is set
then atoms are also considered (and passed to the selector).
fun: A function (sexp start end)
sexp: The sexp parsed from a source file.
start: The point starting the sexp.
end: The point ending the sexp.
KEYS: :deeply (boolean, default nil)
:atoms (boolean, default nil)
NOTE: Scanning stops as soon as an error is detected by forward-sexp.
RETURN: The list of results from fun.
"
(cl-parsing-keywords ((:deeply t)
(:atoms nil)) nil
))
(defun new-map-sexps (source-file fun &rest cl-keys)
"
DO: Scan all sexps in the source file.
(skipping spaces and comment between top-level sexps).
If the deeply flag is set,
then subsexps are also passed to the function fun, after the sexp,
else only the top-level sexps are
If the atoms flags is set
then atoms are also considered (and passed to the selector).
fun: A function (sexp start end)
sexp: The sexp parsed from a source file.
start: The point starting the sexp.
end: The point ending the sexp.
KEYS: :deeply (boolean, default nil)
:atoms (boolean, default nil)
NOTE: Scanning stops as soon as an error is detected by forward-sexp.
RETURN: The list of results from fun.
"
(cl-parsing-keywords ((:deeply t)
(:atoms nil)) nil
`(source-text:map-source-file ,fun ,source-file
:deeply ,cl-deeply
:atoms ,cl-atoms)
))
(defun map-sexps (source-file fun &rest cl-keys)
"
DO: Scan all sexps in the source file.
(skipping spaces and comment between top-level sexps).
If the deeply flag is set,
then subsexps are also passed to the function fun, after the sexp,
else only the top-level sexps are
If the atoms flags is set
then atoms are also considered (and passed to the selector).
fun: A function (sexp start end)
sexp: The sexp parsed from a source file.
start: The point starting the sexp.
end: The point ending the sexp.
KEYS: :deeply (boolean, default nil)
:atoms (boolean, default nil)
NOTE: Scanning stops as soon as an error is detected by forward-sexp.
RETURN: The list of results from fun.
"
(cl-parsing-keywords ((:deeply nil)
(:atoms nil)) ()
(message "map-sexps deeply %S atoms %S" cl-deeply cl-atoms)
(save-excursion
(save-restriction
(let ((old-buffer (current-buffer))
(existing-buffer (buffer-named source-file))
(*map-sexps-deeply* cl-deeply)
(*map-sexps-atoms* cl-atoms)
(*map-sexps-top-level* t)
(*map-sexps-function* fun)
last-bosexp)
(if existing-buffer
(switch-to-buffer existing-buffer)
(find-file source-file))
(widen)
(goto-char (point-min))
(while (< (point) (point-max))
(setq *map-sexps-top-level* t)
(walk-sexps (function map-sexps-filter)))
(if existing-buffer
(switch-to-buffer old-buffer)
(kill-buffer (current-buffer))))))))
(defun old-old-map-sexps (source-file fun)
"
DO: Scan all top-level sexps in the source file.
(skipping spaces and comment between top-level sexps).
fun: A function (sexp start end)
sexp: The sexp parsed from a source file.
start: The point starting the sexp.
end: The point ending the sexp.
:deeply
NOTE: Scanning stops as soon as an error is detected by forward-sexp.
RETURN: The list of results from fun.
"
(save-excursion
(save-restriction
(let ((old-buffer (current-buffer))
(existing-buffer (buffer-named source-file))
last-bosexp)
(if existing-buffer
(switch-to-buffer existing-buffer)
(find-file source-file))
(widen)
(goto-char (point-max))
(forward-sexp -1)
(setq last-bosexp (point))
(goto-char (point-min))
(prog1
(loop with eof = (gensym)
while (<= (point) last-bosexp)
for end = (progn (forward-sexp 1) (point))
for start = (progn (forward-sexp -1) (point))
for sexp = (condition-case nil (sexp-at-point) (error eof))
until (eq eof sexp)
collect (funcall fun sexp start end) into map-sexps-result
do (condition-case nil
(forward-sexp 1)
(error (goto-char (point-max)))
(wrong-type-argument (goto-char (point-max))))
finally (unless existing-buffer (kill-buffer source-file))
finally return (nreverse map-sexps-result))
(switch-to-buffer old-buffer))))))
(defun count-sexps ()
(interactive)
(save-excursion
(goto-char (point-min))
(let ((place (point))
(count 0))
(forward-sexp)
(while (< place (point))
(incf count)
(setq place (point))
(forward-sexp))
(message "There are %d top-level sexps." count)
count))) ;;count-sexps
;; ------------------------------------------------------------------------
;; get-sexps
;; ------------------------------------------------------------------------
;; Read all s-exps from a lisp source file. Can filter s-exps by a given
;; selector function.
;;
(defun get-sexps (source-file &rest cl-keys)
"
KEYS: :selector (function: sexp --> boolean, default: (lambda (s) t))
:deeply (boolean, default nil)
:atoms (boolean, default nil)
DO: Scan all sexp in the source-file.
A selector function may indicate which sexp must be collected.
If the deeply flag is set,
then if a sexp is not selected then sub-sexp are scanned and tested.
If the atoms flags is set
then atoms are also considered (and passed to the selector).
NOTE: Scanning stops as soon as an error is detected by forward-sexp.
RETURN: A list of selected sexp.
"
(save-excursion
(cl-parsing-keywords ((:selector (function (lambda (s) t)))
(:deeply nil)
(:atoms nil)) nil
(let ((get-sexps-result '()))
(map-sexps
source-file
(lambda (sexp start end)
(when (funcall cl-selector sexp)
(push sexp get-sexps-result)))
:deeply cl-deeply :atoms cl-atoms)
(nreverse get-sexps-result)))))
;;; (show
;;; (sort
;;; (let ((histo (make-hash-table)) (max-lisp-eval-depth 1000))
;;; (mapc (lambda (path)
;;; (message path)
;;; (mapcar (lambda (sexp) (incf (gethash (depth sexp) histo 0)))
;;; (get-sexps path)))
;;; (directory "~/src/common/lisp/emacs/[a-z]*.el"))
;;; (let ((result '()))
;;; (maphash (lambda (deep value) (push (cons deep value) result)) histo)
;;; result))
;;; (lambda (a b) (< (car a) (car b))))
;;; )
;;;
;;; ==> ((1 . 325) (2 . 329) (3 . 231) (4 . 163) (5 . 138) (6 . 158) (7 .
;;; 102) (8 . 94) (9 . 63) (10 . 40) (11 . 16) (12 . 20) (13 . 9) (14 . 4)
;;; (15 . 5) (16 . 4) (17 . 2) (19 . 2) (23 . 1))
;; (defun old-get-sexps (source-file &rest cl-keys)
;; "
;; KEYS: :selector (a function, default: true)
;; :deeply (a boolean, default nil)
;; :atoms (a boolean, default nil)
;; DO: Scan all sexp in the source-file.
;; A selector function (sexp->bool) may indicate which sexp must
;; be collected. If the deeply flag is set, then if a sexp is not
;; selected then sub-sexp are scanned and tested. If the atoms flags
;; is set then atoms are also considered (and passed to the selector).
;; NOTE: Scanning stops as soon as an error is detected by forward-sexp.
;; RETURN: A list of selected sexp.
;; "
;; (cl-parsing-keywords ((:selector (function identity))
;; (:deeply nil)
;; (:atoms nil)) nil
;; (save-excursion
;; (save-restriction
;; (let ((existing-buffer (buffer-named source-file)))
;; (if existing-buffer
;; (set-buffer existing-buffer)
;; (find-file source-file))
;; (widen)
;; (goto-char (point-min))
;; (loop with result = nil
;; while (/= (point) (point-max))
;; for sexp = (condition-case nil (sexp-at-point) (error nil))
;; do (flet ((deeply-select
;; (sexp)
;; (if (atom sexp)
;; (if (and cl-atoms (funcall cl-selector sexp))
;; (push sexp result))
;; (let (subsexp)
;; (while sexp
;; (if (consp sexp)
;; (setq subsexp (car sexp)
;; sexp (cdr sexp))
;; (setq subsexp sexp
;; sexp nil))
;; (cond
;; ((atom subsexp)
;; (if (and cl-atoms
;; (funcall cl-selector subsexp))
;; (push subsexp result)))
;; ((funcall cl-selector subsexp)
;; (push subsexp result))
;; (cl-deeply
;; (deeply-select subsexp))))))))
;; (if (atom sexp)
;; (if (and cl-atoms (funcall cl-selector sexp))
;; (push sexp result))
;; (cond
;; ((funcall cl-selector sexp)
;; (push sexp result))
;; (cl-deeply
;; (deeply-select sexp)))))
;; (condition-case nil
;; (forward-sexp 1)
;; (error (goto-char (point-max)))
;; (wrong-type-argument (goto-char (point-max))))
;; finally (unless existing-buffer (kill-buffer source-file))
;; finally return (nreverse result))
;; ))))
;; ) ;;old-get-sexps
;; ------------------------------------------------------------------------
;; replace-sexps
;; ------------------------------------------------------------------------
;; Applies a transformer function to all s-exps from a lisp source file,
;; replacing them by the result of this transformer function in the source file.
;;
;;; TODO: Use CLISP to pretty print, or find an elisp pretty printer.
;;; "(LET ((*PRINT-READABLY* T))
;;; (SETF (READTABLE-CASE *READTABLE*) :PRESERVE)
;;; (WRITE (QUOTE ~S )))"
(defun replace-sexps (source-file transformer &rest cl-keys)
"
DO: Scan all sexp in the source-file.
Each sexps is given to the transformer function whose result
replaces the original sexps in the source-file.
If the deeply flag is set, then the transformer is applied
recursively to the sub-sexps.
If the atoms flags is set then atoms are also considered
(and passed to the transformer).
KEYS: :deeply (a boolean, default nil)
:atoms (a boolean, default nil)
transformer: A function sexp --> sexp.
If returing its argument (eq),
then no replacement takes place (the comments and formating
is then preserved. Otherwise the source of the sexp is
replaced by the returned sexp.
NOTE: For now, no pretty-printing is done.
"
(cl-parsing-keywords ((:deeply nil)
(:atoms nil)) nil
(map-sexps
source-file
(lambda (sexp start end)
(let ((replacement (funcall transformer sexp)))
(unless (eq replacement sexp)
(delete-region start end)
(insert (let ((print-escape-newlines t)
(print-level nil)
(print-circle nil)
(print-length nil)) (format "%S" replacement)))
(set-marker end (point)))))
:deeply cl-deeply :atoms cl-atoms))
nil)
;; ------------------------------------------------------------------------
;; clean-if*
;; ------------------------------------------------------------------------
;; Replace if* by if, when, unless or cond.
;;
(defun escape-sharp ()
(interactive)
(save-excursion
(goto-char (point-min))
(while
(re-search-forward "\\(#\\([^A-Za-z0-9()\\\\ ]\\|\\\\.\\)*\\)" nil t)
(let* ((match (match-string 1))
(escap (base64-encode-string match t)))
(replace-match (format "|ESCAPED-SHARP:%s|" escap) t t)))))
;;; (let ((s "toto #.\\( titi"))
;;; (string-match "\\(#\\(\\\\.\\|[^A-Za-z0-9()\\\\ ]\\)*\\)" s)
;;; (match-string 1 s))
(defun unescape-sharp ()
(interactive)
(save-excursion
(goto-char (point-min))
(while (re-search-forward
"\\(|ESCAPED-SHARP:\\([A-Za-z0-9+/=*]*\\)|\\)" nil t)
(let* ((escap (match-string 2))
(match (base64-decode-string escap)))
(replace-match match t t nil 1)))))
(defun clean-if* ()
(escape-sharp)
(unwind-protect
(replace-sexps
(buffer-file-name)
(lambda (sexp)
(message "sexp=%S" sexp )
(let ((backquoted (eql '\` (car sexp)))
(original-sexp sexp))
(when backquoted (setq sexp (second sexp)))
(if (and (consp sexp) (symbolp (car sexp))
(string-equal 'if* (car sexp)))
(do* ((subs (cons 'elseif (cdr sexp)))
(clauses '())
(condition)
(statements)
(token))
((null subs)
(let ((result
(progn ;;generate the new sexp
(setq clauses (nreverse clauses))
(cond
((and (= 1 (length clauses))
(every
(lambda (clause) (not (null (cdr clause))))
;; clause = (cons condition statements)
clauses)) ;; a when
`(when ,(car (first clauses))
,@(cdr (first clauses))))
((or (= 1 (length clauses))
(< 2 (length clauses))
(not (eq t (car (second clauses))))) ;; a cond
`(cond ,@clauses))
(t ;; a if
`(if ,(car (first clauses))
,(if (= 1 (length (cdr (first clauses))))
(cadr (first clauses))
`(progn ,@(cdr (first clauses))))
,(if (= 1 (length (cdr (second clauses))))
(cadr (second clauses))
`(progn ,@(cdr (second clauses)))))))) ))
(message "sexp=%S\nresult=%S" sexp result)
(if backquoted (list '\` result) result)))
;; read the condition:
(setq token (pop subs))
(cond
((not (symbolp token))
(error "unexpected token %S in %S" token sexp))
((null subs)
(error "unexpected end of sexp in %S" sexp))
((string-equal token 'elseif)
(setq condition (pop subs))
(unless (or (string-equal (car subs) 'then)
(string-equal (car subs) 'thenret))
(error "missing THEN after condition in %S" sexp))
(pop subs))
((string-equal token 'else)
(setq condition t))
(t
(error "unexpected token %S in %S" token sexp)))
;; read the statements:
(do () ((or (null subs)
(and (consp subs) (symbolp (car subs))
(member* (car subs) '(elseif else)
:test (function string-equal)))))
(push (pop subs) statements))
(push (cons condition (nreverse statements)) clauses)
(setq condition nil statements nil))
original-sexp)))
:deeply t :atoms nil)
(unescape-sharp)))
;;;; THE END ;;;;
| 24,817 | Common Lisp | .lisp | 557 | 35.658887 | 118 | 0.512084 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 25211241de5a66be770270386c740daa443f4e62c4cba7e6b4d8a8221cf06919 | 4,694 | [
-1
] |
4,695 | packages.lisp | informatimago_lisp/future/lisp-sexp/packages.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: packages.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; XXX
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-06 <PJB> Extracted from source-form.lisp
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
;;; Not used yet.
;;;; THE END ;;;;
| 1,371 | Common Lisp | .lisp | 35 | 38.114286 | 83 | 0.574213 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a536b9ebca4f23cc316e02e9f2c4d87eccdf41966e58fc9e2c58c2528fb23c4e | 4,695 | [
-1
] |
4,696 | parse-rivest.lisp | informatimago_lisp/future/rivest-sexp/parse-rivest.lisp | ;; Path: news.easynet.es!numbering.news.easynet.net!spool2.bllon.news.easynet.net!easynet-quince!easynet.net!newsfeeds.sol.net!newspump.sol.net!news.glorb.com!newsfeed2.telusplanet.net!newsfeed.telus.net!edtnps84.POSTED!53ab2750!not-for-mail
;; From: Wade Humeniuk <[email protected]>
;; User-Agent: Mozilla Thunderbird 1.0 (Windows/20041206)
;; X-Accept-Language: en-us, en
;; MIME-Version: 1.0
;; Newsgroups: comp.lang.lisp
;; Subject: Re: S-expression grammar?
;; References: <[email protected]> <[email protected]> <[email protected]> <[email protected]>
;; In-Reply-To: <[email protected]>
;; Content-Type: text/plain; charset=ISO-8859-1; format=flowed
;; Content-Transfer-Encoding: 7bit
;; Lines: 69
;; Message-ID: <UyIje.4658$HI.1721@edtnps84>
;; Date: Sat, 21 May 2005 15:35:16 GMT
;; NNTP-Posting-Host: 142.59.106.101
;; X-Trace: edtnps84 1116689716 142.59.106.101 (Sat, 21 May 2005 09:35:16 MDT)
;; NNTP-Posting-Date: Sat, 21 May 2005 09:35:16 MDT
;; Xref: news.easynet.es comp.lang.lisp:87328
;;
;; Stefan Ram wrote:
;;
;; > draft-rivest-sexp-00.txt introduces Base64-atom-literals, like
;; > |YWJj|, which are not part of most Lisp-implementations,
;; > AFAIK, and on the other hand, does not seem to include dotted
;; > pairs.
;; >
;;
;; Speaking of which, here is a possible parser for Rivest's Canonical/Transport
;; sexprs (For LispWorks),
;;
;; CL-USER 8 > (parse-rivest-sexp "(4:icon[12:image/bitmap]9:xxxxxxxxx)")
;; ("icon" (:DISPLAY-ENCODED "image/bitmap" #(120 120 120 120 120 120 120 120 120)))
;; NIL
;;
;; CL-USER 9 > (parse-rivest-sexp "(7:subject(3:ref5:alice6:mother))")
;; ("subject" ("ref" "alice" "mother"))
;; NIL
;;
;; Wade
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "parsergen")
(use-package :parsergen))
(defparser rivest-canonical-sexp-parser
((s-expression sexpr))
((sexpr string) $1)
((sexpr list) $1)
((string display simple-string)
(list :display-encoded $1
(map '(simple-array (unsigned-byte 8) (*)) #'char-int $2)))
((string simple-string) $1)
((display \[ simple-string \]) $2)
((simple-string raw) $1)
((elements sexpr) (list $1))
((elements sexpr elements) (cons $1 $2))
((list \( elements \)) $2))
(defun rivest-canonical-sexp-lexer (stream)
(let ((c (read-char stream nil)))
(cond
((null c) (values nil nil))
((member c '(#\space #\tab #\newline)) (error "No Whitespace
Allowed in Rivest Canonical Form"))
((char= c #\() (values '\( c))
((char= c #\)) (values '\) c))
((char= c #\[) (values '\[ c))
((char= c #\]) (values '\] c))
((digit-char-p c)
(let ((length (digit-char-p c)))
(loop for c = (read-char stream) do
(cond
((digit-char-p c)
(setf length (+ (* 10 length) (digit-char-p c))))
((char= #\: c)
(loop with string = (make-array length
:element-type 'character)
for i from 0 below length
do (setf (aref string i) (read-char stream))
finally (return-from rivest-canonical-sexp-lexer
(values 'raw string))))
(t (error "Invalid Rivest Simple String")))))))))
(defun parse-rivest-sexp (string)
(with-input-from-string (s string)
(rivest-canonical-sexp-parser (lambda () (rivest-canonical-sexp-lexer s)))))
| 3,703 | Common Lisp | .lisp | 85 | 38.458824 | 241 | 0.641374 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 708624d0f8564db3ea27447deb5dd7e6dbdf5775459da5c880ffe0619e00be97 | 4,696 | [
-1
] |
4,697 | reps.lisp | informatimago_lisp/future/rivest-sexp/simple-sexp/reps.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: reps.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines representations for the read.lisp
;;;; simple lisp reader/printer.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2007-10-26 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2007 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
;;;--------------------
;;; Representations
;;;--------------------
;;; Strings:
(defun %make-string (contents) (assert (stringp contents)) contents)
(defun %stringp (object) (stringp object))
(defun %string-length (object) (assert (%stringp object)) (length object))
(defun %string-ref (object i) (assert (%stringp object)) (char object i))
;;; Symbols:
;;; These symbol name contains the package and colons in addition to
;;; the name.
(defstruct sym name)
(defun %make-symbol (name) (make-sym :name name))
(defun %symbolp (object) (typep object 'sym))
(defun %symbol-eql (a b) (string= (sym-name a) (sym-name b)))
(defun %symbol-name (s) (sym-name s))
;;; Integers:
(defun %make-integer (contents)
(assert (stringp contents))
(multiple-value-bind (ok strongp value) (parse-integer-token contents)
(cond
(ok (assert (integerp value)) value)
(strongp (error value))
(t nil))))
(defun %integerp (object) (integerp object))
;;; Floating points:
(defun %make-float (contents)
(assert (stringp contents))
(multiple-value-bind (ok strongp value) (parse-float-token contents)
(cond
(ok (assert (floatp value)) value)
(strongp (error value))
(t nil))))
(defun %floatp (object) (floatp object))
;;; Conses:
(defun %cons (car cdr) (cons car cdr))
(defun %consp (object) (consp object))
(defun %car (cons) (car cons))
(defun %cdr (cons) (cdr cons))
(defun %nil () '())
(defun %null (object) (eq (%nil) object))
(defun %nreverse (list) (nreverse list))
(defun %length (list) (length list))
(defun %nreconc (list tail) (nreconc list tail))
(defmacro %push (object list) `(push ,object ,list))
(defun %list (&rest args)
(do ((sgra (reverse args) (cdr sgra))
(list (%nil) (%cons (car sgra) list)))
((null sgra) list)))
;;; Hashes:
(defstruct hash options data)
(defun %make-hash-table (options data)
"
OPTIONS: an %alist of (%cons key value) options.
DATA: an %alist of (%cons key value) data.
"
(make-hash :options options :data data))
(defun %hash-table-p (object) (typep object 'hash))
(defun %hash-table-options (object)
(assert (%hash-table-p object))
(hash-options object))
(defun %hash-table-data (object)
(assert (%hash-table-p object))
(hash-data object))
;;; Structures:
(defstruct struct type data)
(defun %make-struct (type data) (make-struct :type type :data data))
(defun %structp (object) (typep object 'struct))
(defun %struct-type (object) (assert (%structp object)) (struct-type object))
(defun %struct-data (object) (assert (%structp object)) (struct-data object))
;;; Arrays:
(defun %make-array (dimensions contents)
(if contents
(make-array dimensions :initial-contents contents)
(make-array dimensions)))
(defun %arrayp (object) (arrayp object))
(defun %array-ref (array &rest indices)
(apply (function aref) array indices))
(defun %array-dimensions (array)
(array-dimensions array))
(defun %array-collect-contents (array)
"
RETURN: A %list of the array contents.
"
(labels ((collect (indices dims)
(if (null dims)
(apply (function %array-ref) array indices)
(let ((row (%nil)))
(dotimes (i (first dims) (%nreverse row))
(%push (collect (append indices (%cons i (%nil)))
(%cdr dims)) row))))))
(collect (%nil) (%array-dimensions array))))
;;; Dots:
(defstruct dots contents)
(defun %make-dots (contents) (make-dots :contents contents))
(defun %dotsp (object) (typep object 'dots))
(defun %dots-contents (object) (assert (%dots)))
;;;; THE END ;;;;
| 5,100 | Common Lisp | .lisp | 134 | 35.19403 | 78 | 0.629091 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d78a46c1e20bac449094e24fe9662fede65d945a9786479ca2169ba5f4b51e08 | 4,697 | [
-1
] |
4,698 | read.lisp | informatimago_lisp/future/rivest-sexp/simple-sexp/read.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: sexp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Reads and writes simple S-Expressions.
;;;; This implements a simple parser, subset of the
;;;; standard Common Lisp parser.
;;;;
;;;; We can read and write:
;;;; - integers (expressed in base ten),
;;;; - floating point numbers,
;;;; - strings,
;;;; - symbols,
;;;; - lists,
;;;; - arrays and vectors,
;;;; - structures,
;;;; - hash tables.
;;;;
;;;; We don't implement most of the macro character or dispatching macro
;;;; characters. No comment, no quote, one can use (quote x), nothing fancy.
;;;; Only " for strings, ( for lists and dotted lists, #( for vectors,
;;;; #nA for arrays, #S for structures and hash-tables.
;;;; Symbols may be qualified, but it's up to the user supplied %make-symbol
;;;; routine to handle the packages.
;;;;
;;;; string ::= "\"([^\\\"]|\\\\|\\\)\""
;;;; number ::= "[-+]?[0-9]+(\.[0-9]*)([eE][-+]?[0-9]+)?"
;;;; cardinal ::= [0-9]+
;;;; symbol ::= [[ident]':']ident
;;;; ident ::= constituent+
;;;; char ::= #\\. | #\\space | #\\newline
;;;;
;;;; vector ::= '#(' sexp* ')'
;;;; array ::= '#'cardinal'A(' sexp* ')'
;;;; list ::= '(' [ sexp+ [ '.' sexp ] ] ')'
;;;; hash ::= '#S(' 'HASH-TABLE' pair* ')'
;;;; pair ::= '(' sexp '.' sexp ')'
;;;;
;;;; sexp ::= string | number | symbol | list | array | hash
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2007-10-25 <PJB>
;;;; Complete %stuff (arrays, conses).
;;;; Implement SIMPLE-PRIN1-TO-STRING
;;;; 2007-10-25 <PJB> Created.
;;;;BUGS
;;;;
;;;; Perhaps we should implement River's Sexp format.
;;;;
;;;; Simplify the implementation (use a subset of Common Lisp, to
;;;; be easily translatable into other programming languages).
;;;;
;;;; Implement translators to other programming languages (to be
;;;; able to exchange data between languages).
;;;;
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2007 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(load "repr.lisp")
;;;
;;;--------------------
(defun make-scanner (string)
(let ((i -1))
(lambda (message)
(ecase message
((currchar) (when (< i (length string)) (aref string i)))
((nextchar) (when (< (1+ i) (length string)) (aref string (1+ i))))
((advance) (when (< i (length string)) (incf i))
(when (< i (length string)) (aref string i)))))))
(defun advance (s) (funcall s 'advance))
(defun currchar (s) (funcall s 'currchar))
(defun nextchar (s) (funcall s 'nextchar))
(defun test-scanner ()
(let ((s (make-scanner "(\"a\" b c d)")))
(advance s)
(do ()
((not (currchar s)))
(advance s))))
(define-condition simple-end-of-file (simple-error end-of-file) ())
(define-condition simple-reader-error (simple-error reader-error) ())
(defun reject-eos (object)
(unless object
(error 'simple-end-of-file
:format-control "Reached end of string while reading."))
object)
(defun reject-dots (token)
(when (%dotsp token)
(error 'simple-reader-error
:format-control
"A token consisting only of dots cannot be meaningfully read in."))
token)
(defmacro defparser (name arguments &body body)
"Defines a token parser function, which parses its argument token and returns
three values: a ok flag; a type of value; and a value parsed from the token.
When the ok flag is false, the type indicates whether it's a strong error,
and the value returned is an error message.
A strong error is a lexical error that is not ambiguous. A weak error is
when the token could still be of another lexical category.
In the body of the parser, there are macrolet defined to REJECT or ACCEPT
the token, and to describe the parsed syntax with ALT, ZERO-OR-MORE,
ONE-OR-MORE and OPT-SIGN."
`(defun ,name ,arguments
,@(when (stringp (first body)) (list (pop body)))
,@(loop ; declarations
:while (and (listp (car body)) (eq 'declare (caar body)))
:collect (pop body))
(macrolet ((reject (strongp &rest ctrlstring-and-args)
`(return-from ,',name
(values nil ,strongp
,(when ctrlstring-and-args
`(format nil ,@ctrlstring-and-args)))))
(accept (type token)
`(return-from ,',name (values t ,type ,token)))
(alt (&rest clauses)
`(cond ,@clauses))
(zero-or-more (test &body body)
`(loop :while ,test :do ,@body))
(one-or-more (test &body body)
`(progn
(if ,test (progn ,@body) (reject nil))
(loop :while ,test :do ,@body))))
,@body)))
(defparser parse-integer-token (token)
"integer ::= [sign] digit+ [decimal-point]"
(let ((sign 1)
(mant 0)
(i 0))
(unless (< i (length token)) (reject nil))
(alt ((char= #\- (aref token i)) (incf i) (setf sign -1))
((char= #\+ (aref token i)) (incf i)))
(one-or-more (and (< i (length token)) (digit-char-p (aref token i)))
(setf mant (+ (* 10. mant) (digit-char-p (aref token i)))
i (1+ i)))
(alt ((and (< i (length token)) (char= #\. (aref token i))) (incf i)))
(if (= i (length token))
(accept 'integer (* sign mant))
(reject t "Junk after integer in ~S" token))))
(defparser parse-float-token (token)
"
float ::= [sign] {decimal-digit}+ [decimal-point {decimal-digit}*] exponent
float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ [exponent]
exponent ::= exponent-marker [sign] {digit}+"
(let ((sign 1)
(mant 0)
(esgn 1)
(mexp 0)
(expo 0)
(i 0)
(type 'float)
(fp nil))
(unless (< i (length token)) (reject nil))
(alt ((char= #\- (aref token i)) (incf i) (setf sign -1))
((char= #\+ (aref token i)) (incf i)))
(zero-or-more (and (< i (length token)) (digit-char-p (aref token i)))
(setf mant (+ (* 10. mant) (digit-char-p (aref token i)))
i (1+ i)))
(alt ((and (< i (length token)) (char= #\. (aref token i)))
(setf fp t)
(incf i)
(zero-or-more
(and (< i (length token)) (digit-char-p (aref token i)))
(setf mant (+ (* 10. mant) (digit-char-p (aref token i)))
mexp (1- mexp)
i (1+ i)))))
(when (and (< i (length token))
;; Marker Meaning
;; D or d double-float
;; E or e float (see *read-default-float-format*)
;; F or f single-float
;; L or l long-float
;; S or s short-float
(setf type (cdr (assoc (aref token i)
'((#\d . double-float)
(#\e . float)
(#\f . single-float)
(#\l . long-float)
(#\s . short-float))
:test (function char-equal)))))
(setf fp t)
(incf i)
(unless (< i (length token)) (reject nil))
(alt ((char= #\- (aref token i)) (incf i) (setf esgn -1))
((char= #\+ (aref token i)) (incf i)))
(one-or-more (and (< i (length token)) (digit-char-p (aref token i)))
(setf expo (+ (* 10. expo) (digit-char-p (aref token i)))
i (1+ i))))
(if fp
(if (= i (length token))
(accept type
(* (coerce (* sign mant) type)
(expt 10.0 (+ mexp (* esgn expo)))))
(reject t "Junk after floating point number ~S" token))
(reject nil))))
(defun test-%make-integer ()
(dolist (test '(("123" 123)
("+123" 123)
("-123" -123)
("123." 123)
("+123." 123)
("-123." -123)))
(assert (= (%make-integer (first test)) (second test))
() "(%MAKE-INTEGER ~S) returned ~S instead of ~S"
(first test) (%make-integer (first test)) (second test)))
:success)
(defun test-%make-float ()
(dolist (test '(("123.0" 123.0)
("+123.0" 123.0)
("-123.0" -123.0)
("123.0" 123.0)
("+123.0" 123.0)
("-123.0" -123.0)
("123e0" 123e0)
("+123e0" 123e0)
("-123e0" -123e0)
("123e0" 123e0)
("+123e0" 123e0)
("-123e0" -123e0)
(".123e3" 123e0)
("+.123e3" 123e0)
("-.123e3" -123e0)
(".123e3" 123e0)
("+.123e3" 123e0)
("-.123e3" -123e0)
("0.123e3" 123e0)
("+0.123e3" 123e0)
("-0.123e3" -123e0)
("0.123e3" 123e0)
("+0.123e3" 123e0)
("-0.123e3" -123e0)
(".123e+3" 123e0)
("+.123e+3" 123e0)
("-.123e+3" -123e0)
(".123e+3" 123e0)
("+.123e+3" 123e0)
("-.123e+3" -123e0)
("0.123e+3" 123e0)
("+0.123e+3" 123e0)
("-0.123e+3" -123e0)
("0.123e+3" 123e0)
("+0.123e+3" 123e0)
("-0.123e+3" -123e0)
("1230e-1" 123e0)
("+1230e-1" 123e0)
("-1230e-1" -123e0)
("1230.0e-1" 123e0)
("+1230.0e-1" 123e0)
("-1230.0e-1" -123e0)
("123s0" 123s0)
("+123s0" 123s0)
("-123s0" -123s0)
("123s0" 123s0)
("+123s0" 123s0)
("-123s0" -123s0)
(".123s3" 123s0)
("+.123s3" 123s0)
("-.123s3" -123s0)
(".123s3" 123s0)
("+.123s3" 123s0)
("-.123s3" -123s0)
("0.123s3" 123s0)
("+0.123s3" 123s0)
("-0.123s3" -123s0)
("0.123s3" 123s0)
("+0.123s3" 123s0)
("-0.123s3" -123s0)
(".123s+3" 123s0)
("+.123s+3" 123s0)
("-.123s+3" -123s0)
(".123s+3" 123s0)
("+.123s+3" 123s0)
("-.123s+3" -123s0)
("0.123s+3" 123s0)
("+0.123s+3" 123s0)
("-0.123s+3" -123s0)
("0.123s+3" 123s0)
("+0.123s+3" 123s0)
("-0.123s+3" -123s0)
("1230s-1" 123s0)
("+1230s-1" 123s0)
("-1230s-1" -123s0)
("1230.0s-1" 123s0)
("+1230.0s-1" 123s0)
("-1230.0s-1" -123s0)
("123f0" 123f0)
("+123f0" 123f0)
("-123f0" -123f0)
("123f0" 123f0)
("+123f0" 123f0)
("-123f0" -123f0)
(".123f3" 123f0)
("+.123f3" 123f0)
("-.123f3" -123f0)
(".123f3" 123f0)
("+.123f3" 123f0)
("-.123f3" -123f0)
("0.123f3" 123f0)
("+0.123f3" 123f0)
("-0.123f3" -123f0)
("0.123f3" 123f0)
("+0.123f3" 123f0)
("-0.123f3" -123f0)
(".123f+3" 123f0)
("+.123f+3" 123f0)
("-.123f+3" -123f0)
(".123f+3" 123f0)
("+.123f+3" 123f0)
("-.123f+3" -123f0)
("0.123f+3" 123f0)
("+0.123f+3" 123f0)
("-0.123f+3" -123f0)
("0.123f+3" 123f0)
("+0.123f+3" 123f0)
("-0.123f+3" -123f0)
("1230f-1" 123f0)
("+1230f-1" 123f0)
("-1230f-1" -123f0)
("1230.0f-1" 123f0)
("+1230.0f-1" 123f0)
("-1230.0f-1" -123f0)
("123d0" 123d0)
("+123d0" 123d0)
("-123d0" -123d0)
("123d0" 123d0)
("+123d0" 123d0)
("-123d0" -123d0)
(".123d3" 123d0)
("+.123d3" 123d0)
("-.123d3" -123d0)
(".123d3" 123d0)
("+.123d3" 123d0)
("-.123d3" -123d0)
("0.123d3" 123d0)
("+0.123d3" 123d0)
("-0.123d3" -123d0)
("0.123d3" 123d0)
("+0.123d3" 123d0)
("-0.123d3" -123d0)
(".123d+3" 123d0)
("+.123d+3" 123d0)
("-.123d+3" -123d0)
(".123d+3" 123d0)
("+.123d+3" 123d0)
("-.123d+3" -123d0)
("0.123d+3" 123d0)
("+0.123d+3" 123d0)
("-0.123d+3" -123d0)
("0.123d+3" 123d0)
("+0.123d+3" 123d0)
("-0.123d+3" -123d0)
("1230d-1" 123d0)
("+1230d-1" 123d0)
("-1230d-1" -123d0)
("1230.0d-1" 123d0)
("+1230.0d-1" 123d0)
("-1230.0d-1" -123d0)
("123l0" 123l0)
("+123l0" 123l0)
("-123l0" -123l0)
("123l0" 123l0)
("+123l0" 123l0)
("-123l0" -123l0)
(".123l3" 123l0)
("+.123l3" 123l0)
("-.123l3" -123l0)
(".123l3" 123l0)
("+.123l3" 123l0)
("-.123l3" -123l0)
("0.123l3" 123l0)
("+0.123l3" 123l0)
("-0.123l3" -123l0)
("0.123l3" 123l0)
("+0.123l3" 123l0)
("-0.123l3" -123l0)
(".123l+3" 123l0)
("+.123l+3" 123l0)
("-.123l+3" -123l0)
(".123l+3" 123l0)
("+.123l+3" 123l0)
("-.123l+3" -123l0)
("0.123l+3" 123l0)
("+0.123l+3" 123l0)
("-0.123l+3" -123l0)
("0.123l+3" 123l0)
("+0.123l+3" 123l0)
("-0.123l+3" -123l0)
("1230l-1" 123l0)
("+1230l-1" 123l0)
("-1230l-1" -123l0)
("1230.0l-1" 123l0)
("+1230.0l-1" 123l0)
("-1230.0l-1" -123l0)
))
(assert (string= (format nil "~7,3F" (%make-float (first test)))
(format nil "~7,3F" (second test)))
() "(%MAKE-FLOAT ~S) returned ~S instead of ~S"
(first test) (%make-float (first test)) (second test)))
:success)
(declaim (inline whitespacep terminating-macro-char-p))
(defun whitespacep (ch) (member ch '(#\space #\newline #\tab)))
(defun terminating-macro-char-p (ch) (member ch '(#\( #\))))
(defun skip-spaces (s)
(do ()
((not (and (currchar s) (whitespacep (currchar s)))))
(advance s))
(assert (or (null (currchar s)) (not (whitespacep (currchar s))))))
(defun unescape (token)
;; WARNING: This destroys the contents of TOKEN, which must be mutable.
(let ((dst 0)
(state :normal))
(do ((src 0 (1+ src)))
((>= src (length token))
(unless (eq state :normal)
(error "end-of-file with unfinished token escape."))
(subseq token 0 dst))
(ecase state
((:normal)
(case (aref token src)
((#\\) (setf state :single))
((#\|) (setf state :double))
(otherwise (setf (aref token dst) (aref token src))
(incf dst))))
((:single)
(setf state :normal)
(setf (aref token dst) (aref token src))
(incf dst))
((:double)
(case (aref token src)
((#\|) (setf state :normal))
((#\\) (setf state :double-single))
(otherwise (setf (aref token dst) (aref token src))
(incf dst))))
((:double-single)
(setf state :double)
(setf (aref token dst) (aref token src))
(incf dst))))))
(defun test-unescape ()
(dolist (test '(("" "")
("Hello World" "Hello World")
("xHello World!" "\\xHello \\World\\!")
("\\Hello \"World\"\\" "\\\\Hello \\\"World\\\"\\\\")
("Hello World" "|Hello World|")
("Hello World" "|Hello|| World|")
("Hello World" "|Hello| |World|")
("Hello| |World" "|Hello\\| \\|World|")
("Hello\"\\World" "|Hello\\\"\\\\World|")))
(assert (string= (first test) (unescape (copy-seq (second test))))
()
"(unescape ~S) should give ~S instead of ~S"
(second test) (first test) (unescape (copy-seq (second test)))))
:success)
(defun parse-list (s)
(advance s) ; skip over #\(
(let ((list (%nil)))
(loop
(skip-spaces s)
(when (char= (reject-eos (currchar s)) #\))
(advance s)
(return-from parse-list (%nreverse list)))
(when (and list
(char= (currchar s) #\.)
(or (null (nextchar s))
(whitespacep (nextchar s))
(terminating-macro-char-p (nextchar s))))
(collect-token s)
(let ((last-cdr (parse-object s)))
(if (char= (reject-eos (currchar s)) #\))
(progn
(advance s)
(return-from parse-list (%nreconc list last-cdr)))
(error "There can be only one object after the dot in a dotted-list."))))
(%push (parse-object s) list))))
(defun parse-vector (length s)
(advance s) ; skip over #\(
(if length
(let ((object nil)
(vector (%make-array (list length) nil)))
(skip-spaces s)
(do ((i 0 (1+ i)))
((not (char/= (reject-eos (currchar s)) #\)))
(do ((i i (1+ i)))
((not (< i length)))
(setf (aref vector i) object))
(advance s)
vector)
(setf object (parse-object s))
(when (< i length)
(setf (aref vector i) object))
(skip-spaces s)))
#- (and)
(loop
:with object = nil
:with vector = (%make-array (list length) nil)
:for i :from 0
:do (skip-spaces s)
:while (char/= (reject-eos (currchar s)) #\))
:do (setf object (parse-object s))
:do (when (< i length)
(setf (aref vector i) object))
:finally (progn (loop
:while (< i length)
:do (setf (aref vector i) object))
(advance s)
(return vector)))
(let ((object nil)
(list '()))
(skip-spaces s)
(do ((i 0 (1+ i)))
((not (char/= (reject-eos (currchar s)) #\)))
(advance s)
(%make-array (list (%length list)) (%nreverse list)))
(%push (parse-object s) list)
(skip-spaces s)))
#- (and)
(loop
:with object = nil
:with list = '()
:for i :from 0
:do (skip-spaces s)
:while (char/= (reject-eos (currchar s)) #\))
:do (push (parse-object s) list)
:finally (progn (advance s)
(return (coerce (nreverse list) 'vector))))))
(defun parse-struct-or-hash (s)
(let ((data (parse-list s)))
(if (%symbol-eql (%make-symbol "HASH-TABLE") (%car data))
(let ((cur (%cdr data)))
(do ((cur (%cdr data)
(%cdr (%cdr cur)))
(options (%nil)
(%cons (%cons (%car cur) (%car (%cdr cur))) options)))
((not (and (%symbolp (%car cur))
(char= #\: (aref (%symbol-name (%car cur)) 0))))
(%make-hash-table options cur))))
#- (and)
(loop ; read a hash table
:with cur = (%cdr data)
:while (and (%symbolp (%car cur))
(char= #\: (aref (%symbol-name (%car cur)) 0)))
:nconc (%cons (%car cur) (%car (%cdr cur))) :into options
:do (setf cur (%cdr (%cdr cur)))
:finally (return))
(%make-struct (%car data) (%cdr data)))))
;; (let ((h (make-hash-table :test (function equal))))
;; (setf (gethash "One" h) 1
;; (gethash "Two" h) 2
;; (gethash "Three" h) 3)
;; h)
;;
(defun parse-array (dimensions s)
(let ((initial-contents (parse-object s)))
(labels ((collect-dimensions (n contents dimensions)
(if (zerop n)
(nreverse dimensions)
(collect-dimensions (1- n) (first contents)
(cons (length contents) dimensions)))))
;; TODO: we rely on make-array to raise some errors that it may not raise...
(%make-array (collect-dimensions dimensions initial-contents '())
initial-contents))))
(declaim (inline make-buffer))
(defun make-buffer ()
(make-array 0 :adjustable t :fill-pointer 0 :element-type 'character))
(defun collect-token (s)
(case (currchar s)
((#\") ; a string; this should move to macro char...
(let ((string (make-buffer))
(state :normal))
(advance s)
(do ()
((not (currchar s))
(error 'simple-end-of-file
:format-control "Reached end-of-file while reading a string."))
(ecase state
((:normal)
(case (currchar s)
((#\") (advance s)
(return-from collect-token (%make-string string)))
((#\\) (setf state :single))
(otherwise (vector-push-extend (currchar s) string))))
((:single)
(vector-push-extend (currchar s) string)
(setf state :normal)))
(advance s))
#-(and)
(loop
:with state = :normal
:do (advance s)
:while (currchar s)
:do (ecase state
((:normal)
(case (currchar s)
((#\") (advance s)
(return-from collect-token (%make-string string)))
((#\\) (setf state :single))
(otherwise (vector-push-extend (currchar s) string))))
((:single)
(vector-push-extend (currchar s) string)
(setf state :normal)))
:finally
(error 'simple-end-of-file
:format-control "Reached end-of-file while reading a string."))))
(otherwise
(let ((escapedp nil)
(token (make-buffer))
(state :normal))
(do ()
((not (and (currchar s)
(not (or (whitespacep (currchar s))
(terminating-macro-char-p (currchar s))))))
(unless (eq state :normal)
(error "end-of-file with unfinished token escape."))
(cond
(escapedp
(%make-symbol token))
((every (lambda (ch) (char= #\. ch)) token)
(%make-dots token))
((%make-float token))
((%make-integer token))
(t
(%make-symbol token))))
(ecase state
((:normal)
(case (currchar s)
((#\\) (setf state :single escapedp t))
((#\|) (setf state :double escapedp t))
(otherwise (vector-push-extend (currchar s) token))))
((:single)
(setf state :normal)
(vector-push-extend (currchar s) token))
((:double)
(case (currchar s)
((#\|) (setf state :normal))
((#\\) (setf state :double-single))
(otherwise (vector-push-extend (currchar s) token))))
((:double-single)
(setf state :double)
(vector-push-extend (currchar s) token)))
(advance s)))
#- (and)
(loop
:with escapedp = nil
:with token = (make-buffer)
:with state = :normal
:while (and (currchar s)
(not (or (whitespacep (currchar s))
(terminating-macro-char-p (currchar s)))))
:do (progn
(ecase state
((:normal)
(case (currchar s)
((#\\) (setf state :single escapedp t))
((#\|) (setf state :double escapedp t))
(otherwise (vector-push-extend (currchar s) token))))
((:single)
(setf state :normal)
(vector-push-extend (currchar s) token))
((:double)
(case (currchar s)
((#\|) (setf state :normal))
((#\\) (setf state :double-single))
(otherwise (vector-push-extend (currchar s) token))))
((:double-single)
(setf state :double)
(vector-push-extend (currchar s) token)))
(advance s))
:finally (progn
(unless (eq state :normal)
(error "end-of-file with unfinished token escape."))
(return
(cond
(escapedp
(%make-symbol token))
((every (lambda (ch) (char= #\. ch)) token)
(%make-dots token))
((%make-float token))
((%make-integer token))
(t
(%make-symbol token)))))))))
(defun scan-cardinal (s)
(let ((token (make-buffer)))
(do ()
((not (digit-char-p (currchar s)))
(%make-integer token))
(vector-push-extend (currchar s) token)
(advance s)))
#- (and)
(loop
:with token = (make-buffer)
:while (digit-char-p (currchar s))
:do (vector-push-extend (currchar s) token) (advance s)
:finally (return (%make-integer token))))
(defun parse-object (s)
(skip-spaces s)
(case (reject-eos (currchar s))
((#\()
(parse-list s))
((#\#)
(advance s)
(case (reject-eos (currchar s))
((#\() (parse-vector nil s))
((#\A)
(error "Missing a dimensions argument between # and A"))
((#\S) (advance s) (parse-struct-or-hash s))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(let ((arg (scan-cardinal s)))
(case (reject-eos (currchar s))
((#\() (parse-vector arg s))
((#\A) (advance s) (parse-array arg s))
((#\S)
(error "No number allowed between # and S"))
((#\@ #\: #\,)
(error "This simple reader doesn't implement multiple argument or flags for dispatching reader macros."))
(otherwise
(error "This simple reader doesn't implement dispatching reader macros other than #(, #A and #S. Rejecting: #~A" (currchar s))))))
((#\@ #\: #\,)
(error "This simple reader doesn't implement multiple argument or flags for dispatching reader macros."))))
(otherwise (reject-dots (collect-token s)))))
(defun simple-read-from-string (string)
(let ((s (make-scanner string)))
(advance s)
(parse-object s)))
(defun simple-prin1-to-string (object)
"
OBJECT: is one of the objects made by the various %MAKE- functions.
"
(with-output-to-string (out)
(cond
((%symbolp object)
(princ (%symbol-name object) out))
((%stringp object)
(princ "\"" out)
(do ((i 0 (1+ i)))
((>= i (%string-length object)))
(let ((ch (%string-ref object i)))
(when (member ch '(#\\ #\"))
(princ "\\" out))
(princ ch out)))
#- (and)
(loop
:for ch :in object
:do (when (member ch '(#\\ #\"))
(princ "\\" out))
:do (princ ch out))
(princ "\"" out))
((%integerp object) ; TODO: We'd need an accessor for the integer value
(princ object out))
((%floatp object) ; TODO: We'd need an accessor for the float value (eg decode-float).
(princ object out))
((%consp object)
(princ "(" out)
(do ((cur object (%cdr cur))
(sep "" " "))
((not (%consp cur))
(unless (%null cur)
(princ " . " out)
(princ (simple-prin1-to-string cur) out)))
(princ sep out)
(princ (simple-prin1-to-string (%car cur)) out))
(princ ")" out))
((%hash-table-p object)
(princ "#S(HASH-TABLE" out)
(dolist (item (%hash-table-options object))
(princ " " out)
(princ (simple-prin1-to-string (%car item)) out)
(princ " " out)
(princ (simple-prin1-to-string (%cdr item)) out))
(dolist (pair (%hash-table-data object))
(princ " (" out)
(princ (simple-prin1-to-string (%car pair)) out)
(princ " . " out)
(princ (simple-prin1-to-string (%cdr pair)) out)
(princ ")" out))
(princ ")" out))
((%structp object)
(princ "#S(" out)
(princ (simple-prin1-to-string (%struct-type object)) out)
(dolist (item (%struct-data object))
(princ " " out)
(princ (simple-prin1-to-string item) out))
(princ ")" out))
((%arrayp object)
(let ((dims (%array-dimensions object))
(contents (%array-collect-contents object)))
(if (= 1 (%length dims))
;; a vector
(progn
(princ "#" out)
(princ (simple-prin1-to-string contents) out))
;; a multi-D array
(progn
(princ "#" out) (princ (%length dims) out) (princ "A" out)
(princ (simple-prin1-to-string contents) out)))))
(t
(cond
((subtypep (class-of (class-of object)) 'structure-class)
(princ "#S(" out)
(princ (symbol-name (type-of object)) out)
(dolist (slot (clos::class-slots (find-class 'dots)))
(princ " :" out)
(princ (symbol-name (clos:slot-definition-name slot)) out)
(princ " " out)
(princ (simple-prin1-to-string
(slot-value object (clos:slot-definition-name slot))) out))
(princ ")" out))
(t
(error "Cannot print objects of type ~S like: ~S"
(type-of object) object)))))))
;; #- (and)
;; (untrace make-scanner advance currchar nextchar reject-eos reject-dots
;; whitespacep terminating-macro-char-p skip-spaces unescape
;; test-unescape parse-list parse-vector parse-struct-or-hash parse-array
;; collect-token parse-object simple-read-from-string)
;;
;; (print (simple-read-from-string "(\"a\" (a b c) b c-c . d)"))
;; (print (simple-read-from-string "(\"a\" #S(dots :contents \"...\") #(a b c) b c-c . (d 123 123.0 123l0))"))
;; (print (simple-read-from-string "(#1A(1 2 3) #0Afoo \"a\" #S(dots :contents \"...\") #S(HASH-TABLE :TEST EXT:FASTHASH-EQUAL (\"Three\" . 3) (\"Two\" . 2) (\"One\" . 1)) #(a b c) b c-c . (d 123 123.0 123l0))"))
(defun test-read-print ()
(dolist
(test
'((#1="(\"a\" (a b c) b c-c . d)" #1#)
("(\"a\" #S(dots :contents \"...\") #(a b c) b c-c . (d 123 123.0 123l0))"
"(\"a\" #S(dots :contents \"...\") #(a b c) b c-c d 123 123.0 123.0L0)")
("(#1A(1 2 3) #0Afoo \"a\" #S(dots :contents \"...\") #S(HASH-TABLE :TEST EXT:FASTHASH-EQUAL (\"Three\" . 3) (\"Two\" . 2) (\"One\" . 1)) #(a b c) b c-c . (d 123 123.0 123l0))"
"(#(1 2 3) #0Afoo \"a\" #S(dots :contents \"...\") #S(HASH-TABLE :TEST EXT:FASTHASH-EQUAL (\"Three\" . 3) (\"Two\" . 2) (\"One\" . 1)) #(a b c) b c-c d 123 123.0 123.0L0)")))
(assert (string= (simple-prin1-to-string
(simple-read-from-string (first test)))
(second test))
()
"Test failed:~% ~S~% ~S"
(simple-prin1-to-string (simple-read-from-string (first test)))
(second test)))
:success)
;;;; THE END ;;;;
| 34,480 | Common Lisp | .lisp | 855 | 28.364912 | 213 | 0.455034 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e5fb2a148d65a7ad882c04b7f5ea8e05a9638c88f3b6a5b1ec234c92e9fa9686 | 4,698 | [
-1
] |
4,699 | cl-stream.lisp | informatimago_lisp/future/vfs/cl-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: cl-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the cl-stream operations.
;;;; CL-STREAMs are streams implemented as native CL streams.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass cl-stream (stream)
((stream :accessor cl-stream-stream
:initarg :cl-stream)))
(defun cl-stream (stream) (make-instance 'cl-stream :cl-stream stream))
(defparameter *debug-io* (cl-stream cl:*debug-io*))
(defparameter *error-output* (cl-stream cl:*error-output*))
(defparameter *trace-output* (cl-stream cl:*trace-output*))
(defparameter *standard-output* (cl-stream cl:*standard-output*))
(defparameter *standard-input* (cl-stream cl:*standard-input*))
(defparameter *terminal-io* (cl-stream cl:*terminal-io*))
;;;; THE END ;;;;
| 2,238 | Common Lisp | .lisp | 50 | 43.3 | 78 | 0.629358 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 8ebd1fd22eab0eba16dcdfaeed97b9bb48058d7bff612232f5508d674f35723e | 4,699 | [
-1
] |
4,700 | general.lisp | informatimago_lisp/future/vfs/general.lisp |
;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: general.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the general file and stream functions and macro.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defun y-or-n-p (&optional format-string &rest args)
(when format-string
(fresh-line *query-io*)
(apply (function format) *query-io* format-string args)
(write-string " (y/n) " *query-io*))
(loop
(let ((line (string-left-trim " " (read-line *query-io*))))
(when (plusp (length line))
(let ((first-char (char-upcase (char line 0))))
(when (char-equal first-char #\n) (return nil))
(when (char-equal first-char #\y) (return t))))
(write-string "Please answer with 'y' or 'n': " *query-io*))))
(defun yes-or-no-p (&optional format-string &rest args)
(when format-string
(fresh-line *query-io*)
(apply (function format) *query-io* format-string args)
(write-string " (yes/no) " *query-io*))
(loop
(clear-input *query-io*)
(let ((line (string-trim " " (read-line *query-io*))))
(when (string-equal line "NO") (return nil))
(when (string-equal line "YES") (return t)))
(write-string "Please answer with 'yes' or 'no': " *query-io*)))
;; Macros are taken from clisp sources, and adapted.
(defmacro with-open-file ((stream &rest options) &body body)
(multiple-value-bind (body-rest declarations) (parse-body :locally body)
`(let ((,stream (open ,@options)))
(declare (read-only ,stream) ,@declarations)
(unwind-protect
(multiple-value-prog1 (progn ,@body-rest)
(when ,stream (close ,stream)))
(when ,stream (close ,stream :abort t))))))
(defmacro with-open-stream ((var stream) &body body)
(multiple-value-bind (body-rest declarations) (parse-body :locally body)
`(let ((,var ,stream))
(declare (read-only ,var) ,@declarations)
(unwind-protect
(multiple-value-prog1 (progn ,@body-rest) (close ,var))
(close ,var :abort t)))))
(defmacro with-input-from-string ((var string &key (index nil sindex)
(start '0 sstart) (end 'nil send))
&body body)
(multiple-value-bind (body-rest declarations) (parse-body :loally body)
`(let ((,var (make-string-input-stream
,string
,@(if (or sstart send)
`(,start ,@(if send `(,end) '()))
'()))))
(declare (read-only ,var) ,@declarations)
(unwind-protect
(progn ,@body-rest)
,@(when sindex `((setf ,index (%string-stream-index ,var))))
(close ,var)))))
(defmacro with-output-to-string ((var &optional (string nil)
&key (element-type ''character))
&body body)
(multiple-value-bind (body-rest declarations) (parse-body :locally body)
(if string
(let ((ignored-var (gensym)))
`(let ((,var (make-instance 'string-output-stream :string ,string))
(,ignored-var ,element-type))
(declare (read-only ,var) (ignore ,ignored-var) ,@declarations)
(unwind-protect
(progn ,@body-rest)
(close ,var))))
`(let ((,var (make-string-output-stream :element-type ,element-type)))
(declare (read-only ,var) ,@declarations)
(unwind-protect
(progn ,@body-rest (get-output-stream-string ,var))
(close ,var))))))
;;;; THE END ;;;;
| 5,009 | Common Lisp | .lisp | 109 | 38.853211 | 78 | 0.576931 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d6055452b3bb637825f162b572e43139a57325051f9d9526a7bf3be8ae78263c | 4,700 | [
-1
] |
4,701 | echo-stream.lisp | informatimago_lisp/future/vfs/echo-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: echo-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the echo stream operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass echo-stream (stream)
((input-stream :accessor %echo-stream-input-stream
:initarg :input-stream
:initform nil)
(output-stream :accessor %echo-stream-output-stream
:initarg :output-stream
:initform nil)))
(defun make-echo-stream (input-stream output-stream)
(unless (input-stream-p stream)
(error (make-condition
'simple-type-error
:datum input-stream
:expected-type 'stream
:format-control "Stream is not an input stream")))
(unless (output-stream-p stream)
(error (make-condition
'simple-type-error
:datum output-stream
:expected-type 'stream
:format-control "Stream is not an output stream")))
(make-instance 'echo-stream
:input-stream input-stream
:output-stream output-stream))
(define-forward echo-stream-input-stream (echo-stream)
(declare (stream-argument echo-stream)
(check-stream-type echo-stream)))
(define-forward echo-stream-output-stream (echo-stream)
(declare (stream-argument echo-stream)
(check-stream-type echo-stream)))
(define-stream-methods echo-stream
(read-byte
(let ((byte (read-byte (%echo-stream-input-stream stream) nil stream)))
(if (eq byte stream)
(eof-error stream eof-error-p eof-value)
(progn
(write-byte byte (%echo-stream-output-stream stream))
byte))))
(read-char
(let ((char (read-char (%echo-stream-input-stream stream) nil stream)))
(if (eq char stream)
(eof-error stream eof-error-p eof-value)
(progn
(write-char char (%echo-stream-output-stream stream))
char))))
(read-char-no-hang)
(peek-char)
(unread-char)
(read-line)
(read-sequence)
(terpri)
(fresh-line)
(write-byte (write-byte byte (%echo-stream-output-stream stream)))
(write-char (write-char character (%echo-stream-output-stream stream)))
(write-string)
(write-line)
(write-sequence)
(listen)
(clear-input)
(clear-output)
(force-output)
(finish-output)
(file-length)
(file-position)
(file-string-length)
(stream-external-format)
(close))
| 3,840 | Common Lisp | .lisp | 104 | 32.192308 | 78 | 0.624832 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 60f4782c1dce5bd191f1a659728732caaf4207f755c17d170171ba51a0437354 | 4,701 | [
-1
] |
4,702 | synonym-stream.lisp | informatimago_lisp/future/vfs/synonym-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: synonym-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the synonyms stream operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass synonym-stream (stream)
((symbol :accessor %synonym-stream-symbol
:initarg :symbol)))
(defun make-synonym-stream (symbol)
(check-type symbol symbol)
(make-instance 'synonym-stream :symbol symbol))
(define-forward synonym-stream-symbol (synonym-stream)
(declare (stream-argument synonym-stream)
(check-stream-type synonym-stream)))
(define-stream-methods synonym-stream
(synonym-stream-symbol (%synonym-stream-symbol synonym-stream))
(read-byte (read-byte (symbol-value (%synonym-stream-symbol stream))
eof-error-p eof-value))
(write-byte (write-byte (symbol-value (%synonym-stream-symbol stream))))
(read-char (read-char (symbol-value (%synonym-stream-symbol stream))
eof-error-p eof-value))
(write-char (write-char (symbol-value (%synonym-stream-symbol stream)))))
;;;; THE END ;;;;
| 2,516 | Common Lisp | .lisp | 56 | 41.964286 | 78 | 0.632095 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c4aff63131d0a525e4e1b7df5b49e34ede138f4bbe198bf2b67f22875d47e727 | 4,702 | [
-1
] |
4,703 | utility.lisp | informatimago_lisp/future/vfs/utility.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: utility.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines a few utilities.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-15 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defun proper-list-p (object)
(labels ((proper (current slow)
(cond ((null current) t)
((atom current) nil)
((null (cdr current)) t)
((atom (cdr current)) nil)
((eq current slow) nil)
(t (proper (cddr current) (cdr slow))))))
(proper object (cons nil object))))
(defun test-proper-list-p ()
(assert
(every
(function identity)
(mapcar (lambda (test) (eq (first test) (proper-list-p (second test))))
'((nil x)
(t ())
(t (a))
(t (a b))
(t (a b c))
(t (a b c d))
(nil (a . x))
(nil (a b . x))
(nil (a b c . x))
(nil (a b c d . x))
(nil #1=(a . #1#))
(nil #2=(a b . #2#))
(nil #3=(a b c . #3#))
(nil #4=(a b c d . #4#))
(nil (1 . #1#))
(nil (1 2 . #1#))
(nil (1 2 3 . #1#))
(nil (1 2 3 4 . #1#))
(nil (1 . #2#))
(nil (1 2 . #2#))
(nil (1 2 3 . #2#))
(nil (1 2 3 4 . #2#))
(nil (1 . #3#))
(nil (1 2 . #3#))
(nil (1 2 3 . #3#))
(nil (1 2 3 4 . #3#))
(nil (1 . #4#))
(nil (1 2 . #4#))
(nil (1 2 3 . #4#))
(nil (1 2 3 4 . #4#)))))))
(defun unsplit-string (string-list &optional (separator " "))
"
DO: The inverse than split-string.
If no separator is provided then a simple space is used.
SEPARATOR: (OR NULL STRINGP CHARACTERP)
"
(check-type separator (or string character symbol) "a string designator.")
(if string-list
(cl:with-output-to-string (cl:*standard-output*)
(cl:princ (pop string-list))
(dolist (item string-list)
(cl:princ separator) (cl:princ item)))
""))
(defun assert-type (datum expected-type)
"
DO: Signal a TYPE-ERROR if DATUM is not of the EXPECTED-TYPE.
NOTICE: CHECK-TYPE signals a PROGRAM-ERROR.
"
(or (typep datum expected-type)
(error (make-condition 'type-error
:datum datum :expected-type expected-type))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; regular expressions
;;;
(defun re-compile (re &key extended)
#+clisp
(regexp:regexp-compile re :extended extended)
#+(and (not clisp) cl-ppcre)
(cl-ppcre:create-scanner re :extended-mode extended)
#-(or clisp cl-ppcre)
(error "Please implement RE-COMPILE"))
(defun re-exec (re string &key (start 0) (end nil))
#+clisp
(mapcar (lambda (match)
(list (regexp:match-start match)
(regexp:match-end match)
match))
(multiple-value-list (regexp:regexp-exec re string :start start :end (or end (length string)))))
#+(and (not clisp) cl-ppcre)
(multiple-value-bind (start end starts ends)
(cl-ppcre:scan re string :start start :end (or end (length string)))
(and start end
(values-list (cons (list start end)
(map 'list (lambda (s e)
(if (or s e)
(list s e)
nil))
starts ends)))))
#-(or clisp cl-ppcre)
(error "Please implement RE-EXEC"))
(defun re-match-string (string match)
#+clisp
(regexp:match-string string (third match))
#+(and (not clisp) cl-ppcre)
(subseq string (first match) (second match))
#-(or clisp cl-ppcre)
(error "Please implement RE-MATCH-STRING"))
(defun re-match (regexp string)
(re-exec (re-compile regexp :extended t) string))
(defun re-quote (re &key extended)
(assert extended (extended) "re-quote is not implemented yet for non-extended regexps.")
(cl:with-output-to-string (out)
(loop
:for ch :across re
:do (cond
((alphanumericp ch) (princ ch out))
(t (princ "\\" out) (princ ch out))))))
;;;; THE END ;;;;
| 5,791 | Common Lisp | .lisp | 150 | 30.78 | 106 | 0.515394 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7ec1cbf24aaf0100b0d491a0ee9c0c23187deb518e8a2e5cab6fc9e6a6d8224f | 4,703 | [
-1
] |
4,704 | files.lisp | informatimago_lisp/future/vfs/files.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: files.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; THis file defines the files operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-15 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 20. Files
;;; http://www.lispworks.com/documentation/HyperSpec/Body/20_.htm
(defun collapse-sequences-of-wild-inferiors (list)
(if (search '(:wild-inferiors :wild-inferiors) list)
(labels ((collapse (list)
(cond ((null list) list)
((and (eq :wild-inferiors (first list))
(eq :wild-inferiors (second list)))
(collapse (rest list)))
(t (cons (first list) (collapse (rest list)))))))
(collapse list))
list))
(defun collect (current dpath fspath)
(cond
((null dpath)
(if (pathname-name fspath)
(let ((entries
(select-entries
current
(lambda (item)
(and (typep item 'fs-file)
(match-item-p (name item) (pathname-name fspath) t)
(match-item-p (type item) (pathname-type fspath) t))))))
(if (pathname-version fspath)
(mapcan (lambda (item)
(select-versions
item
(lambda (version)
(match-item-p (version version)
(pathname-version fspath) nil))))
entries)
entries))
(list current)))
((eq :wild-inferiors (car dpath))
(nconc (mapcan (lambda (item) (collect item dpath fspath))
(select-entries current (constantly t)))
(mapcan (lambda (item) (collect item (rest dpath) fspath))
(select-entries current (constantly t)))))
(t
(mapcan
(lambda (item) (collect item (rest dpath) fspath))
(select-entries
current
(lambda (item) (and (typep item 'fs-directory)
(match-item-p (name item) (car dpath) t))))))))
(defun directory (pathspec &key)
(let* ((fspath (resolve-pathspec pathspec))
(fs (if (pathname-host fspath)
(file-system-named (pathname-host fspath))
*default-file-system*)))
(if fs
(let ((d (cdr (pathname-directory fspath))))
(mapcar (function pathname)
(collect fs (collapse-sequences-of-wild-inferiors d) fspath)))
(error "Invalid host ~S" (pathname-host fspath)))))
(defun ensure-directories-exist (pathspec &key verbose)
(declare (ignore verbose))
(let* ((fspath (resolve-pathspec pathspec))
(fs (if (pathname-host fspath)
(file-system-named (pathname-host fspath))
*default-file-system*))
(dir (if (pathname-name fspath)
(pathname-directory fspath)
(butlast (pathname-directory fspath)))))
(if fs
(values pathspec (create-directories-at-path fs (cdr dir)))
(error "There's no file system named ~S" (pathname-host fspath)))))
(defun truename (filespec)
"
RETURN: The truename of the filespec.
URL: http://www.lispworks.com/documentation/HyperSpec/Body/f_tn.htm
COMMON-LISP: truename tries to find the file indicated by filespec and
returns its truename. If the filespec designator is an
open stream, its associated file is used. If filespec is
a stream, truename can be used whether the stream is open
or closed. It is permissible for truename to return more
specific information after the stream is closed than when
the stream was open. If filespec is a pathname it
represents the name used to open the file. This may be,
but is not required to be, the actual name of the file.
"
(let ((filespec (resolve-pathspec filespec)))
(if (wild-pathname-p filespec)
(error (make-condition 'simple-file-error
:pathname filespec
:format-control "~A: Filespec ~S is a wild pathname. "
:format-arguments (list 'truename filespec)))
(let ((entry (file-entry filespec)))
(if entry
(pathname entry)
(error (make-condition 'simple-file-error
:pathname filespec
:format-control "~A: File ~S does not exist. "
:format-arguments (list 'truename filespec))))))))
(defun probe-file (pathspec)
"
RETURN: the truename of the file or NIL.
URL: http://www.lispworks.com/documentation/HyperSpec/Body/f_probe_.htm
COMMON-LISP: probe-file tests whether a file exists.
probe-file returns false if there is no file named
pathspec, and otherwise returns the truename of
pathspec.
If the pathspec designator is an open stream, then
probe-file produces the truename of its associated
file. If pathspec is a stream, whether open or closed, it
is coerced to a pathname as if by the function pathname.
"
(values (ignore-errors (truename pathspec))))
(defun file-author (path) (author (file-entry (truename path))))
(defun file-write-date (path) (write-date (file-entry (truename path))))
(defun file-element-type (path) (element-type (file-entry (truename path))))
(defgeneric rename-entry (self newpath))
(defmethod rename-entry ((self fs-file) newpath)
;; rename the whole file
(when (ignore-errors (probe-file newpath))
(delete-file newpath))
(delete-entry self)
(setf (name self) (pathname-name newpath)
(type self) (pathname-type newpath))
(add-entry newpath self)
self)
(defmethod rename-entry ((self file-contents) newpath)
;; rename the version
(let ((file (if (ignore-errors (probe-file newpath))
(file-at-path newpath)
(create-file-at-path newpath :create-version-p nil))))
(remove-version (file self) (version self))
(setf (version self) (if (newest file)
(max (version self) (1+ (version (newest file))))
(version self))
(file self) file
(gethash (version self) (versions file)) self)
self))
(defgeneric delete-entry (self))
(defmethod delete-entry ((self fs-file))
;; delete the whole file
(remove-entry-named (parent self) (pathname-entry-name self)))
(defgeneric remove-version (self version))
(defmethod remove-version ((self fs-file) version)
(remhash version (versions self))
(when (= version (version (newest self)))
(let ((maxk -1) (maxv))
(maphash (lambda (k v) (when (< maxk k) (setf maxk k maxv v))) (versions self))
(if maxv
(setf (newest self) maxv)
;; otherwise, we've deleted the last version, let's delete the file:
(delete-entry self)))))
(defmethod delete-entry ((self file-contents))
;; delete the version ( careful with (newest (file self)) ).
(remove-version (file self) (version self)))
(defun rename-file (filespec new-name)
(let* ((defaulted (merge-pathnames new-name filespec))
(old-truename (truename filespec))
(new-truename (resolve-pathspec defaulted)))
(print (list defaulted old-truename new-truename))
(when (wild-pathname-p defaulted)
(error (make-condition
'simple-file-error
:pathname defaulted
:format-control "~A: source path ~A contains wildcards"
:format-arguments (list 'rename-file defaulted))))
(when (wild-pathname-p new-truename)
(error (make-condition
'simple-file-error
:pathname new-truename
:format-control "~A: target path ~A contains wildcards"
:format-arguments (list 'rename-file new-truename))))
(let* ((newpath (make-pathname :version nil :defaults new-truename))
(newdir (directory-entry newpath)))
(unless newdir
(error (make-condition
'simple-file-error
:pathname newpath
:format-control "~A: target directory ~A doesn't exist"
:format-arguments (list 'rename-file newpath))))
(rename-entry (file (file-entry old-truename)) newpath))
(values defaulted old-truename new-truename)))
(defun delete-file (filespec)
(delete-entry (file (file-entry (truename filespec))))
t)
(defun delete-directory (pathspec)
(let ((dir (directory-entry pathspec)))
(when dir
(when (plusp (hash-table-count (entries dir)))
(error (make-condition
'simple-file-error
:pathname pathspec
:format-control "~A: directory ~A is not empty"
:format-arguments (list 'delete-directory pathspec))))
(delete-entry dir)))
t)
;;;; THE END ;;;;
| 10,551 | Common Lisp | .lisp | 231 | 36.467532 | 87 | 0.587681 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c1fc8199042185f702237a503c17dbad7dba5b2bf711f2014b08651a343b4a99 | 4,704 | [
-1
] |
4,705 | virtual-fs-test.lisp | informatimago_lisp/future/vfs/virtual-fs-test.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(print
(mapcar (lambda (path) (cons path (parse-logical-pathname path)))
(list ""
"HOST:;"
"HOST:;*;"
"HOST:;**;"
"HOST:;DIR;"
"HOST:;DIR1;DIR2;DIR3;"
"HOST:;DIR1;*;DIR3;"
"HOST:;DIR1;**;DIR3;"
"HOST:"
"HOST:*;"
"HOST:**;"
"HOST:DIR;"
"HOST:DIR1;DIR2;DIR3;"
"HOST:DIR1;*;DIR3;"
"HOST:DIR1;**;DIR3;"
"HOST:;NAME"
"HOST:;*;NAME"
"HOST:;**;NAME"
"HOST:;DIR;NAME"
"HOST:;DIR1;DIR2;DIR3;NAME"
"HOST:;DIR1;*;DIR3;NAME"
"HOST:;DIR1;**;DIR3;NAME"
"HOST:"
"HOST:*;NAME"
"HOST:**;NAME"
"HOST:DIR;NAME"
"HOST:DIR1;DIR2;DIR3;NAME"
"HOST:DIR1;*;DIR3;NAME"
"HOST:DIR1;**;DIR3;NAME"
"HOST:;*"
"HOST:;*;*"
"HOST:;**;*"
"HOST:;DIR;*"
"HOST:;DIR1;DIR2;DIR3;*"
"HOST:;DIR1;*;DIR3;*"
"HOST:;DIR1;**;DIR3;*"
"HOST:"
"HOST:*;*"
"HOST:**;*"
"HOST:DIR;*"
"HOST:DIR1;DIR2;DIR3;*"
"HOST:DIR1;*;DIR3;*"
"HOST:DIR1;**;DIR3;*"
"HOST:;.TYPE"
"HOST:;*;.TYPE"
"HOST:;**;.TYPE"
"HOST:;DIR;.TYPE"
"HOST:;DIR1;DIR2;DIR3;.TYPE"
"HOST:;DIR1;*;DIR3;.TYPE"
"HOST:;DIR1;**;DIR3;.TYPE"
"HOST:"
"HOST:*;.TYPE"
"HOST:**;.TYPE"
"HOST:DIR;.TYPE"
"HOST:DIR1;DIR2;DIR3;.TYPE"
"HOST:DIR1;*;DIR3;.TYPE"
"HOST:DIR1;**;DIR3;.TYPE"
"HOST:;NAME.TYPE"
"HOST:;*;NAME.TYPE"
"HOST:;**;NAME.TYPE"
"HOST:;DIR;NAME.TYPE"
"HOST:;DIR1;DIR2;DIR3;NAME.TYPE"
"HOST:;DIR1;*;DIR3;NAME.TYPE"
"HOST:;DIR1;**;DIR3;NAME.TYPE"
"HOST:"
"HOST:*;NAME.TYPE"
"HOST:**;NAME.TYPE"
"HOST:DIR;NAME.TYPE"
"HOST:DIR1;DIR2;DIR3;NAME.TYPE"
"HOST:DIR1;*;DIR3;NAME.TYPE"
"HOST:DIR1;**;DIR3;NAME.TYPE"
"HOST:;*.TYPE"
"HOST:;*;*.TYPE"
"HOST:;**;*.TYPE"
"HOST:;DIR;*.TYPE"
"HOST:;DIR1;DIR2;DIR3;*.TYPE"
"HOST:;DIR1;*;DIR3;*.TYPE"
"HOST:;DIR1;**;DIR3;*.TYPE"
"HOST:"
"HOST:*;*.TYPE"
"HOST:**;*.TYPE"
"HOST:DIR;*.TYPE"
"HOST:DIR1;DIR2;DIR3;*.TYPE"
"HOST:DIR1;*;DIR3;*.TYPE"
"HOST:DIR1;**;DIR3;*.TYPE"
"HOST:;.TYPE.123"
"HOST:;*;.TYPE.123"
"HOST:;**;.TYPE.123"
"HOST:;DIR;.TYPE.123"
"HOST:;DIR1;DIR2;DIR3;.TYPE.123"
"HOST:;DIR1;*;DIR3;.TYPE.123"
"HOST:;DIR1;**;DIR3;.TYPE.123"
"HOST:"
"HOST:*;.TYPE.123"
"HOST:**;.TYPE.123"
"HOST:DIR;.TYPE.123"
"HOST:DIR1;DIR2;DIR3;.TYPE.123"
"HOST:DIR1;*;DIR3;.TYPE.123"
"HOST:DIR1;**;DIR3;.TYPE.123"
"HOST:;NAME.TYPE.123"
"HOST:;*;NAME.TYPE.123"
"HOST:;**;NAME.TYPE.123"
"HOST:;DIR;NAME.TYPE.123"
"HOST:;DIR1;DIR2;DIR3;NAME.TYPE.123"
"HOST:;DIR1;*;DIR3;NAME.TYPE.123"
"HOST:;DIR1;**;DIR3;NAME.TYPE.123"
"HOST:"
"HOST:*;NAME.TYPE.123"
"HOST:**;NAME.TYPE.123"
"HOST:DIR;NAME.TYPE.123"
"HOST:DIR1;DIR2;DIR3;NAME.TYPE.123"
"HOST:DIR1;*;DIR3;NAME.TYPE.123"
"HOST:DIR1;**;DIR3;NAME.TYPE.123"
"HOST:;*.TYPE.123"
"HOST:;*;*.TYPE.123"
"HOST:;**;*.TYPE.123"
"HOST:;DIR;*.TYPE.123"
"HOST:;DIR1;DIR2;DIR3;*.TYPE.123"
"HOST:;DIR1;*;DIR3;*.TYPE.123"
"HOST:;DIR1;**;DIR3;*.TYPE.123"
"HOST:"
"HOST:*;*.TYPE.123"
"HOST:**;*.TYPE.123"
"HOST:DIR;*.TYPE.123"
"HOST:DIR1;DIR2;DIR3;*.TYPE.123"
"HOST:DIR1;*;DIR3;*.TYPE.123"
"HOST:DIR1;**;DIR3;*.TYPE.123"
"HOST:;.TYPE.newest"
"HOST:;*;.TYPE.newest"
"HOST:;**;.TYPE.newest"
"HOST:;DIR;.TYPE.newest"
"HOST:;DIR1;DIR2;DIR3;.TYPE.newest"
"HOST:;DIR1;*;DIR3;.TYPE.newest"
"HOST:;DIR1;**;DIR3;.TYPE.newest"
"HOST:"
"HOST:*;.TYPE.newest"
"HOST:**;.TYPE.newest"
"HOST:DIR;.TYPE.newest"
"HOST:DIR1;DIR2;DIR3;.TYPE.newest"
"HOST:DIR1;*;DIR3;.TYPE.newest"
"HOST:DIR1;**;DIR3;.TYPE.newest"
"HOST:;NAME.TYPE.newest"
"HOST:;*;NAME.TYPE.newest"
"HOST:;**;NAME.TYPE.newest"
"HOST:;DIR;NAME.TYPE.newest"
"HOST:;DIR1;DIR2;DIR3;NAME.TYPE.newest"
"HOST:;DIR1;*;DIR3;NAME.TYPE.newest"
"HOST:;DIR1;**;DIR3;NAME.TYPE.newest"
"HOST:"
"HOST:*;NAME.TYPE.newest"
"HOST:**;NAME.TYPE.newest"
"HOST:DIR;NAME.TYPE.newest"
"HOST:DIR1;DIR2;DIR3;NAME.TYPE.newest"
"HOST:DIR1;*;DIR3;NAME.TYPE.newest"
"HOST:DIR1;**;DIR3;NAME.TYPE.newest"
"HOST:;*.TYPE.newest"
"HOST:;*;*.TYPE.newest"
"HOST:;**;*.TYPE.newest"
"HOST:;DIR;*.TYPE.newest"
"HOST:;DIR1;DIR2;DIR3;*.TYPE.newest"
"HOST:;DIR1;*;DIR3;*.TYPE.newest"
"HOST:;DIR1;**;DIR3;*.TYPE.newest"
"HOST:"
"HOST:*;*.TYPE.newest"
"HOST:**;*.TYPE.newest"
"HOST:DIR;*.TYPE.newest"
"HOST:DIR1;DIR2;DIR3;*.TYPE.newest"
"HOST:DIR1;*;DIR3;*.TYPE.newest"
"HOST:DIR1;**;DIR3;*.TYPE.newest"
"HOST:;.TYPE.NEWEST"
"HOST:;*;.TYPE.NEWEST"
"HOST:;**;.TYPE.NEWEST"
"HOST:;DIR;.TYPE.NEWEST"
"HOST:;DIR1;DIR2;DIR3;.TYPE.NEWEST"
"HOST:;DIR1;*;DIR3;.TYPE.NEWEST"
"HOST:;DIR1;**;DIR3;.TYPE.NEWEST"
"HOST:"
"HOST:*;.TYPE.NEWEST"
"HOST:**;.TYPE.NEWEST"
"HOST:DIR;.TYPE.NEWEST"
"HOST:DIR1;DIR2;DIR3;.TYPE.NEWEST"
"HOST:DIR1;*;DIR3;.TYPE.NEWEST"
"HOST:DIR1;**;DIR3;.TYPE.NEWEST"
"HOST:;NAME.TYPE.NEWEST"
"HOST:;*;NAME.TYPE.NEWEST"
"HOST:;**;NAME.TYPE.NEWEST"
"HOST:;DIR;NAME.TYPE.NEWEST"
"HOST:;DIR1;DIR2;DIR3;NAME.TYPE.NEWEST"
"HOST:;DIR1;*;DIR3;NAME.TYPE.NEWEST"
"HOST:;DIR1;**;DIR3;NAME.TYPE.NEWEST"
"HOST:"
"HOST:*;NAME.TYPE.NEWEST"
"HOST:**;NAME.TYPE.NEWEST"
"HOST:DIR;NAME.TYPE.NEWEST"
"HOST:DIR1;DIR2;DIR3;NAME.TYPE.NEWEST"
"HOST:DIR1;*;DIR3;NAME.TYPE.NEWEST"
"HOST:DIR1;**;DIR3;NAME.TYPE.NEWEST"
"HOST:;*.TYPE.NEWEST"
"HOST:;*;*.TYPE.NEWEST"
"HOST:;**;*.TYPE.NEWEST"
"HOST:;DIR;*.TYPE.NEWEST"
"HOST:;DIR1;DIR2;DIR3;*.TYPE.NEWEST"
"HOST:;DIR1;*;DIR3;*.TYPE.NEWEST"
"HOST:;DIR1;**;DIR3;*.TYPE.NEWEST"
"HOST:"
"HOST:*;*.TYPE.NEWEST"
"HOST:**;*.TYPE.NEWEST"
"HOST:DIR;*.TYPE.NEWEST"
"HOST:DIR1;DIR2;DIR3;*.TYPE.NEWEST"
"HOST:DIR1;*;DIR3;*.TYPE.NEWEST"
"HOST:DIR1;**;DIR3;*.TYPE.NEWEST"
"HOST:;.TYPE.*"
"HOST:;*;.TYPE.*"
"HOST:;**;.TYPE.*"
"HOST:;DIR;.TYPE.*"
"HOST:;DIR1;DIR2;DIR3;.TYPE.*"
"HOST:;DIR1;*;DIR3;.TYPE.*"
"HOST:;DIR1;**;DIR3;.TYPE.*"
"HOST:"
"HOST:*;.TYPE.*"
"HOST:**;.TYPE.*"
"HOST:DIR;.TYPE.*"
"HOST:DIR1;DIR2;DIR3;.TYPE.*"
"HOST:DIR1;*;DIR3;.TYPE.*"
"HOST:DIR1;**;DIR3;.TYPE.*"
"HOST:;NAME.TYPE.*"
"HOST:;*;NAME.TYPE.*"
"HOST:;**;NAME.TYPE.*"
"HOST:;DIR;NAME.TYPE.*"
"HOST:;DIR1;DIR2;DIR3;NAME.TYPE.*"
"HOST:;DIR1;*;DIR3;NAME.TYPE.*"
"HOST:;DIR1;**;DIR3;NAME.TYPE.*"
"HOST:"
"HOST:*;NAME.TYPE.*"
"HOST:**;NAME.TYPE.*"
"HOST:DIR;NAME.TYPE.*"
"HOST:DIR1;DIR2;DIR3;NAME.TYPE.*"
"HOST:DIR1;*;DIR3;NAME.TYPE.*"
"HOST:DIR1;**;DIR3;NAME.TYPE.*"
"HOST:;*.TYPE.*"
"HOST:;*;*.TYPE.*"
"HOST:;**;*.TYPE.*"
"HOST:;DIR;*.TYPE.*"
"HOST:;DIR1;DIR2;DIR3;*.TYPE.*"
"HOST:;DIR1;*;DIR3;*.TYPE.*"
"HOST:;DIR1;**;DIR3;*.TYPE.*"
"HOST:"
"HOST:*;*.TYPE.*"
"HOST:**;*.TYPE.*"
"HOST:DIR;*.TYPE.*"
"HOST:DIR1;DIR2;DIR3;*.TYPE.*"
"HOST:DIR1;*;DIR3;*.TYPE.*"
"HOST:DIR1;**;DIR3;*.TYPE.*"
"HOST:;.*"
"HOST:;*;.*"
"HOST:;**;.*"
"HOST:;DIR;.*"
"HOST:;DIR1;DIR2;DIR3;.*"
"HOST:;DIR1;*;DIR3;.*"
"HOST:;DIR1;**;DIR3;.*"
"HOST:"
"HOST:*;.*"
"HOST:**;.*"
"HOST:DIR;.*"
"HOST:DIR1;DIR2;DIR3;.*"
"HOST:DIR1;*;DIR3;.*"
"HOST:DIR1;**;DIR3;.*"
"HOST:;NAME.*"
"HOST:;*;NAME.*"
"HOST:;**;NAME.*"
"HOST:;DIR;NAME.*"
"HOST:;DIR1;DIR2;DIR3;NAME.*"
"HOST:;DIR1;*;DIR3;NAME.*"
"HOST:;DIR1;**;DIR3;NAME.*"
"HOST:"
"HOST:*;NAME.*"
"HOST:**;NAME.*"
"HOST:DIR;NAME.*"
"HOST:DIR1;DIR2;DIR3;NAME.*"
"HOST:DIR1;*;DIR3;NAME.*"
"HOST:DIR1;**;DIR3;NAME.*"
"HOST:;*.*"
"HOST:;*;*.*"
"HOST:;**;*.*"
"HOST:;DIR;*.*"
"HOST:;DIR1;DIR2;DIR3;*.*"
"HOST:;DIR1;*;DIR3;*.*"
"HOST:;DIR1;**;DIR3;*.*"
"HOST:"
"HOST:*;*.*"
"HOST:**;*.*"
"HOST:DIR;*.*"
"HOST:DIR1;DIR2;DIR3;*.*"
"HOST:DIR1;*;DIR3;*.*"
"HOST:DIR1;**;DIR3;*.*"
"HOST:;.*.123"
"HOST:;*;.*.123"
"HOST:;**;.*.123"
"HOST:;DIR;.*.123"
"HOST:;DIR1;DIR2;DIR3;.*.123"
"HOST:;DIR1;*;DIR3;.*.123"
"HOST:;DIR1;**;DIR3;.*.123"
"HOST:"
"HOST:*;.*.123"
"HOST:**;.*.123"
"HOST:DIR;.*.123"
"HOST:DIR1;DIR2;DIR3;.*.123"
"HOST:DIR1;*;DIR3;.*.123"
"HOST:DIR1;**;DIR3;.*.123"
"HOST:;NAME.*.123"
"HOST:;*;NAME.*.123"
"HOST:;**;NAME.*.123"
"HOST:;DIR;NAME.*.123"
"HOST:;DIR1;DIR2;DIR3;NAME.*.123"
"HOST:;DIR1;*;DIR3;NAME.*.123"
"HOST:;DIR1;**;DIR3;NAME.*.123"
"HOST:"
"HOST:*;NAME.*.123"
"HOST:**;NAME.*.123"
"HOST:DIR;NAME.*.123"
"HOST:DIR1;DIR2;DIR3;NAME.*.123"
"HOST:DIR1;*;DIR3;NAME.*.123"
"HOST:DIR1;**;DIR3;NAME.*.123"
"HOST:;*.*.123"
"HOST:;*;*.*.123"
"HOST:;**;*.*.123"
"HOST:;DIR;*.*.123"
"HOST:;DIR1;DIR2;DIR3;*.*.123"
"HOST:;DIR1;*;DIR3;*.*.123"
"HOST:;DIR1;**;DIR3;*.*.123"
"HOST:"
"HOST:*;*.*.123"
"HOST:**;*.*.123"
"HOST:DIR;*.*.123"
"HOST:DIR1;DIR2;DIR3;*.*.123"
"HOST:DIR1;*;DIR3;*.*.123"
"HOST:DIR1;**;DIR3;*.*.123"
"HOST:;.*.newest"
"HOST:;*;.*.newest"
"HOST:;**;.*.newest"
"HOST:;DIR;.*.newest"
"HOST:;DIR1;DIR2;DIR3;.*.newest"
"HOST:;DIR1;*;DIR3;.*.newest"
"HOST:;DIR1;**;DIR3;.*.newest"
"HOST:"
"HOST:*;.*.newest"
"HOST:**;.*.newest"
"HOST:DIR;.*.newest"
"HOST:DIR1;DIR2;DIR3;.*.newest"
"HOST:DIR1;*;DIR3;.*.newest"
"HOST:DIR1;**;DIR3;.*.newest"
"HOST:;NAME.*.newest"
"HOST:;*;NAME.*.newest"
"HOST:;**;NAME.*.newest"
"HOST:;DIR;NAME.*.newest"
"HOST:;DIR1;DIR2;DIR3;NAME.*.newest"
"HOST:;DIR1;*;DIR3;NAME.*.newest"
"HOST:;DIR1;**;DIR3;NAME.*.newest"
"HOST:"
"HOST:*;NAME.*.newest"
"HOST:**;NAME.*.newest"
"HOST:DIR;NAME.*.newest"
"HOST:DIR1;DIR2;DIR3;NAME.*.newest"
"HOST:DIR1;*;DIR3;NAME.*.newest"
"HOST:DIR1;**;DIR3;NAME.*.newest"
"HOST:;*.*.newest"
"HOST:;*;*.*.newest"
"HOST:;**;*.*.newest"
"HOST:;DIR;*.*.newest"
"HOST:;DIR1;DIR2;DIR3;*.*.newest"
"HOST:;DIR1;*;DIR3;*.*.newest"
"HOST:;DIR1;**;DIR3;*.*.newest"
"HOST:"
"HOST:*;*.*.newest"
"HOST:**;*.*.newest"
"HOST:DIR;*.*.newest"
"HOST:DIR1;DIR2;DIR3;*.*.newest"
"HOST:DIR1;*;DIR3;*.*.newest"
"HOST:DIR1;**;DIR3;*.*.newest"
"HOST:;.*.NEWEST"
"HOST:;*;.*.NEWEST"
"HOST:;**;.*.NEWEST"
"HOST:;DIR;.*.NEWEST"
"HOST:;DIR1;DIR2;DIR3;.*.NEWEST"
"HOST:;DIR1;*;DIR3;.*.NEWEST"
"HOST:;DIR1;**;DIR3;.*.NEWEST"
"HOST:"
"HOST:*;.*.NEWEST"
"HOST:**;.*.NEWEST"
"HOST:DIR;.*.NEWEST"
"HOST:DIR1;DIR2;DIR3;.*.NEWEST"
"HOST:DIR1;*;DIR3;.*.NEWEST"
"HOST:DIR1;**;DIR3;.*.NEWEST"
"HOST:;NAME.*.NEWEST"
"HOST:;*;NAME.*.NEWEST"
"HOST:;**;NAME.*.NEWEST"
"HOST:;DIR;NAME.*.NEWEST"
"HOST:;DIR1;DIR2;DIR3;NAME.*.NEWEST"
"HOST:;DIR1;*;DIR3;NAME.*.NEWEST"
"HOST:;DIR1;**;DIR3;NAME.*.NEWEST"
"HOST:"
"HOST:*;NAME.*.NEWEST"
"HOST:**;NAME.*.NEWEST"
"HOST:DIR;NAME.*.NEWEST"
"HOST:DIR1;DIR2;DIR3;NAME.*.NEWEST"
"HOST:DIR1;*;DIR3;NAME.*.NEWEST"
"HOST:DIR1;**;DIR3;NAME.*.NEWEST"
"HOST:;*.*.NEWEST"
"HOST:;*;*.*.NEWEST"
"HOST:;**;*.*.NEWEST"
"HOST:;DIR;*.*.NEWEST"
"HOST:;DIR1;DIR2;DIR3;*.*.NEWEST"
"HOST:;DIR1;*;DIR3;*.*.NEWEST"
"HOST:;DIR1;**;DIR3;*.*.NEWEST"
"HOST:"
"HOST:*;*.*.NEWEST"
"HOST:**;*.*.NEWEST"
"HOST:DIR;*.*.NEWEST"
"HOST:DIR1;DIR2;DIR3;*.*.NEWEST"
"HOST:DIR1;*;DIR3;*.*.NEWEST"
"HOST:DIR1;**;DIR3;*.*.NEWEST"
"HOST:;.*.*"
"HOST:;*;.*.*"
"HOST:;**;.*.*"
"HOST:;DIR;.*.*"
"HOST:;DIR1;DIR2;DIR3;.*.*"
"HOST:;DIR1;*;DIR3;.*.*"
"HOST:;DIR1;**;DIR3;.*.*"
"HOST:"
"HOST:*;.*.*"
"HOST:**;.*.*"
"HOST:DIR;.*.*"
"HOST:DIR1;DIR2;DIR3;.*.*"
"HOST:DIR1;*;DIR3;.*.*"
"HOST:DIR1;**;DIR3;.*.*"
"HOST:;NAME.*.*"
"HOST:;*;NAME.*.*"
"HOST:;**;NAME.*.*"
"HOST:;DIR;NAME.*.*"
"HOST:;DIR1;DIR2;DIR3;NAME.*.*"
"HOST:;DIR1;*;DIR3;NAME.*.*"
"HOST:;DIR1;**;DIR3;NAME.*.*"
"HOST:"
"HOST:*;NAME.*.*"
"HOST:**;NAME.*.*"
"HOST:DIR;NAME.*.*"
"HOST:DIR1;DIR2;DIR3;NAME.*.*"
"HOST:DIR1;*;DIR3;NAME.*.*"
"HOST:DIR1;**;DIR3;NAME.*.*"
"HOST:;*.*.*"
"HOST:;*;*.*.*"
"HOST:;**;*.*.*"
"HOST:;DIR;*.*.*"
"HOST:;DIR1;DIR2;DIR3;*.*.*"
"HOST:;DIR1;*;DIR3;*.*.*"
"HOST:;DIR1;**;DIR3;*.*.*"
"HOST:"
"HOST:*;*.*.*"
"HOST:**;*.*.*"
"HOST:DIR;*.*.*"
"HOST:DIR1;DIR2;DIR3;*.*.*"
"HOST:DIR1;*;DIR3;*.*.*"
"HOST:DIR1;**;DIR3;*.*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;"
"HOST:*DIR1;D*I*R*2;DIR3*;"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*"
"HOST:;*DIR1;D*I*R*2;DIR3*;*"
"HOST:*DIR1;D*I*R*2;DIR3*;*"
"HOST:;*DIR1;D*I*R*2;DIR3*;.T*P*"
"HOST:*DIR1;D*I*R*2;DIR3*;.T*P*"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.T*P*"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.T*P*"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.T*P*"
"HOST:*DIR1;D*I*R*2;DIR3*;*.T*P*"
"HOST:;*DIR1;D*I*R*2;DIR3*;.T*P*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;.T*P*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.T*P*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;*.T*P*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;.T*P*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;.T*P*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.T*P*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;*.T*P*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;.T*P*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;.T*P*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.T*P*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;*.T*P*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;.T*P*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;.T*P*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.T*P*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.T*P*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;*.T*P*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;.*"
"HOST:*DIR1;D*I*R*2;DIR3*;.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;.*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;.*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.*.123"
"HOST:*DIR1;D*I*R*2;DIR3*;*.*.123"
"HOST:;*DIR1;D*I*R*2;DIR3*;.*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;.*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.*.newest"
"HOST:*DIR1;D*I*R*2;DIR3*;*.*.newest"
"HOST:;*DIR1;D*I*R*2;DIR3*;.*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;.*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.*.NEWEST"
"HOST:*DIR1;D*I*R*2;DIR3*;*.*.NEWEST"
"HOST:;*DIR1;D*I*R*2;DIR3*;.*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;.*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;N*M*.*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;N*M*.*.*"
"HOST:;*DIR1;D*I*R*2;DIR3*;*.*.*"
"HOST:*DIR1;D*I*R*2;DIR3*;*.*.*"
)))
;; (ls -v --versions)
;; (ls -l --long) ; show author, write-date, element-type, size
(progn
(ensure-directories-exist "HOME:A;B;C;D.E")
(ensure-directories-exist "HOME:A;C;C;D.E")
(ensure-directories-exist "HOME:A;D;C;D.E")
(ensure-directories-exist "HOME:A;D;G;D.E")
(ensure-directories-exist "HOME:B;C;D;E.E")
(ensure-directories-exist "HOME:B;C;E;E.E")
(ensure-directories-exist "HOME:B;C;F;E.E"))
(dotimes (i 2) (create-file-at-path "HOME:B;C;E;TEST.LISP"))
(dotimes (i 1) (create-file-at-path "HOME:A;B;EXEMPLE-1.TXT"))
(dotimes (i 2) (create-file-at-path "HOME:A;B;EXEMPLE-2.TXT"))
(dotimes (i 3) (create-file-at-path "HOME:A;B;EXEMPLE-3.TXT"))
(dotimes (i 2) (create-file-at-path "HOME:A;2-TOTO.TXT"))
(dotimes (i 3) (create-file-at-path "HOME:A;3-TOTO.TXT"))
(dotimes (i 4) (create-file-at-path "HOME:A;4-TOTO.TXT"))
(in-package "VFS-USER")
(INSTALL-PATHNAME-READER-MACRO)
(progn
(vfs::create-file-at-path #P"HOME:TEST.TEXT")
(vfs::create-file-at-path #P"HOME:EXAMPLE.TEXT")
(vfs::create-new-version (vfs::file (vfs::file-entry #P"HOME:EXAMPLE.TEXT")))
(vfs::dump (vfs::file-system-named "HOME")))
(let ((path #P"HOME:TEST.TEXT")
(path #P"HOME:EXAMPLE.TEXT"))
(defparameter *s* (open path :direction :output
:if-exists :new-version
:if-does-not-exist :create
:element-type 'base-char))
(write-char #\* *s*)
(print (file-length *s*))
(write-string " Hello World" *s*)
(print (file-length *s*))
(write-line "! How do you do?" *s*)
(print (file-length *s*))
(close *s*)
(terpri)
(finish-output)
(vfs::dump (vfs::file-system-named "HOME")))
(let ((path #P"HOME:EXAMPLE.DATA"))
(defparameter *s* (open path
:direction :output
:element-type '(unsigned-byte 21)
:if-exists :new-version
:if-does-not-exist :create))
(write-byte (char-code #\*) *s*)
(print (file-length *s*))
(write-sequence (map 'vector 'char-code " Hello World") *s*)
(print (file-length *s*))
(write-sequence (map 'vector 'char-code "! How do you do?") *s*)
(write-byte (char-code #\newline) *s*)
(print (file-length *s*))
(close *s*)
(terpri)
(finish-output)
(vfs::dump (vfs::file-system-named "HOME")))
(untrace replace)
(untrace vfs::!write-element replace)
(progn
(defparameter *s* (open "HOME:EXAMPLE.TEXT" :direction :input
:element-type 'base-char))
(prog1 (read-line *s*)
(close *s*)
(vfs::dump (vfs::file-system-named "HOME"))))
(progn
(defparameter *s* (open "HOME:EXAMPLE.DATA" :direction :input
:element-type '(unsigned-byte 21)))
(prog1 (read-sequence (make-array (file-length *s*)
:element-type '(unsigned-byte 21))
*s*)
(close *s*)
(vfs::dump (vfs::file-system-named "HOME"))))
(setf (logical-pathname-translations "LISP") nil)
(setf (logical-pathname-translations "LISP") (list (list #P"LISP:**;*.*.*" #P"HOME:SRC;LISP;**;*.*.*")
(list #P"LISP:**;*.*" #P"HOME:SRC;LISP;**;*.*")
(list #P"LISP:**;*" #P"HOME:SRC;LISP;**;*")))
(let ((path #P"LISP:TEST.LISP"))
(defparameter *s* (open path :direction :output
:if-exists :new-version
:if-does-not-exist :create))
(write-line ";;;; -*- mode:lisp -*-" *s*)
(write-string (prin1-to-string '(defun test (arg)
(princ "Hello Test!") (terpri)
(princ arg) (terpri)
(princ "Done here." (terpri)
arg)))
*s*)
(terpri *s*)
(print (file-length *s*))
(close *s*)
(terpri)
(finish-output)
(vfs::dump (vfs::file-system-named "HOME")))
(vfs::dump-pathname #P"LISP:TEST.LISP")
| 25,440 | Common Lisp | .lisp | 629 | 25.594595 | 102 | 0.406436 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | aa908228beec1e35b103bbf6528d4d82a8186079d5ad2b6e0f2d2925d0b93adb | 4,705 | [
-1
] |
4,706 | standard-streams.lisp | informatimago_lisp/future/vfs/standard-streams.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: standard-streams.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Defines the standard streams.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defvar *standard-input* (make-string-input-stream ""))
(defvar *standard-output* (make-string-output-stream))
(defvar *error-output* (make-string-output-stream))
(defvar *trace-output* *standard-output*)
(defvar *terminal-io* (make-two-way-stream *standard-input*
*standard-output*))
(defvar *debug-io* *terminal-io*)
(defvar *query-io* *terminal-io*)
;;;; THE END ;;;;
| 2,034 | Common Lisp | .lisp | 47 | 41.170213 | 78 | 0.602823 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 47a8e5560b3b478bb3928c7b0a271dd3272a230baf66d0ab57bfbfbcadbaba90 | 4,706 | [
-1
] |
4,707 | vfs-file-stream.lisp | informatimago_lisp/future/vfs/vfs-file-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: vfs-file-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the file stream operators
;;;; for the Virtual File System backend.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass file-stream (stream)
((pathname :accessor pathname
:initarg :pathname)
(file :accessor %file-stream-file
:initarg :file)
(contents :accessor %file-stream-contents
:initarg :contents)
(position :accessor %file-stream-position
:initarg :position
:initform 0
:type (integer 0))
(override-p :accessor %override-p
:initarg :override-p)))
(defclass file-input-stream (file-stream)
())
(defclass file-output-stream (file-stream)
())
(defclass file-io-stream (file-input-stream file-output-stream)
())
(defgeneric print-object-fields (self stream))
(defmethod print-object-fields ((self file-stream) stream)
(call-next-method)
(format stream " :PATHNAME ~S :POSITION ~A"
(pathname self) (%file-stream-position self)))
(defmethod print-object ((self file-stream) stream)
(print-unreadable-object (self stream :type nil :identity t)
(format stream "~A" 'file-stream)
(print-object-fields self stream))
self)
(define-stream-methods file-stream
(stream-external-format (%stream-external-format stream))
(file-length (length (contents (%file-stream-contents stream))))
(file-string-length
(etypecase object
(character 1)
(string (length object))))
(close
(prog1 (%open-stream-p stream)
(when (%open-stream-p stream)
(setf (%open-stream-p stream) nil)
(when (%override-p stream)
(let* ((path (pathname stream))
(dir (directory-entry path)))
(delete-file path)
(add-entry dir (%file-stream-file stream))))))))
(defun open (filespec &key (direction :input)
(element-type 'character)
(if-exists nil)
(if-does-not-exist nil)
(external-format :default))
(check-type direction (member :input :output :io :probe))
(check-type if-exists (member :error :new-version :rename :rename-and-delete
:overwrite :append :supersede nil))
(check-type if-does-not-exist (member :error :create nil))
(check-type external-format (member :default))
(let ((path (resolve-pathspec filespec)))
(labels ((make-stream (file openp inputp outputp overridep position)
(let* ((contents (newest file)))
(make-instance (if inputp
(if outputp
'file-io-stream
'file-input-stream)
(if outputp
'file-output-stream
'file-stream))
:open-p openp
:element-type (element-type contents)
:external-format :default ; ???
:input-p inputp
:output-p outputp
:override-p overridep
:pathname (truename path)
:file file
:contents contents
:position (ecase position
(:start 0)
(:end (length (contents contents)))))))
(new-file (path element-type)
(create-file-at-path path :create-version-p t :element-type element-type))
(new-file/unlinked (path element-type)
(let ((entry (make-instance 'fs-file
:name (pathname-name path) :type (pathname-type path))))
(create-new-version entry :element-type element-type)
entry))
(new-version (file element-type)
(create-new-version file :element-type element-type))
(copy-new-version (contents)
(let ((new-contents (newest (create-new-version (file contents)
:element-type (element-type contents)))))
(setf (contents new-contents) (copy-array (contents contents)
:copy-fill-pointer t
:copy-adjustable t))
(file new-contents)))
(rename-old (file &optional (index 0))
(let ((old (make-pathname :type (format nil "~A-OLD-~3,'0D"
(pathname-type file)
(incf index))
:defaults file)))
(if (file-entry old)
(rename-old file index)
(rename-file file old)))))
(let ((contents (file-entry path)))
;; filespec ¬N.T ¬N.T.3<NEWEST ¬N.T.3>NEWEST N.T.3=NEWEST N.T.3<NEWEST
;; N.T no exist newest newest newest newest
;; N.T.3 no exist no exist no exist newest old version
;; create newest create newest
(ecase direction
((:input :probe)
(if contents
(progn
;; TODO: use CERROR to ignre the requested element-type
(assert (equal (element-type contents) element-type)
() "~A: the element-type requested ~S must be identical to the element-type ~S of the file ~S"
'open element-type (element-type contents) path)
(make-stream (file contents) (eql direction :input) t nil nil :start))
(ecase if-does-not-exist
((:error)
(error (make-condition
'simple-file-error
:pathname path
:format-control "~A: file ~S does not exist"
:format-arguments (list 'open path))))
((:create)
(make-stream (new-file path element-type) (eql direction :input) t nil nil :start))
((nil)
(return-from open nil)))))
((:output :io)
(if contents
;; file exists:
(ecase if-exists
((:error)
(error (make-condition
'simple-file-error
:pathname path
:format-control "~A: file ~S already exists"
:format-arguments (list 'open path))))
((:new-version)
(make-stream (new-version (file contents) element-type)
t (eql direction :io) t nil :start))
((:rename)
(rename-old path)
(make-stream (new-file path element-type)
t (eql direction :io) t nil :start))
((:rename-and-delete)
(let ((old nil))
(unwind-protect
(progn
(setf old (rename-old path))
(make-stream (new-file path element-type)
t (eql direction :io) t nil :start))
(when old
(delete-file old)))))
((:overwrite)
(make-stream (if (eql contents (newest (file contents)))
(file contents)
(copy-new-version contents))
t (eql direction :io) t nil :start))
((:append)
(make-stream (if (eql contents (newest (file contents)))
(file contents)
(copy-new-version contents))
t (eql direction :io) t nil :end))
((:supersede)
(make-stream (new-file/unlinked path element-type)
t (eql direction :io) t nil :start))
((nil)
(return-from open nil)))
;; file does not exist:
(ecase if-does-not-exist
((:error)
(error (make-condition
'simple-file-error
:pathname path
:format-control "~A: file ~S does not exist"
:format-arguments (list 'open path))))
((:create)
(make-stream (new-file path element-type) t (eql direction :io) t t :start))
((nil)
(return-from open nil))))))))))
(defun !read-element (stream eof-error-p eof-value)
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(if (< position (length (contents contents)))
(aref (contents contents) (prog1 position (incf position)))
(if eof-error-p
(error 'end-of-file :stream stream)
eof-value))))
(defun !write-element (stream sequence start end)
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(let* ((end (or end (length sequence)))
(size (- end start))
(new-position (+ position size))
(data (contents contents)))
(if (< new-position *maximum-file-size*)
(progn
(unless (< new-position (array-dimension data 0))
(setf data (adjust-array data
(max new-position (* 2 (array-dimension data 0)))
:element-type (array-element-type data)
:initial-element (if (subtypep (array-element-type data)
'character)
#\space
0)
:fill-pointer (fill-pointer data))
(contents contents) data))
(when (< (fill-pointer data) new-position)
(setf (fill-pointer data) new-position))
(replace data sequence :start1 position :start2 start :end2 end)
(setf position new-position))
(error 'simple-stream-error
:stream stream
:format-control "data too big to be written on stream ~S (~A+~A=~A>~A)"
:format-arguments (list stream
position size new-position *maximum-file-size*))))))
(defun whitespacep (ch)
(position ch #(#\Space #\Newline #\Tab #\Linefeed #\Page #\Return)))
(define-stream-methods file-input-stream
(file-position
(call-next-method)
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(if position-spec
(if (< -1 position-spec (length (contents contents)))
(setf position position-spec)
(error 'simple-stream-error
:stream stream
:format-control "~A: invalid position ~A on stream ~S"
:format-arguments (list 'file-position position-spec stream))))
position))
(read-byte (!read-element stream eof-error-p eof-value))
(read-char (!read-element input-stream eof-error-p eof-value))
(read-char-no-hang (!read-element input-stream eof-error-p eof-value))
(peek-char
(flet ((eof ()
(if eof-error-p
(error 'end-of-file :stream stream)
eof-value)))
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(case peek-type
((nil))
((t)
(setf position (or (position-if-not (function whitespacep)
(contents contents)
:start position)
(length (contents contents)))))
(otherwise
(setf position (or (position peek-type
(contents contents)
:start position)
(length (contents contents))))))
(if (< position (length (contents contents)))
(aref (contents contents) position)
(eof)))))
(unread-char
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) input-stream
(when (plusp position)
(decf position))))
(read-line
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) input-stream
(let ((start position)
(end (or (position #\newline (contents contents) :start position)
(length (contents contents)))))
(prog1 (subseq (contents contents) start (if (< end (length (contents contents)))
(1- end)
end))
(setf position end)))))
(read-sequence
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(let ((start position)
(end (or (position #\newline (contents contents) :start position)
(length (contents contents)))))
(prog1 (subseq (contents contents) start (if (< end (length (contents contents)))
(1- end)
end))
(setf position end)))))
(listen
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) input-stream
(< position (length (contents contents)))))
(clear-input
#|nothing|#
nil))
(defvar *newline* (string #\newline))
(define-stream-methods file-output-stream
(file-position
(call-next-method)
(with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(if position-spec
(if (< -1 position-spec *maximum-file-size*)
(setf position position-spec)
(error 'simple-stream-error
:stream stream
:format-control "~A: invalid position ~A on stream ~S"
:format-arguments (list 'file-position position-spec stream))))
position))
(write-byte (!write-element stream (vector byte) 0 1)
byte)
(write-char (!write-element output-stream (string character) 0 1)
character)
(terpri (!write-element output-stream *newline* 0 (length *newline*))
nil)
(fresh-line (with-accessors ((contents %file-stream-contents)
(position %file-stream-position)) stream
(unless (and (plusp position)
(char= #\newline (aref (contents contents) (1- position))))
(!write-element output-stream *newline* 0 (length *newline*))
#\newline)))
(write-string (!write-element output-stream string start end)
string)
(write-line (!write-element output-stream string start end)
(!write-element output-stream *newline* 0 (length *newline*))
string)
(write-sequence (!write-element stream sequence start end)
sequence)
(clear-output #|nothing|# nil)
(force-output #|nothing|# nil)
(finish-output #|nothing|# nil))
;;;; THE END ;;;;
| 17,614 | Common Lisp | .lisp | 363 | 33.063361 | 119 | 0.50093 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | fdc39b76520a797200935eb3f4aa2cd1ee5243e02d013e3a03eb71c61b152e02 | 4,707 | [
-1
] |
4,708 | string-input.lisp | informatimago_lisp/future/vfs/string-input.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: string-input.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the string input operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass string-input-stream (string-stream)
((string :accessor %string-stream-input-string
:initarg :string
:initform ""
:type string)
(index :accessor %string-stream-index
:initarg :index
:initform 0
:type (integer 0))
(start :accessor %string-stream-start
:initarg :start
:initform 0
:type (integer 0))
(end :accessor %string-stream-end
:initarg :end
:initform nil
:type (or null (integer 0)))))
(defun make-string-input-stream (string &optional (start 0) (end nil))
(make-instance 'string-input-stream
:open-p t
:input-p t
:output-p nil
:element-type 'character
:external-format :default
:string string
:start start
:end end))
(defun !string-input-read (stream)
(if (< (%string-stream-index stream)
(or (%string-stream-end stream)
(length (%string-stream-input-string stream))))
(aref (%string-stream-input-string stream)
(prog1 (%string-stream-index stream)
(incf (%string-stream-index stream))))
(eof-stream stream eof-error-p eof-value)))
(define-stream-methods string-input-stream
(read-byte (char-code (!string-input-read stream)))
(read-char (!string-input-read stream)))
;;;; THE END ;;;;
| 2,979 | Common Lisp | .lisp | 77 | 34.168831 | 78 | 0.604426 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 5d10d216fea98ff054608a795c514b6c4d10dd62ad3302eb7b715b8893226105 | 4,708 | [
-1
] |
4,709 | two-way-stream.lisp | informatimago_lisp/future/vfs/two-way-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: two-way-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the two-way stream operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass two-way-stream (stream)
((input-stream :accessor %two-way-stream-input-stream
:initarg :input-stream
:initform nil)
(output-stream :accessor %two-way-stream-output-stream
:initarg :output-stream
:initform nil)))
(defun make-two-way-stream (input-stream output-stream)
(unless (input-stream-p input-stream)
(error (make-condition
'simple-type-error
:datum input-stream
:expected-type 'stream
:format-control "Stream is not an input stream")))
(unless (output-stream-p output-stream)
(error (make-condition
'simple-type-error
:datum output-stream
:expected-type 'stream
:format-control "Stream is not an output stream")))
(unless (equal (stream-element-type input-stream)
(stream-element-type output-stream))
(error "~S: the element types of the input stream ~S and the output stream ~S are not equal."
'make-two-way-stream
(stream-element-type input-stream)
(stream-element-type output-stream)))
(unless (equal (stream-external-format input-stream)
(stream-external-format output-stream))
(error "~S: the external-formats of the input stream ~S and the output stream ~S are not equal."
'make-two-way-stream
(stream-external-format input-stream)
(stream-external-format output-stream)))
(make-instance 'two-way-stream
:open-p t
:input-p t
:output-p t
:element-type (stream-element-type input-stream)
:external-format (stream-external-format input-stream)
:input-stream input-stream
:output-stream output-stream))
(define-forward two-way-stream-input-stream (two-way-stream)
(declare (stream-argument two-way-stream)
(check-stream-type two-way-stream)))
(define-forward two-way-stream-output-stream (two-way-stream)
(declare (stream-argument two-way-stream)
(check-stream-type two-way-stream)))
(define-stream-methods two-way-stream
(read-byte (read-byte (%two-way-stream-input-stream stream)
eof-error-p eof-value))
(read-char (read-char (%two-way-stream-input-stream stream)
eof-error-p eof-value))
(write-byte (write-byte (%two-way-stream-output-stream stream)))
(write-char (write-char (%two-way-stream-output-stream stream)))
(two-way-stream-input-stream (%two-way-stream-input-stream two-way-stream))
(two-way-stream-output-stream (%two-way-stream-output-stream two-way-stream)))
;;;; THE END ;;;;
| 4,301 | Common Lisp | .lisp | 94 | 39.87234 | 100 | 0.626698 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 46e48db5bf9cf92e5a8e7643becdbad0c3684de2a18c6447a75174a1bf46d06d | 4,709 | [
-1
] |
4,710 | string-output.lisp | informatimago_lisp/future/vfs/string-output.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: string-output.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the string output operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass string-output-stream (string-stream)
((string :accessor %string-stream-output-string
:initarg :string
:initform (make-array 8
:fill-pointer 0 :adjustable t
:element-type 'character)
:type string)))
(defun make-string-output-stream (&key (element-type 'character))
(make-instance 'string-output-stream
:open-p t
:input-p nil
:output-p t
:element-type 'character
:external-format :default
:string (make-array 8
:fill-pointer 0 :adjustable t
:element-type element-type)))
(define-stream-methods string-output-stream
(write-byte
(vector-push-extend (char-code byte)
(%string-stream-output-string stream)
(* 2 (length (%string-stream-output-string stream))))
byte)
(write-char
(vector-push-extend character
(%string-stream-output-string stream)
(* 2 (length (%string-stream-output-string stream))))
character))
(define-forward get-output-stream-string (string-output-stream)
(declare (stream-argument string-output-stream)
(check-stream-type string-output-stream))
(:method string-output-stream
(prog1 (copy-seq (%string-stream-output-string string-output-stream))
(setf (fill-pointer (%string-stream-output-string string-output-stream)) 0))))
;;;; THE END ;;;;
| 3,118 | Common Lisp | .lisp | 73 | 36.986301 | 84 | 0.602767 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e0c617efed0108c4a8d6b379c1f914027e4753c2749798468ffddcadc2605765 | 4,710 | [
-1
] |
4,711 | broadcast-stream.lisp | informatimago_lisp/future/vfs/broadcast-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: broadcast-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the broadcast stream operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass broadcast-stream (stream)
((streams :accessor %broadcast-stream-streams
:initarg :streams
:initform nil)))
(defun make-broadcast-stream (&rest streams)
(dolist (stream streams)
(unless (output-stream-p stream)
(error (make-condition
'simple-type-error
:datum stream
:expected-type 'stream
:format-control "Stream is not an output stream"))))
(make-instance 'broadcast-stream :streams streams))
(define-forward broadcast-stream-streams (broadcast-stream)
(declare (stream-argument broadcast-stream)
(check-stream-type broadcast-stream)))
(defmacro do-broadcast ((output-stream broadcast-stream)
&body body)
`(let ((results '()))
(dolist (,output-stream (%broadcast-stream-streams ,broadcast-stream)
(values-list results))
(setf results (multiple-value-list (progn ,@body))))))
(define-stream-methods broadcast-stream
(broadcast-stream-streams (%broadcast-stream-streams broadcast-stream))
(write-byte (do-broadcast (ostream stream)
(write-char byte ostream))
byte)
(write-char (do-broadcast (ostream stream)
(write-char character ostream))
character)
(terpri (do-broadcast (ostream stream)
(terpri ostream))
nil)
(fresh-line (do-broadcast (ostream stream)
(fresh-line ostream)))
(write-string (do-broadcast (ostream stream)
(write-string string ostream :start start :end end))
string)
(write-line (do-broadcast (ostream stream)
(write-line string ostream :start start :end end))
string)
(write-sequence (do-broadcast (ostream stream)
(write-sequence sequence ostream :start start :end end))
sequence)
(clear-output (do-broadcast (ostream stream)
(clear-output ostream)))
(force-output (do-broadcast (ostream stream)
(force-output ostream)))
(finish-output (do-broadcast (ostream stream)
(finish-output ostream)))
(file-length (if (%broadcast-stream-streams stream)
(file-length
(first (last (%broadcast-stream-streams stream))))
0))
(file-position (if (%broadcast-stream-streams stream)
(file-position
(first (last (%broadcast-stream-streams stream))))
0))
(file-string-length (if (%broadcast-stream-streams stream)
(file-string-length
(first (last (%broadcast-stream-streams stream))))
1))
(stream-external-format (if (%broadcast-stream-streams stream)
(stream-external-format
(car (last (%broadcast-stream-streams stream))))
't))
(close (prog1 (%open-stream-p stream)
(setf (%open-stream-p stream) nil
(%broadcast-stream-streams stream) nil))))
;;;; THE END ;;;;
| 5,267 | Common Lisp | .lisp | 108 | 37.398148 | 85 | 0.533644 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 90b97f4b4907566c39b4163ad0df1391a35f27002ed38e60b02cb5976292d01f | 4,711 | [
-1
] |
4,712 | loader.lisp | informatimago_lisp/future/vfs/loader.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(cd (make-pathname :name nil :type nil :version nil
:defaults (load-time-value *load-pathname*)))
(pushnew (pwd) asdf:*central-registry*)
(ql:quickload :com.informatimago.common-lisp.virtual-file-system)
(in-package "VFS-USER")
| 382 | Common Lisp | .lisp | 8 | 43.5 | 65 | 0.713514 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 66b02c336329802b552cb22d1a16c561f7bbc71b22e2d586623bd573207afdac | 4,712 | [
-1
] |
4,713 | virtual-fs.lisp | informatimago_lisp/future/vfs/virtual-fs.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: virtual-fs.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file implements a RAM based virtual file system.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-04-26 <PJB> Created. Quick-and-Dirty.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal Bourguignon 2006 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
;; (do-external-symbols (symbol "COMMON-LISP")
;; (export (intern (string symbol) *package*)))
(defvar *maximum-file-size* (* 1024 1024)
"Maximum virtual file size.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Internals: Memory based file systems.
(deftype file-type () '(or string null))
(deftype pathname-type () '(or file-type (member :wild :unspecific)))
(deftype file-version () 'integer)
(deftype pathname-version () '(or file-version
(member nil :wild :unspecific :newest)))
(defvar *dump-indent* " :")
(defgeneric dump (object &OPTIONAL STREAM LEVEL)
(:documentation "Dumps the OBJECT to *standard-output*."))
;;;---------------------------------------------------------------------
;;; FS-ITEM
;;;---------------------------------------------------------------------
(defclass fs-item ()
((parent :accessor parent
:initarg :parent
:type (or null fs-directory)))
(:documentation "Either a file, a directory or a whole file system."))
(defmethod dump ((self fs-item)
&optional (stream *standard-output*) (level ""))
(format stream "~A--> [ITM] ~S ### CANNOT DUMP SUCH AN ITEM~%" level self))
;;;---------------------------------------------------------------------
;;; FS-DIRECTORY
;;;---------------------------------------------------------------------
(defclass fs-directory (fs-item)
((name :accessor name
:initarg :name
:type string)
(entries :accessor entries
:initarg :entries
:initform (make-hash-table :test (function equal))
:type hash-table))
(:documentation "A directory, mapping item names to subdirectories or files."))
(defmethod pathname ((self fs-directory))
(let ((path (pathname (parent self))))
(setf (%pathname-directory path) (nconc (%pathname-directory path)
(list (name self))))
path))
(defmethod dump ((self fs-directory)
&optional (stream *standard-output*) (level ""))
(format t "~A--> [DIR] ~A~%" level (name self))
(maphash (lambda (k v)
(declare (ignore k))
(dump v stream (concatenate 'string level *dump-indent*)))
(entries self)))
(defgeneric select-entries (self predicate))
(defmethod select-entries ((self t) predicate)
(declare (ignorable self predicate))
'())
(defmethod select-entries ((self fs-directory) predicate)
(declare (ignorable predicate))
(let ((result '()))
(maphash (lambda (k v)
(declare (ignore k))
(when (funcall predicate v) (push v result))) (entries self))
result))
(defgeneric entry-name (self))
(defmethod entry-name ((self fs-directory))
(name self))
(defgeneric entry-named (self name))
(defmethod entry-named ((self t) (name string))
(error "~A is not a directory" (pathname self)))
(defmethod entry-named ((self fs-directory) (name string))
(gethash name (entries self)))
(defgeneric entry-at-path (self path))
(defmethod entry-at-path ((self t) path)
(declare (ignorable path))
(error "~S is not a directory" self))
(defmethod entry-at-path ((self fs-directory) path)
(if (null path)
self
(let ((entry (entry-named self (car path))))
(if (null entry)
(error "There's no directory ~A~A;" (pathname self) (car path))
(entry-at-path entry (cdr path))))))
(defgeneric add-entry (self entry))
(defmethod add-entry ((self fs-directory) (entry fs-item))
(let ((name (entry-name entry)))
(if (entry-named self name)
(error "An entry named ~S already exists in ~S" name self)
(setf (parent entry) self
(gethash name (entries self)) entry))))
(defgeneric remove-entry-named (self name))
(defmethod remove-entry-named ((self fs-directory) (name string))
(if (entry-named self name)
(remhash name (entries self))
(error "No entry named ~S exists in ~S" name self)))
;;;---------------------------------------------------------------------
;;; FS-FILE
;;;---------------------------------------------------------------------
(defclass fs-file (fs-item)
((name :accessor name
:initarg :name
:type string)
(type :accessor type
:initarg :type
:type file-type)
(versions :accessor versions
:initarg :versions
:initform (make-hash-table :test (function eql))
:type hash-table)
(newest :accessor newest
:initarg :newest
:initform nil
:type (or null file-contents)))
(:documentation "A file, with all its versions."))
(defmethod pathname ((self fs-file))
(let ((path (pathname (parent self))))
(setf (%pathname-name path) (name self)
(%pathname-type path) (type self))
path))
(defmethod dump ((self fs-file)
&optional (stream *standard-output*) (level ""))
(format t "~A--> [FIL] ~A.~A~%" level (name self) (type self))
(dolist (v (let ((versions '()))
(maphash (lambda (k v)
(declare (ignore k))
(push v versions))
(versions self))
(sort versions (function <) :key (function version))))
(dump v stream (concatenate 'string level *dump-indent*)))
self)
(defun pathname-entry-name (path)
(format nil "~A.~A" (pathname-name path) (pathname-type path)))
(defmethod entry-name ((self fs-file))
(format nil "~A.~A" (name self) (type self)))
(defgeneric author (self))
(defgeneric write-date (self))
(defgeneric element-type (self))
(defmethod author ((self fs-file)) (author (newest self)))
(defmethod write-date ((self fs-file)) (write-date (newest self)))
(defmethod element-type ((self fs-file)) (element-type (newest self)))
(defgeneric select-versions (self predicate))
(defmethod select-versions ((self fs-file) predicate)
(let ((result '()))
(maphash (lambda (k v)
(declare (ignore k))
(when (funcall predicate v) (push v result))) (versions self))
result))
(defun purge-file (file)
"
DO: Delete all the versions of the file but the newest.
"
(let ((entry (file-entry file)))
(if entry
(let* ((file (file entry))
(newest (newest file)))
(when newest
(let ((newtab (make-hash-table :test (function eql))))
(setf (gethash (version newest) newtab) newest
(versions file) newtab))))
(error "There's no file ~A" file)))
file)
(defun delete-version (file)
"
DO: Delete only the specified version.
"
(let ((entry (file-entry file)))
(if entry
(remove-version (file entry) (version entry))
(error "There's no file ~A" file))))
;;;---------------------------------------------------------------------
;;; FILE-CONTENTS
;;;---------------------------------------------------------------------
(defclass file-contents ()
((file :accessor file
:initarg :file
:type fs-file)
(version :accessor version
:initarg :version
:type file-version)
(author :accessor author
:initarg :author
:initform nil
:type (or null string))
(write-date :accessor write-date
:initarg :write-date
:initform (get-universal-time)
:type (or null (integer 0)))
(element-type :accessor element-type
:initarg :element-type
:initform 'character)
(contents :accessor contents
:initarg :contents
:type vector))
(:documentation "A versionned file contents."))
(defmethod pathname ((self file-contents))
(let ((path (pathname (file self))))
(setf (%pathname-version path) (version self))
path))
(defmethod dump ((self file-contents)
&optional (stream *standard-output*) (level ""))
(format stream "~A--> [VER] ~A ~((:AUTHOR ~S :WRITE-DATE ~S :ELEMENT-TYPE ~S :SIZE ~A)~)~%"
level (version self) (author self) (write-date self)
(element-type self)
(length (contents self))))
;;;---------------------------------------------------------------------
;;; fs-file
(defvar *author* nil
"The name or identification of the user.")
(defgeneric create-new-version (self &key element-type))
(defmethod create-new-version ((self fs-file) &key (element-type 'character))
"
DO: Add a new version to the file.
RETURN: The FS-FILE.
"
(setf (newest self)
(make-instance 'file-contents
:version (1+ (if (null (newest self)) 0 (version (newest self))))
:author *author*
:write-date (get-universal-time)
:element-type element-type
:contents (make-array 0 :fill-pointer 0 :adjustable t
:element-type element-type)
:file self))
(setf (gethash (version (newest self)) (versions self)) (newest self))
self)
;;;---------------------------------------------------------------------
;;; FILE SYSTEM
;;;---------------------------------------------------------------------
;;;
;;; We initialize three file systems ROOT:, SYS: and HOME:.
;;;
(defclass file-system (fs-directory)
()
(:documentation "A file system."))
(defmethod pathname ((self file-system))
(make-pathname :host (name self) :directory (list :absolute)))
(defparameter *file-systems* (make-hash-table :test (function equal)))
(defun file-system-register (fs)
(setf (gethash (name fs) *file-systems*) fs))
(defun file-system-named (name)
(gethash name *file-systems*))
(defparameter *default-file-system*
(file-system-register (make-instance 'file-system :name "ROOT")))
(file-system-register (make-instance 'file-system :name "SYS"))
(file-system-register (make-instance 'file-system :name "HOME"))
(defparameter *default-pathname-defaults*
(make-pathname :host (name *default-file-system*)
:directory '(:absolute)
:defaults nil))
(defun resolve-pathspec (pathspec)
(translate-logical-pathname (pathname pathspec)))
(defun directory-entry (pathspec)
(let* ((fspath (resolve-pathspec pathspec))
(fs (if (pathname-host fspath)
(file-system-named (pathname-host fspath))
*default-file-system*)))
(if fs
(entry-at-path fs (cdr (pathname-directory fspath)))
(error "There's no file system named ~S" (pathname-host fspath)))))
(defgeneric create-directories-at-path (self path &optional created))
(defmethod create-directories-at-path ((self fs-directory) path
&optional created)
(if (null path)
created
(let ((entry (entry-named self (car path))))
(unless entry
(setf entry (make-instance 'fs-directory :name (car path))
created t)
(add-entry self entry))
(if (typep entry 'fs-directory)
(create-directories-at-path entry (cdr path) created)
(error "~A~A; already exists and is not a directory."
(pathname self) (car path))))))
(defun file-entry (pathspec)
"
RETURN: The FILE-CONTENTS specified by PATHSPEC (if no version is specified, NEWEST is returned).
"
(let* ((file (resolve-pathspec pathspec))
(dir (directory-entry file))
(entry (entry-named dir (pathname-entry-name file))))
(when entry
(case (pathname-version file)
((nil :newest) (newest entry))
(otherwise (gethash (pathname-version file) (versions entry)))))))
(defun create-file-at-path (pathspec &key (create-version-p t) (element-type 'character))
"
RETURN: The FS-FILE created.
NOTE: If a FS-FILE existed at the given PATHSPEC, then it is returned,
a new version being created if CREATE-VERSION-P is true.
"
(let* ((file (resolve-pathspec pathspec))
(dir (directory-entry file))
(entry (entry-named dir (pathname-entry-name file))))
(unless entry
(setf entry (make-instance 'fs-file
:name (pathname-name file) :type (pathname-type file)))
(add-entry dir entry))
(typecase entry
(fs-file (if create-version-p
(create-new-version entry :element-type element-type)
entry))
(t (error "~A already exist and is not a file" (pathname entry))))))
;;;; the END ;;;;
| 14,575 | Common Lisp | .lisp | 337 | 36.133531 | 97 | 0.560783 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b5bc028fee802eb39a100f5b5849dc9aebb8f81425ec81c95db5560b086278fe | 4,713 | [
-1
] |
4,714 | streams.lisp | informatimago_lisp/future/vfs/streams.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: streams.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file exports streams.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-15 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 21. Streams
;;; http://www.lispworks.com/documentation/HyperSpec/Body/21_.htm
(define-condition simple-stream-error (stream-error simple-error)
()
(:report (lambda (condition stream)
(format stream "~?"
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)))))
;;;---------------------------------------------------------------------
;;; STREAM
;;;---------------------------------------------------------------------
(defclass stream ()
((open-p :accessor %open-stream-p
:initarg :open-p
:initform nil)
(element-type :accessor %stream-element-type
:initarg :element-type
:initform 'character)
(external-format :accessor %stream-external-format
:initarg :external-format
:initform :default)
(input-p :accessor %input-stream-p
:initarg :input-p
:initform nil)
(output-p :accessor %output-stream-p
:initarg :output-p
:initform nil)))
(defmethod print-object-fields ((self stream) stream)
(format stream " ~:[CLOSED~;OPEN~] ~[PROBE~;INPUT~;OUTPUT~;I/O~] :ELEMENT-TYPE ~S :EXTERNAL-FORMAT ~S"
(%open-stream-p self)
(if (%input-stream-p self)
(if (%output-stream-p self)
3
1)
(if (%output-stream-p self)
2
0))
(%stream-element-type self)
(%stream-external-format self)))
(defmethod print-object ((self stream) stream)
(print-unreadable-object (self stream :identity t :type t)
(print-object-fields self stream))
self)
(defclass string-stream (stream)
())
;; (define-forward name arguments
;; [ documentation-string ]
;; { declarations }
;; { forward-method-description })
;;
;; (declare (stream-arguments stream)
;; (stream-designnator (istream :input)) ; default
;; (stream-designator (ostream :output))
;; (check-stream-type file-stream)
;; (cl-forward t))
;;
;; (declare (stream-arguments stream))
;;
;; (declare (check-stream-type file-stream))
;;
;; method-description ::= (:method class [[declaration* | documentation]] form*)
(eval-when (:execute :compile-toplevel :load-toplevel)
(defun make-method-lambda-list (lambda-list self-name self-type)
(let* ((got-it nil)
(mand (mapcar (lambda (par)
(let ((name (parameter-name par)))
(if (eq name self-name)
(progn (setf got-it t)
(list name self-type))
(list name 't))))
(lambda-list-mandatory-parameters lambda-list)))
(opti (let ((optionals (lambda-list-optional-parameters lambda-list)))
(cond
((null optionals) nil)
(got-it (cons '&optional
(mapcar (function parameter-specifier)
optionals)))
(t (let ((pos (position self-name optionals
:key (function parameter-name))))
(if pos
(append
(mapcar (lambda (par) (list (parameter-name par) 't))
(subseq optionals 0 pos))
(list
(list (parameter-name (nth pos optionals))
self-type))
(when (< (1+ pos) (length optionals))
(cons '&optional
(mapcar (function parameter-specifier)
(subseq optionals (1+ pos))))))
(cons '&optional
(mapcar (function parameter-specifier)
optionals))))))))
(keys (mapcar (function parameter-specifier)
(lambda-list-keyword-parameters lambda-list)))
(rest (and (lambda-list-rest-p lambda-list)
(mapcar (function parameter-specifier)
(lambda-list-rest-parameter lambda-list)))))
(append mand opti
(when keys (cons '&key keys))
(when rest (list '&rest rest))))))
(defun stream-designator (stream direction)
"DIRECTION is either *standard-input* or *standard-output*"
(case stream
((t) *terminal-io*)
((nil) direction)
(otherwise stream)))
(defun signal-type-error (object type)
(error (make-condition 'type-error :datum object :expected-type type)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *stream-methods* (make-hash-table)
"Keep the information about methods defined with DEFINE-FORWARD,
for use by DEFINE-STREAM-METHODS"))
(defun check-open (method stream)
(unless (%open-stream-p stream)
(error (make-condition 'simple-stream-error
:stream stream
:format-control "~S on ~S is illegal: the stream must be open. "
:format-arguments (list method stream)))))
(defclass cl-stream (stream) ()) ; forward declaration for define-forward...
#+emacs (put 'define-forward 'lisp-indent-function 2)
(defmacro define-forward (name arguments &body body)
"
DO: Specifies the name and parameter list of methods.
The BODY contains declarations and method clauses.
Specific pseudo-declarations are:
(stream-argument stream-parameter)
(stream-designator (stream-parameter [:input|:output]))
Specify the stream parameter. In the case of
stream-designator, the stream can be *standard-input* or
*standard-output* by default, as indicated by the keyword.
(check-stream-type stream-parameter)
When given, the stream type is checked in the default method.
(overriding methods should (call-next-method)).
(check-open-p stream-parameter)
When given, the methods generated by DEFINE-STREAM-METHODS
will test for an open stream.
(cl-forward booolean)
When the boolean is true, a method is defined for CL-STREAM
that forwards the call to the corresponding CL function.
The method clauses in the body are of the form:
(:method class . body)
For each of these clause, method is defined for the given
stream class.
"
(let* ((documentation (extract-documentation body))
(declarations (declarations-hash-table (extract-declarations body)))
(body (extract-body body))
(stream-argument (caar (gethash 'stream-argument declarations)))
(stream-designator (caar (gethash 'stream-designator declarations)))
(stream-name (or stream-argument
(if (consp stream-designator)
(first stream-designator)
stream-designator)))
(check-stream-type (caar (gethash 'check-stream-type declarations)))
(cl-forward (caar (gethash 'cl-forward declarations)))
(check-open-p (caar (gethash 'check-open-p declarations)))
(lambda-list (parse-lambda-list arguments :ordinary))
(m-name (intern (format nil "%~A" (string name))))
(cl-name (intern (string name) "COMMON-LISP"))
(method-lambda-list (make-method-lambda-list lambda-list stream-name 'cl-stream))
(m-arguments (mapcar
(lambda (arg)
(if (eq arg stream-name)
`(cl-stream-stream ,stream-name)
arg))
(make-argument-list lambda-list))))
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (gethash ',name *stream-methods*)
(list ',m-name (parse-lambda-list ',arguments :ordinary)
',stream-name ',check-open-p)))
(defun ,name ,arguments
,@(when documentation (list documentation))
,@(when stream-designator
`((setf ,stream-name (stream-designator
,stream-name
,(if (listp stream-designator)
(ecase (second stream-designator)
((:input) '*standard-input*)
((:output) '*standard-output*))
'*standard-input*)))))
,(if (lambda-list-rest-p lambda-list)
`(apply (function ,m-name) ,@(make-argument-list lambda-list))
`(,m-name ,@(butlast (make-argument-list lambda-list)))))
,@(when cl-forward
;; TODO: review the generation of generic function lambda list:
`((defgeneric ,m-name ,(mapcar (lambda (parameter)
(if (listp parameter)
(first parameter)
parameter))
method-lambda-list))
(defmethod ,m-name ,method-lambda-list
,(if (lambda-list-rest-p lambda-list)
`(apply (function ,cl-name) ,@m-arguments)
`(,cl-name ,@(butlast m-arguments))))
;; We don't want to allow access to CL:STREAM from a sandbox.
;; (defmethod ,m-name
;; ,(make-method-lambda-list lambda-list stream-name 'cl:stream)
;; ,(let ((m-arguments (make-argument-list lambda-list)))
;; (if (lambda-list-rest-p lambda-list)
;; `(apply (function ,cl-name) ,@m-arguments)
;; `(,cl-name ,@(butlast m-arguments)))))
))
,@(when check-stream-type
`((defmethod ,m-name ,(make-method-lambda-list lambda-list stream-name 't)
(declare (ignore ,@(remove 'stream (if (lambda-list-rest-p lambda-list)
(make-argument-list lambda-list)
(butlast (make-argument-list lambda-list))))))
(signal-type-error ,stream-name ',check-stream-type))))
,@(mapcar
(lambda (method)
(when (and (listp method) (eq :method (car method)))
(destructuring-bind (method class-name &body body) method
(declare (ignore method))
`(defmethod ,m-name
,(make-method-lambda-list lambda-list stream-name class-name)
,@body))))
body))))
#+emacs (put 'define-stream-methods 'lisp-indent-function 1)
(defmacro define-stream-methods (class-name &body methods)
"
DO: Expands to a bunch of defmethod forms, with the parameter
defined with DEFINE-FORWARD, and the body provided in the
METHODS clauses.
"
`(progn
,@(mapcar (lambda (method)
(let ((minfo (gethash (first method) *stream-methods*)))
(unless minfo
(error "Unknown method ~S; please use DEFINE-FORWARD first"
(first method)))
(destructuring-bind (name lambda-list stream-name check-open-p)
minfo
`(defmethod ,name
,(make-method-lambda-list lambda-list stream-name class-name)
,@(when check-open-p `((check-open ',name ,stream-name)))
,@(rest method)))))
methods)))
(define-forward input-stream-p (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(define-forward output-stream-p (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(define-forward interactive-stream-p (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t))
(:method stream nil))
(define-forward open-stream-p (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(define-forward stream-element-type (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(defun streamp (object) (typep object 'stream))
(defun eof-stream (stream eof-error-p eof-value)
(if eof-error-p
(error (make-condition 'eof-error :stream stream))
eof-value))
(define-forward read-byte (stream &optional (eof-error-p t) (eof-value nil))
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)
(check-open-p t)))
(define-forward write-byte (byte stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)
(check-open-p t)))
(define-forward peek-char (&optional (peek-type nil) (stream *standard-input*)
(eof-error-p t) (eof-value nil)
(recursive-p nil))
(declare (stream-designator (stream :input))
(cl-forward t)
(check-open-p t)))
(define-forward read-char (&optional (input-stream *standard-input*)
(eof-error-p t) (eof-value nil)
(recursive-p nil))
(declare (stream-designator (input-stream :input))
(cl-forward t)
(check-open-p t)))
(define-forward read-char-no-hang (&optional (input-stream *standard-input*)
(eof-error-p t) (eof-value nil)
(recursive-p nil))
(declare (stream-designator (input-stream :input))
(cl-forward t)
(check-open-p t)))
(define-forward terpri (&optional (output-stream *standard-output*))
(declare (stream-designator (output-stream :output))
(cl-forward t)
(check-open-p t)))
(define-forward fresh-line (&optional (output-stream *standard-output*))
(declare (stream-designator (output-stream :output))
(cl-forward t)
(check-open-p t)))
(define-forward unread-char (character &optional (input-stream *standard-input*))
(declare (stream-designator (input-stream :input))
(cl-forward t)
(check-open-p t)))
(define-forward write-char (character
&optional (output-stream *standard-output*))
(declare (stream-designator (output-stream :output))
(cl-forward t)
(check-open-p t)))
(define-forward read-line (&optional (input-stream *standard-input*)
(eof-error-p t) (eof-value nil)
(recursive-p nil))
(declare (stream-designator (input-stream :input))
(cl-forward t)
(check-open-p t)))
(define-forward write-string (string
&optional (output-stream *standard-output*)
&key (start 0) (end nil))
(declare (stream-designator (output-stream :output))
(cl-forward t)
(check-open-p t)))
(define-forward write-line (string
&optional (output-stream *standard-output*)
&key (start 0) (end nil))
(declare (stream-designator (output-stream :output))
(cl-forward t)
(check-open-p t)))
(define-forward read-sequence (sequence stream &key (start 0) (end nil))
(declare (stream-argument stream)
(cl-forward t)
(check-open-p t)))
(define-forward write-sequence (sequence stream &key (start 0) (end nil))
(declare (stream-argument stream)
(cl-forward t)
(check-open-p t)))
(define-forward file-length (stream)
(declare (stream-argument stream)
(check-stream-type file-stream)
(cl-forward t)))
(define-forward file-position (stream &optional (position-spec nil))
(declare (stream-argument stream)
(cl-forward t)
(check-open-p t)))
(define-forward file-string-length (stream object)
(declare (stream-argument stream)
(check-stream-type file-stream)
(cl-forward t)
(check-open-p t)))
(define-forward stream-external-format (stream)
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(define-forward close (stream &key (abort nil))
(declare (stream-argument stream)
(check-stream-type stream)
(cl-forward t)))
(define-forward listen (&optional input-stream)
(declare (stream-designator input-stream)
(cl-forward t) (check-open-p t)))
(define-forward clear-input (&optional input-stream)
(declare (stream-designator (input-stream :input))
(cl-forward t) (check-open-p t)))
(define-forward clear-output (&optional output-stream)
(declare (stream-designator (output-stream :output))
(cl-forward t) (check-open-p t)))
(define-forward force-output (&optional output-stream)
(declare (stream-designator (output-stream :output))
(cl-forward t) (check-open-p t)))
(define-forward finish-output (&optional output-stream)
(declare (stream-designator (output-stream :output))
(cl-forward t) (check-open-p t)))
;;;; THE END ;;;;
| 19,750 | Common Lisp | .lisp | 412 | 35.59466 | 104 | 0.544448 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 8ff5d926dc521437c8356e927b6bbe1ab3ae15059f89110b9cb6ed3c629eef0e | 4,714 | [
-1
] |
4,715 | initialize.lisp | informatimago_lisp/future/vfs/initialize.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: initialize.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file initializes the vfs.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-15 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defparameter *debug-io* cl:*debug-io*)
(defparameter *error-output* cl:*error-output*)
(defparameter *trace-output* cl:*trace-output*)
(defparameter *standard-output* cl:*standard-output*)
(defparameter *standard-input* cl:*standard-input*)
(defparameter *terminal-io* cl:*terminal-io*)
(defparameter *author*
(first (last (cl:pathname-directory (cl:user-homedir-pathname))))
"The name or identification of the user.")
;;;; THE END ;;;;
| 2,027 | Common Lisp | .lisp | 48 | 40.916667 | 78 | 0.624365 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 59d9ef8ca975b124e7a568394c47a7afc8a01bd330a275bd176cab2450c15779 | 4,715 | [
-1
] |
4,716 | concatenated-stream.lisp | informatimago_lisp/future/vfs/concatenated-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: concatenated-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file defines the concatenated stream operators.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-01-14 <PJB> Extracted from 'virtual-fs.lisp'.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(defclass concatenated-stream (stream)
((streams :accessor %concatenated-stream-streams
:initarg :streams
:initform nil)))
(defun make-concatenated-stream (&rest input-streams)
(dolist (stream streams)
(unless (input-stream-p stream)
(error (make-condition
'simple-type-error
:datum stream
:expected-type 'stream
:format-control "Stream is not an input stream"))))
(make-instance 'concatenated-stream :streams input-streams))
(define-forward concatenated-stream-streams (concatenated-stream)
(declare (stream-argument concatenated-stream)
(check-stream-type concatenated-stream)))
(defun !concatenated-read-element (read-element
stream eof-error-p eof-value recursive-p)
(let ((current (first (%concatenated-stream-streams stream))))
(if (null current)
(eof-error stream eof-error-p eof-value)
(let ((element (multiple-value-list
(funcall read-element current nil stream recursive-p))))
(cond
((eq (car element) stream)
(pop (%concatenated-stream-streams stream))
(!concatenated-read-element
read-element stream eof-error-p eof-value recursive-p))
((second element)
(pop (%concatenated-stream-streams stream))
(multiple-value-bind (line missing-newline-p)
(!concatenated-read-element
read-element stream eof-error-p eof-value recursive-p)
(values (concatenate 'string (first element) line)
missing-newline-p)))
(t (values-list element)))))))
(define-stream-methods concatenated-stream
(read-byte (!concatenated-read-element
(lambda (s e v r) (declare (ignore r)) (read-byte s e v))
stream eof-error-p eof-value nil))
(read-char (!concatenated-read-element
(function read-char)
stream eof-error-p eof-value recursive-p))
(read-char-no-hang (!concatenated-read-element
(function read-char-no-hang)
stream eof-error-p eof-value recursive-p))
(peek-char (!concatenated-read-element
(lambda (s e v r) (peek-char peek-type s e v r))
stream eof-error-p eof-value recursive-p))
(unread-char
(let ((current (first (%concatenated-stream-streams stream))))
(if (null current)
(push (make-string-input-stream (string character))
(%concatenated-stream-streams stream))
(unread-char character current))))
(read-line (!concatenated-read-element
(lambda (s e v r) (declare (ignore r)) (read-line s e v))
stream eof-error-p eof-value recursive-p))
(read-sequence
(let ((current (first (%concatenated-stream-streams stream))))
(if (null current)
(eof-error stream eof-error-p eof-value)
(let* ((end (or end (length sequence)))
(position (read-stream sequence current start end)))
(if (< position end)
(progn
(pop (%concatenated-stream-streams stream))
(setf current (first (%concatenated-stream-streams stream)))
(if (null current)
position
(read-sequence sequence stream :start position :end end)))
position)))))
(listen
(let ((current (first (%concatenated-stream-streams stream))))
(warn "LISTEN may return NIL in the middle of a concatenated-stream when we're at the end of one of the substreams")
(listen current)))
(clear-input
(let ((current (first (%concatenated-stream-streams stream))))
(and current (clear-input current))))
(stream-external-format ;; or use the attribute?
(let ((current (first (%concatenated-stream-streams stream))))
(if current
(stream-external-format current)
:default)))
(close
(prog1 (%open-stream-p stream)
(setf (%open-stream-p stream) nil
(%concatenated-stream-streams stream) nil))))
;;;; THE END ;;;;
| 5,893 | Common Lisp | .lisp | 127 | 38.141732 | 121 | 0.599618 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f738c169a1f961fc92f59bda3ee900d15bdedaa728bdfd371e368a055317a68c | 4,716 | [
-1
] |
4,717 | com.informatimago.common-lisp.virtual-file-system.asd | informatimago_lisp/future/vfs/com.informatimago.common-lisp.virtual-file-system.asd | ;;;; -*- mode:lisp; coding:utf-8 -*-
(asdf:defsystem :com.informatimago.common-lisp.virtual-file-system
:name "Virtual File System"
:description "Implements a RAM-based Virtual File System."
:author "<PJB> Pascal Bourguignon <[email protected]>"
:version "1.2.0"
:licence "GPL"
:properties ((#:author-email . "[email protected]")
(#:date . "Spring 2011")
((#:albert #:output-dir) . "../documentation/com.informatimago.vfs/")
((#:albert #:formats) . ("docbook"))
((#:albert #:docbook #:template) . "book")
((#:albert #:docbook #:bgcolor) . "white")
((#:albert #:docbook #:textcolor) . "black"))
:depends-on (:split-sequence
:cl-ppcre
:com.informatimago.common-lisp.cesarum)
:components ((:file "packages")
(:file "utility" :depends-on ("packages"))
(:file "filenames" :depends-on ("utility"))
(:file "streams" :depends-on ("utility"))
(:file "virtual-fs" :depends-on ("filenames"))
(:file "files" :depends-on ("streams" "filenames" "virtual-fs"))
(:file "vfs-file-stream" :depends-on ("streams" "filenames" "virtual-fs"))
(:file "string-input" :depends-on ("streams" "filenames"))
(:file "string-output" :depends-on ("streams" "filenames"))
(:file "concatenated-stream" :depends-on ("streams" "filenames"))
(:file "broadcast-stream" :depends-on ("streams" "filenames"))
(:file "synonym-stream" :depends-on ("streams" "filenames"))
(:file "two-way-stream" :depends-on ("streams" "filenames"))
(:file "echo-stream" :depends-on ("streams" "filenames"))
(:file "standard-streams" :depends-on ("string-input" "string-output" "two-way-stream"))
(:file "cl-stream" :depends-on ("standard-streams"))
(:file "general" :depends-on ("streams" "filenames" "files"))
;; ---
(:file "initialize" :depends-on ("cl-stream" "virtual-fs"))
))
;;;; THE END ;;;;
| 2,460 | Common Lisp | .lisp | 38 | 50.684211 | 109 | 0.487381 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 999eb7ef93270f83101ab71909b29281899a1a4d65d8669c1a28a5dd26726518 | 4,717 | [
-1
] |
4,718 | packages.lisp | informatimago_lisp/future/vfs/packages.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: vfs-packages.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Defines the vfs packages.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2011-05-22 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2011 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *redefined-symbols*
'(
;; 19. Filenames
"PATHNAME" "LOGICAL-PATHNAME"
"PATHNAME-HOST" "PATHNAME-DEVICE" "PATHNAME-DIRECTORY"
"PATHNAME-NAME" "PATHNAME-TYPE" "PATHNAME-VERSION"
"MAKE-PATHNAME" "PATHNAMEP" "LOGICAL-PATHNAME-TRANSLATIONS"
"LOAD-LOGICAL-PATHNAME-TRANSLATIONS" "LOGICAL-PATHNAME"
"*DEFAULT-PATHNAME-DEFAULTS*" "PARSE-NAMESTRING"
"WILD-PATHNAME-P" "PATHNAME-MATCH-P"
"TRANSLATE-LOGICAL-PATHNAME" "TRANSLATE-PATHNAME" "MERGE-PATHNAMES"
"NAMESTRING" "FILE-NAMESTRING" "DIRECTORY-NAMESTRING" "HOST-NAMESTRING" "ENOUGH-NAMESTRING"
;; 20. Files
"DIRECTORY" "PROBE-FILE" "ENSURE-DIRECTORIES-EXIST" "TRUENAME"
"FILE-AUTHOR" "FILE-WRITE-DATE" "RENAME-FILE" "DELETE-FILE"
;; 21. Streams.
"STREAM" "BROADCAST-STREAM" "CONCATENATED-STREAM" "ECHO-STREAM" "FILE-STREAM"
"STRING-STREAM" "SYNONYM-STREAM" "TWO-WAY-STREAM"
"INPUT-STREAM-P" "OUTPUT-STREAM-P" "INTERACTIVE-STREAM-P"
"OPEN-STREAM-P" "STREAM-ELEMENT-TYPE" "STREAMP" "READ-BYTE"
"WRITE-BYTE" "PEEK-CHAR" "READ-CHAR" "READ-CHAR-NO-HANG" "TERPRI"
"FRESH-LINE" "UNREAD-CHAR" "WRITE-CHAR" "READ-LINE" "WRITE-STRING"
"WRITE-LINE" "READ-SEQUENCE" "WRITE-SEQUENCE" "FILE-LENGTH"
"FILE-POSITION" "FILE-STRING-LENGTH" "OPEN" "STREAM-EXTERNAL-FORMAT"
"WITH-OPEN-FILE" "CLOSE" "WITH-OPEN-STREAM" "LISTEN" "CLEAR-INPUT"
"FINISH-OUTPUT" "FORCE-OUTPUT" "CLEAR-OUTPUT" "Y-OR-N-P" "YES-OR-NO-P"
"MAKE-SYNONYM-STREAM" "SYNONYM-STREAM-SYMBOL"
"BROADCAST-STREAM-STREAMS" "MAKE-BROADCAST-STREAM"
"MAKE-TWO-WAY-STREAM" "TWO-WAY-STREAM-INPUT-STREAM"
"TWO-WAY-STREAM-OUTPUT-STREAM" "ECHO-STREAM-INPUT-STREAM"
"ECHO-STREAM-OUTPUT-STREAM" "MAKE-ECHO-STREAM"
"CONCATENATED-STREAM-STREAMS" "MAKE-CONCATENATED-STREAM"
"GET-OUTPUT-STREAM-STRING" "MAKE-STRING-INPUT-STREAM"
"MAKE-STRING-OUTPUT-STREAM" "WITH-INPUT-FROM-STRING"
"WITH-OUTPUT-TO-STRING" "*DEBUG-IO*" "*ERROR-OUTPUT*" "*QUERY-IO*"
"*STANDARD-INPUT*" "*STANDARD-OUTPUT*" "*TRACE-OUTPUT*"
"*TERMINAL-IO*" "STREAM-ERROR-STREAM"
;; 3. Evaluation and Compilation
"TYPE")))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM"
(:nicknames "VFS" "VIRTUAL-FILE-SYSTEM")
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY"
"COM.INFORMATIMAGO.COMMON-LISP.LISP-SEXP.SOURCE-FORM")
(:shadow . #.*redefined-symbols*)
(:export "INSTALL-PATHNAME-READER-MACRO" "RESET-READTABLE"
"DELETE-DIRECTORY"
"FILE-ELEMENT-TYPE"
"PURGE-FILE" "DELETE-VERSION"
. #.*redefined-symbols*))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM-USER"
(:nicknames "VFS-USER" "VIRTUAL-FILE-SYSTEM-USER")
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM")
(:shadowing-import-from
"COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM"
. #.*redefined-symbols*))
;;;; THE END ;;;;
| 4,677 | Common Lisp | .lisp | 99 | 42.828283 | 97 | 0.652602 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 624e67617c72fa13372dffc2d58ded6d8031838724526022d38499e8a70275c0 | 4,718 | [
-1
] |
4,719 | missing.lisp | informatimago_lisp/mocl/kludges/missing.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: missing.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements CL standard operators missing from MoCL.
;;;;
;;;; !!!! NOTICE THE LICENSE OF THIS FILE !!!!
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-03-01 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING"
(:use "COMMON-LISP")
(:shadow "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:export "*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:documentation "
Implements CL standard operators missing from MoCL.
LEGAL
AGPL3
Copyright Pascal J. Bourguignon 2015 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"))
(in-package "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING")
;; CHANGE-CLASS ;; CLOS!
;; COMPLEX ;; all complex is missing.
(defvar *load-verbose* nil)
(defvar *load-print* nil)
(defvar *trace-output* *standard-output*)
(define-condition print-not-readable (error)
((object :initarg :object :reader print-not-readable-object))
(:report (lambda (condition stream)
(let ((*print-readably* nil))
(format stream "Object to printable readably ~S"
(print-not-readable-object condition))))))
(defun array-displacement (array)
;; if not provided, then displaced array don't exist!
(declare (ignore array))
(values nil 0))
;; COMPILE ;; required to implement minimal compilation.
(defun load (filespec &key verbose print if-does-not-exist external-format)
)
(defun ensure-directories-exist (pathspec &key verbose)
(error "~S not implemented yet" 'ensure-directories-exist)
(let ((created nil))
(values pathspec created)))
(defun rename-file (filespec new-name)
(error "~S not implemented yet" 'rename-file)
(let (defaulted-new-name old-truename new-truename)
(values defaulted-new-name old-truename new-truename)))
(defun file-write-date (pathspec)
(declare (ignore pathspec))
nil)
(defvar *debugger-hook* nil)
(defun invoke-debugger (condition)
(when *debugger-hook*
(let ((saved-hook *debugger-hook*)
(*debugger-hook* nil))
(funcall saved-hook condition)))
(rt:formatd "Debugger invoked on condition ~A; aborting." condition)
(rt:quit))
(defvar *hosts* '())
(defun logical-pathname-translations (host)
(cdr (assoc host *hosts* :test (function equalp))))
(defun (setf logical-pathname-translations) (new-translations host)
(let ((entry (assoc host *hosts* :test (function equalp))))
(if entry
(setf (cdr entry) (copy-tree new-translations))
(push (cons (nstring-upcase (copy-seq host))
(copy-tree new-translations))
*hosts*))))
(defun translate-logical-pathname (pathname &key &allow-other-keys)
(error "~S not implemented yet" 'translate-logical-pathname)
pathname)
(defun machine-instance ()
;; TODO: find the hostname of the machine, or some other machine identification.
#+android "Android"
#+ios "iOS")
(defun machine-version ()
;; TODO: find the hardware version, or some other machine version.
#+android "0.0"
#+ios "0.0")
;; Clozure Common Lisp --> ("larissa.local" "MacBookAir6,2")
;; CLISP --> ("larissa.local [192.168.7.8]" "X86_64")
;; ECL --> ("larissa.local" NIL)
;; SBCL --> ("larissa.local" "Intel(R) Core(TM) i7-4650U CPU @ 1.70GHz")
(defun nset-difference (list-1 list-2 &rest rest &key key test test-not)
(declare (ignore key test test-not))
(apply (function set-difference) list-1 list-2 rest))
(defun nsubstitute-if (new-item predicate sequence &key from-end start end count key)
(let* ((length (length sequence))
(start (or start 0))
(end (or end lengh))
(key (or key (function identity))))
(assert (<= 0 start end length))
(etypecase sequence
(list (cond
(from-end
(nreverse (nsubstitute-if new-item predicate (nreverse sequence)
:start (- length end) :end (- length start)
:count count :key key)))
(count
(when (plusp count)
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item)
(decf count)
(when (zerop count)
(return))))))
(t
(loop
:repeat (- end start)
:for current :on (nthcdr start sequence)
:do (when (funcall predicate (funcall key (car current)))
(setf (car current) new-item))))))
(vector (if from-end
(if count
(when (plusp count)
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from (1- end) :downto start
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item))))
(if count
(when (plusp count)
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)
(decf count)
(when (zerop count)
(return)))))
(loop
:for i :from start :below end
:do (when (funcall predicate (funcall key (aref sequence i)))
(setf (aref sequence i) new-item)))))))
sequence))
(defun substitute-if (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item predicate (copy-seq sequence) rest))
(defun nsubstitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) sequence rest))
(defun substitute-if-not (new-item predicate sequence &rest rest &key from-end start end count key)
(apply (function nsubstitute-if) new-item (complement predicate) (copy-seq sequence) rest))
;; Warning: Function ASDF:FIND-SYSTEM is referenced but not defined.
;; Warning: Function ASDF:GETENV is referenced but not defined.
;; Warning: Function ASDF:RUN-SHELL-COMMAND is referenced but not defined.
;;;; THE END ;;;;
| 10,100 | Common Lisp | .lisp | 227 | 35.057269 | 100 | 0.577721 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 0bdd036942d222e518550ca40277b77a4388a69601e7c06fa312c8906268b3ed | 4,719 | [
-1
] |
4,720 | rename-asdf-systems.lisp | informatimago_lisp/mocl/kludges/rename-asdf-systems.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: rename-asdf-systems.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Kludge for MoCL: rename asdf systems substituting exclaims for dots.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-11-24 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2013 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.MOCL.KLUDGES.RENAME-ASDF-SYSTEMS"
(:use "COMMON-LISP")
(:export "GENERATE-RENAMED-SYSTEMS-FROM-DIRECTORY"))
(in-package "COM.INFORMATIMAGO.MOCL.KLUDGES.RENAME-ASDF-SYSTEMS")
(defconstant +replacement+ #\!)
(defun rename-system-name (name)
(etypecase name
(string (substitute +replacement+ #\. name))
(symbol (intern (substitute +replacement+ #\. (string name))
(load-time-value (find-package "KEYWORD"))))))
(defun process-component (component)
(assert (listp component))
(destructuring-bind (type name &rest options) component
(case type
((:module)
(list* type (rename-system-name name)
(process-options options)))
(otherwise
component))))
(defun process-options (options)
(loop
:for (key value) :on options :by (function cddr)
:collect key
:collect (case key
((:defsystem-depends-on)
(mapcar (function rename-system-name) value))
((:weakly-depends-on)
(mapcar (function rename-system-name) value))
((:depends-on)
(mapcar (lambda (component)
(cond
((atom component)
(rename-system-name component))
((eq :version (first component))
(list (first component)
(rename-system-name (second component))
(third component)))
(t
component)))
value))
((:in-order-to)
(mapcar (lambda (dependency)
(assert (listp dependency))
(cons (first dependency)
(mapcar (lambda (requirement)
(assert (listp requirement))
(cond
((eq :feature (first requirement))
requirement)
(t
(cons (first requirement)
(mapcar (function process-component)
(rest requirement))))))
(rest dependency))))
value))
((:components)
(mapcar (function process-component) value))
(otherwise value))))
(defun rename-systems (defsystem-form)
(assert (and (listp defsystem-form)
(eq 'asdf:defsystem (first defsystem-form))))
(destructuring-bind (defsystem system &rest options) defsystem-form
`(,defsystem ,(rename-system-name system)
,@(process-options options))))
(defun replace-asdf/defsystem (sexp-text)
(let* ((target "asdf/defsystem")
(pos (search target sexp-text)))
(concatenate 'string (subseq sexp-text 0 pos)
"asdf"
(subseq sexp-text (+ pos (length target))))))
(defun process-asd-file (path)
(let ((name (pathname-name path)))
(when (position #\. name)
(with-standard-io-syntax
(let* ((new-name (substitute +replacement+ #\. name))
(new-path (make-pathname :name new-name :defaults path))
(*package* (find-package "COMMON-LISP-USER"))
(*features* (remove :asdf-unicode *features*))
(*print-case* :downcase))
(with-open-file (out new-path
:direction :output
:if-does-not-exist :create
:if-exists :supersede
:external-format :iso-8859-1)
(with-open-file (inp path
:direction :input
:if-does-not-exist :error
:external-format :iso-8859-1)
(loop
:for sexp = (read inp nil inp)
:until (eq sexp inp)
:do (cond
((and (listp sexp)
(eql 'cl:in-package (first sexp)))
(setf *package* (find-package (second sexp)))
(print sexp out))
((and (listp sexp)
(eql 'asdf:defsystem (first sexp)))
(terpri out)
(princ (replace-asdf/defsystem (prin1-to-string (rename-systems sexp))) out))
(t
(print sexp out)))))))))))
(defun generate-renamed-systems-from-directory (directory)
(map nil (function process-asd-file)
(directory (merge-pathnames "**/*.asd" directory nil))))
;; (com.informatimago.mocl.kludges.rename-asdf-systems:generate-renamed-systems-from-directory #P"~/src/public/lisp/")
;;;; THE END ;;;;
| 6,566 | Common Lisp | .lisp | 142 | 32.535211 | 118 | 0.505224 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 171a4a060f949adf26ed056b27453afc198918775f3872077b1310bc9192b196 | 4,720 | [
-1
] |
4,721 | pgl-test.lisp | informatimago_lisp/pgl/pgl-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: pgl-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Tests interactively the PGL.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-11-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "PGL")
(defun test/string-escape ()
(assert (string= (string-escape (coerce #(#\bel #\bs #\page #\newline #\return #\tab #\vt #\" #\\) 'string))
"\"\\a\\b\\f\\n\\r\\t\\v\\042\\\\\""))
(assert (string= (string-unescape "\"\\a\\b\\f\\n\\r\\t\\v\\042\\\\\"")
(coerce #(#\bel #\bs #\page #\newline #\return #\tab #\vt #\" #\\) 'string)))
(assert (string= (string-escape "Hello\\ World\"!")
"\"Hello\\\\ World\\042!\""))
(assert (string= (string-unescape "\"Hello\\\\ World\\042!\"")
"Hello\\ World\"!"))
:success)
(defun test/scanner ()
(assert (equal (let ((s (make-scanner " hello(\"Howdy\", 42,-123.456e+78,false,true,foo)")))
(loop
:for token := (next-token s)
:while token :collect token))
'((symbol . "hello")
#\( "Howdy" #\, 42 #\, -1.2345600000000003D+80 #\,
(boolean) #\, (boolean . t) #\, (symbol . "foo") #\))))
:success)
(defun test/all ()
(test/string-escape)
(test/scanner))
(defun test-event-loop ()
(unwind-protect
(loop :for e := (get-next-event +any-event+)
:when e
:do (format *console-io* "~&~20,3F Got event ~A for window ~A~%"
(event-time e) (event-type-keyword e) (event-window e))
(case (event-type-keyword e)
(:window-closed (loop-finish))
(:window-resized)
(:last-window-closed (loop-finish))
(:action-performed
(scase (event-action-command e)
(("OK") (format *console-io* "~&Yay!~%"))
(("TEXT") (format *console-io* "~&Got text: ~S~%"
(text *t*)))
(otherwise (format *console-io* "~&Got action ~S~%"
(event-action-command e)))))
(:mouse-clicked)
(:mouse-pressed)
(:mouse-released)
(:mouse-moved)
(:mouse-dragged)
(:key-pressed)
(:key-released)
(:key-typed)
(:timer-ticked)))
(format *console-io* "~2%Test Event Loop Done.~2%")))
(defun make-test-window-1 ()
(let ((w 512)
(h 342))
(make-instance
'window
:x 20 :y 40
:width w :height h
:components (loop
:repeat 20
:collect (make-instance
(elt #(rect round-rect oval line)
(random 4))
:x (random (- w 20.0d0))
:y (random (- h 20.0d0))
:width (+ 20 (random 100.0d0))
:height (+ 20 (random 100.0d0))
:color (elt *colors* (random (length *colors*)))
:fill-color (elt *colors* (random (length *colors*)))
:line-width (random 10.0d0)
:filled (zerop (random 2)))))))
'(
(ccl:setenv "JBETRACE" "true" t)
(ccl:setenv "JBETRACE" "false" t)
(close-backend)
(open-backend :program-name "Test Program")
(defparameter *w* (make-instance 'window :title "Test Window"
:width 512.0d0
:height 342.0d0
:x 50.0d0
:y 50.0d0))
(progn
(compound-add *w* (make-instance 'label :text "Text:"
:x 10 :y 40 :width 100 :height 20))
(let ((tf (make-instance 'text-field :nchars 20 :action-command "TEXT"
:x 60 :y 60 :width 100 :height 20)))
(compound-add *w* tf)
(set-text tf "Doctor Who")
(defparameter *t* tf))
(compound-add *w* (make-instance 'button :label "OK" :action-command "OK"
:x 10 :y 60 :width 60 :height 20))
(defparameter *c* (make-instance 'chooser :items '("Red" "Green" "Blue")
:x 20 :y 80))
(compound-add *c*))
(compound-remove *w* (aref (components *w*) 2))
(defparameter *l1* (aref (components *w*) 0))
(defparameter *t1* (aref (components *w*) 1))
(defparameter *l2* (aref (components *w*) 2))
(defparameter *t2* (aref (components *w*) 3))
(progn
(set-window-resizable *w*)
(progn (set-object-size *w* 512 342)
(repaint-windows)
(set-object-location *w* 30 30))
(progn (set-object-location *l1* 10 40) (set-object-location *t1* 50 20))
(set-object-location *l2* 10 70) (set-object-location *t2* 50 50)
(set-object-location (aref (components *w*) 2) 60 60)
(components *w*)
(text *t1*)"Doctor Who and the Daleks")
(object.contains *w* 11.0d0 61.0d0)
)
;;;; THE END ;;;;
| 6,618 | Common Lisp | .lisp | 146 | 33.143836 | 110 | 0.477586 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c0fb1130b33d5467e60f3b3122f5f0bed31f549c87b2311b1259913116953824 | 4,721 | [
-1
] |
4,722 | felt-board.lisp | informatimago_lisp/pgl/examples/felt-board.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: felt-board.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Example taken from https://cs.stanford.edu/people/eroberts/jtf/tutorial/UsingTheGraphicsPackage.html
;;;;
;;;; This program offers a simple example of the acm.graphics package
;;;; that draws a red rectangle and a green oval. The dimensions of
;;;; the rectangle are chosen so that its sides are in proportion to
;;;; the "golden ratio" thought by the Greeks to represent the most
;;;; aesthetically pleasing geometry.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-11-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.FELT-BOARD"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY")
(:export "RUN"))
(in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.FELT-BOARD")
(defun run ()
(let* ((phi 1.618)
(win (make-instance 'window :width 512 :height 342
:title "Felt Board"))
(rect (make-instance 'rect :x 100 :y 50 :width 100 :height (/ 100 phi)))
(oval (make-instance 'oval :x 150 :y (+ 50 (/ 50 phi)) :width 100 :height (/ 100 phi))))
(set-filled rect t)
(set-color rect *orange*)
(set-fill-color rect *red*)
(compound-add win rect)
(set-filled oval t)
(set-color oval *blue*)
(set-fill-color oval *green*)
(compound-add win oval)))
;;;; THE END ;;;;
| 2,688 | Common Lisp | .lisp | 61 | 41.295082 | 108 | 0.618521 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a6de1753098d749c69cbccd38c240322a79a04535ca734b5d28140f9785d90df | 4,722 | [
-1
] |
4,723 | angles.lisp | informatimago_lisp/pgl/examples/angles.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: angles.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2017-02-26 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2017 - 2017
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.ANGLES"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY")
(:export "RUN"))
(in-package "COM.INFORMATIMAGO.PORTABLE-GRAPHICS-LIBRARY.EXAMPLE.ANGLES")
(defstruct problem
points
angles)
(defun problem-n (p)
(length (problem-points p)))
(defun point (p i)
(aref (problem-points p) (mod i (problem-n p))))
(defun point-x (p) (realpart p))
(defun point-y (p) (imagpart p))
(defun angle (p q r)
"Angle between QP and QR"
(phase (/ (- r q)
(- p q))))
(defun compute-angles (p)
(loop
:with n := (problem-n p)
:with r := (make-array n)
:for i :from -1
:for j :from 0 :below n
:for k :from 1
:do (setf (aref r j) (angle (point p i) (point p j) (point p k)))
:finally (return r)))
(defun create-points (npoints)
(loop :with r := (cis (/ (* 2.0d0 pi) npoints))
:with v := (make-array npoints)
:for i :below npoints
:for p := #C(1.0d0 0.0d0) :then (* p r)
:do (setf (aref v i) p)
:finally (return v)))
(defun symetric (p c)
(- (+ c c) p))
;; (compute-angles (make-problem :points (create-points 19)))
(defparameter *size* 50)
(defparameter *point-size* 5)
(defun make-display-point (point cx cy)
(let ((x (+ cx (round (point-x point))))
(y (+ cy (round (point-y point)))))
(make-instance 'oval :x x :y y :width *point-size* :height *point-size* :filled t)))
(defmacro dovector ((var vector &optional result) &body body)
(let ((vvector (gensym "vector"))
(vindex (gensym "index"))
(vlength (gensym "length")))
`(block nil
(let* ((,vvector ,vector)
(,vlength (length ,vvector))
(,vindex -1))
(tagbody
(go :test)
:loop
(let ((,var (aref ,vvector ,vindex)))
,@body)
:test
(incf ,vindex)
(if (< ,vindex ,vlength)
(go :loop))
(return ,result))))))
(defun square (x) (* x x))
(defun closest-point (x0 y0 ovals)
(loop
:with offset := (/ *point-size* 2)
:with min-o := nil
:with min-d := nil
:for o :across ovals
:for x1 := (+ (x o) offset)
:for y1 := (+ (y o) offset)
:for d := (sqrt (+ (square (- x0 x1)) (square (- y0 y1))))
:do (when (or (null min-d)
(< d min-d))
(setf min-d d
min-o o))
:finally (return min-o)))
(defun run (&optional (npoints 3))
(let* ((prob (make-problem :points (map 'vector (lambda (p) (* p *size*)) (create-points npoints))))
(win (make-instance 'window :width 512 :height 342 :title "Problem"
:resizable t))
(cx (truncate (width win) 2))
(cy (truncate (height win) 2))
(ovals (map 'vector (lambda (point)
(let ((oval (make-display-point point cx cy)))
(compound-add win oval)
oval))
(problem-points prob))))
(loop
:with state := 'select-center
:with selected := nil
:for event := (get-next-event (logior +click-event+ +window-event+))
:do (case (event-type-keyword event)
(:window-closed
(print :window-closed)
(loop-finish))
(:window-resized
(print :window-resized)
(let* ((nx (truncate (width win) 2))
(ny (truncate (height win) 2))
(dx (- nx cx))
(dy (- ny cy)))
(setf cx nx
cy ny)
(dovector (o ovals)
(let ((p (location o)))
(print (list (+ (x p) dx) (+ (y p) dy)))
(set-location o (+ (x p) dx) (+ (y p) dy))))))
(:mouse-clicked
(print (list :mouse-clicked (event-x event) (event-y event)))
(let ((o (closest-point (event-x event) (event-y event) ovals)))
(when o
(case state
((select-center)
(setf selected o)
(set-color selected *red*)
(print selected)
(setf state 'select-permuted))
((select-permuted)
(unless (eql selected o)
(print o)
(let* ((si (position selected ovals))
(so (position o ovals))
(new (symetric (point prob so) (point prob si))))
(setf (aref (problem-points prob) so) new)
(set-location o (+ cx (truncate (point-x new))) (+ cy (truncate (point-y new))))
(print (list (+ cx (truncate (point-x new))) (+ cy (truncate (point-y new)))))))
(set-color selected *black*)
(setf selected nil)
(setf state 'select-center)))))))))
(close-backend))
;;;; THE END ;;;;
| 6,525 | Common Lisp | .lisp | 164 | 30.768293 | 104 | 0.508437 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b686311bd7946ed9229d93e953169898f3fc6de0b70cba9eb5f9b25adbdad2b7 | 4,723 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.