1;;; inversion.el --- When you need something in version XX.XX  -*- lexical-binding: t; -*-
2
3;; Copyright (C) 2002-2021  Free Software Foundation, Inc.
4
5;; Author: Eric M. Ludlam <zappo@gnu.org>
6;; Version: 1.3
7;; Keywords: OO, lisp
8;; Obsolete-since: 28.1
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software: you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
24
25;;; Commentary:
26;;
27;; Keeping track of rapidly developing software is a tough thing to
28;; do, especially if you want to have co-dependent packages which all
29;; move at different rates.
30;;
31;; This library provides a framework for specifying version numbers
32;; and (as side effect) have a flexible way of getting a desired feature set.
33;;
34;; If you would like to use this package to satisfy dependency replace this:
35;;
36;; (require 'spiffy)
37;;
38;; with this:
39;;
40;; (require 'inversion)
41;; (inversion-require 'spiffy "1.0")
42;;
43;; If you feel the need to not throw errors, you can do this instead:
44;;
45;; (let ((err (inversion-test 'spiffy "1.0")))
46;;    (if err (your-stuff-here)))
47;;
48;; If you new package (2.0) needs to make sure a load file from your
49;; package is compatible, use this test:
50;;
51;; (if (not (inversion-reverse-test 'spiffy version-from-file))
52;;       ;; Everything ok
53;;       (do stuff)
54;;    ;; Out of date
55;;    (import-old-code))
56;;
57;; If you would like to make inversion optional, do this:
58;;
59;; (or (require 'inversion nil t)
60;;     (defun inversion-test (p v)
61;;       (string= v (symbol-value
62;; 		  (intern-soft (concat (symbol-string p) "-version"))))))
63;;
64;; Or modify to specify `inversion-require' instead.
65;;
66;; TODO:
67;;  Offer to download newer versions of a package.
68
69;;; History:
70;;
71;; Sept 3, 2002:  First general publication.
72
73;;; Code:
74
75(defvar inversion-version "1.3"
76  "Current version of InVersion.")
77
78(defvar inversion-incompatible-version "0.1alpha1"
79  "An earlier release which is incompatible with this release.")
80
81(defconst inversion-decoders
82  '(
83    (alpha  "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.?\\([0-9]*\\)\\s-*\\.?alpha\\([0-9]+\\)?$" 4)
84    (beta   "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.?\\([0-9]*\\)\\s-*\\.?beta\\([0-9]+\\)?$" 4)
85    (beta   "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.?\\([0-9]*\\)\\s-*\\.?(beta\\([0-9]+\\)?)$" 4)
86    (beta  "^[^/]+/\\w+--\\w+--\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)--patch-\\([0-9]+\\)" 4)
87    (beta "^\\w+: v\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)-\\([0-9]+\\)-\\(.*\\)" 5)
88    (prerelease "^\\([0-9]+\\)\\.\\([0-9]+\\)\\s-*\\.?pre\\([0-9]+\\)?$" 3)
89    (full   "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.?\\([0-9]+\\)?$" 3)
90    (fullsingle "^\\([0-9]+\\)$" 1)
91    (patch  "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.?\\([0-9]+\\)?\\s-*(patch \\([0-9]+\\))" 4)
92    (point  "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)$" 3)
93    (point "^\\w+: v\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)-\\(0\\)-\\(.*\\)" 5)
94    (build  "^\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\).\\([0-9]+\\)$" 4)
95    (full   "^[^/]+/\\w+--\\w+--\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)--version-\\([0-9]+\\)" 4)
96    (full "^\\w+: v\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)" 5)
97    )
98  "List of decoders for version strings.
99Each decoder is of the form:
100
101  ( RELEASE-TYPE REGEXP MAX )
102
103RELEASE-TYPE is a symbol specifying something like `beta' or `alpha'.
104REGEXP is the regular expression to match a version string.
105MAX is the maximum number of match-numbers in the release number.
106Decoders must be ordered to decode least stable versions before the
107more stable ones.")
108
109;;; Version Checking
110;;
111(defun inversion-decode-version (version-string)
112  "Decode VERSION-STRING into an encoded list.
113Return value is of the form:
114  (RELEASE MAJOR MINOR ...)
115where RELEASE is a symbol such as `full', or `beta'."
116  (let ((decoders inversion-decoders)
117	(result nil))
118    (while (and decoders (not result))
119      (if (string-match (nth 1 (car decoders)) version-string)
120	  (let ((ver nil)
121		(num-left (nth 2 (car decoders)))
122		(count 1))
123	    (while (<= count num-left)
124	      (setq ver (cons
125			 (if (match-beginning count)
126			     (string-to-number
127			      (substring version-string
128					 (match-beginning count)
129					 (match-end count)))
130			   1)
131			 ver)
132		    count (1+ count)))
133	    (setq result (cons (caar decoders) (nreverse ver))))
134        (setq decoders (cdr decoders))))
135    result))
136
137(defun inversion-package-version (package)
138  "Return the decoded version for PACKAGE."
139  (let ((ver (symbol-value
140	      (intern-soft
141	       (concat (symbol-name package)
142		       "-version"))))
143	(code nil))
144    (unless ver
145      (error "Package %S does not define %S-version" package package))
146    ;; Decode the code
147    (setq code (inversion-decode-version ver))
148    (unless code
149      (error "%S-version value (%s) cannot be decoded" package ver))
150    code))
151
152(defun inversion-package-incompatibility-version (package)
153  "Return the decoded incompatibility version for PACKAGE.
154The incompatibility version is specified by the programmer of
155a package when a package is not backward compatible.  It is
156not an indication of new features or bug fixes."
157  (let ((ver (symbol-value
158	      (intern-soft
159	       (concat (symbol-name package)
160		       "-incompatible-version")))))
161    (if (not ver)
162	nil
163      ;; Decode the code
164      (inversion-decode-version ver))))
165
166(defun inversion-recode (code)
167  "Convert CODE into a string."
168  (let ((r (nth 0 code))		; release-type
169	(n (nth 1 code))		; main number
170	(i (nth 2 code))		; first increment
171	(p (nth 3 code)))		; second increment
172    (cond
173     ((eq r 'full)
174      (setq r "" p ""))
175     ((eq r 'point)
176      (setq r ".")))
177    (format "%s.%s%s%s" n i r p)))
178
179(defun inversion-release-to-number (release-symbol)
180  "Convert RELEASE-SYMBOL into a number."
181  (let* ((ra (assoc release-symbol inversion-decoders))
182	 (rn (- (length inversion-decoders)
183		(length (member ra inversion-decoders)))))
184    rn))
185
186(defun inversion-= (ver1 ver2)
187  "Return non-nil if VER1 is equal to VER2."
188  (equal ver1 ver2))
189
190(defun inversion-< (ver1 ver2)
191  "Return non-nil if VER1 is less than VER2."
192  (let ((v1-0 (inversion-release-to-number (nth 0 ver1)))
193	(v1-1 (nth 1 ver1))
194	(v1-2 (nth 2 ver1))
195	(v1-3 (nth 3 ver1))
196	(v1-4 (nth 4 ver1))
197	;; v2
198	(v2-0 (inversion-release-to-number (nth 0 ver2)))
199	(v2-1 (nth 1 ver2))
200	(v2-2 (nth 2 ver2))
201	(v2-3 (nth 3 ver2))
202	(v2-4 (nth 4 ver2))
203	)
204
205    (cond ((and (equal (list v1-1 v1-2 v1-3 v1-4)
206		       (list v2-1 v2-2 v2-3 v2-4))
207		v1-0 v2-0)
208	   (< v1-0 v2-0))
209	  ((and (equal v1-1 v2-1)
210		(equal v1-2 v2-2)
211		(equal v1-3 v2-3)
212		v1-4 v2-4)		; all or nothing if elt - is =
213	     (< v1-4 v2-4))
214	  ((and (equal v1-1 v2-1)
215		(equal v1-2 v2-2)
216		v1-3 v2-3)		; all or nothing if elt - is =
217	     (< v1-3 v2-3))
218	  ((and (equal v1-1 v2-1)
219		v1-2 v2-2)
220	     (< v1-2 v2-2))
221	  ((and v1-1 v2-1)
222	   (< v1-1 v2-1))
223	)))
224
225(defun inversion-check-version (version incompatible-version
226                                minimum &rest _reserved)
227  "Check that a given version meets the minimum requirement.
228VERSION, INCOMPATIBLE-VERSION and MINIMUM are of similar format to
229return entries of `inversion-decode-version', or a classic version
230string.  INCOMPATIBLE-VERSION can be nil.
231RESERVED arguments are kept for a later use.
232Return:
233- nil if everything is ok.
234- `outdated' if VERSION is less than MINIMUM.
235- `incompatible' if VERSION is not backward compatible with MINIMUM.
236- t if the check failed."
237  (let ((code (if (stringp version)
238		  (inversion-decode-version version)
239		version))
240	(req (if (stringp minimum)
241		 (inversion-decode-version minimum)
242	       minimum))
243	)
244    ;; Perform a test.
245    (cond
246     ((inversion-= code req)
247      ;; Same version.. Yay!
248      nil)
249     ((inversion-< code req)
250      ;; Version is too old!
251      'outdated)
252     ((inversion-< req code)
253      ;; Newer is installed.  What to do?
254      (let ((incompatible
255	     (if (stringp incompatible-version)
256		 (inversion-decode-version incompatible-version)
257	       incompatible-version)))
258	(cond
259	 ((not incompatible) nil)
260	 ((or (inversion-= req incompatible)
261	      (inversion-< req incompatible))
262	  ;; The requested version is = or < than what the package
263	  ;; maintainer says is incompatible.
264	  'incompatible)
265	 ;; Things are ok.
266	 (t nil))))
267     ;; Check failed
268     (t t))))
269
270(defun inversion-test (package minimum &rest reserved)
271  "Test that PACKAGE meets the MINIMUM version requirement.
272PACKAGE is a symbol, similar to what is passed to `require'.
273MINIMUM is of similar format to return entries of
274`inversion-decode-version', or a classic version string.
275RESERVED arguments are kept for a later user.
276This depends on the symbols `PACKAGE-version' and optionally
277`PACKAGE-incompatible-version' being defined in PACKAGE.
278Return nil if everything is ok.  Return an error string otherwise."
279  (let ((check (inversion-check-version
280		(inversion-package-version package)
281		(inversion-package-incompatibility-version package)
282		minimum reserved)))
283    (cond
284     ((null check)
285      ;; Same version.. Yay!
286      nil)
287     ((eq check 'outdated)
288      ;; Version is too old!
289      (format "You need to upgrade package %s to %s" package minimum))
290     ((eq check 'incompatible)
291      ;; Newer is installed but the requested version is = or < than
292      ;; what the package maintainer says is incompatible, then throw
293      ;; that error.
294      (format "Package %s version is not backward compatible with %s"
295	      package minimum))
296     ;; Check failed
297     (t "Inversion version check failed."))))
298
299(defun inversion-reverse-test (package oldversion &rest reserved)
300  "Test that PACKAGE at OLDVERSION is still compatible.
301If something like a save file is loaded at OLDVERSION, this
302test will identify if OLDVERSION is compatible with the current version
303of PACKAGE.
304PACKAGE is a symbol, similar to what is passed to `require'.
305OLDVERSION is of similar format to return entries of
306`inversion-decode-version', or a classic version string.
307RESERVED arguments are kept for a later user.
308This depends on the symbols `PACKAGE-version' and optionally
309`PACKAGE-incompatible-version' being defined in PACKAGE.
310Return nil if everything is ok.  Return an error string otherwise."
311  (let ((check (inversion-check-version
312		(inversion-package-version package)
313		(inversion-package-incompatibility-version package)
314		oldversion reserved)))
315    (cond
316     ((null check)
317      ;; Same version.. Yay!
318      nil)
319     ((eq check 'outdated)
320      ;; Version is too old!
321      (format "Package %s version %s is not compatible with current version"
322	      package oldversion))
323     ((eq check 'incompatible)
324      ;; Newer is installed but the requested version is = or < than
325      ;; what the package maintainer says is incompatible, then throw
326      ;; that error.
327      (format "Package %s version is not backward compatible with %s"
328	      package oldversion))
329     ;; Check failed
330     (t "Inversion version check failed."))))
331
332(defun inversion-require (package version &optional file directory
333				  &rest _reserved)
334  "Declare that you need PACKAGE with at least VERSION.
335PACKAGE might be found in FILE.  (See `require'.)
336Throws an error if VERSION is incompatible with what is installed.
337Optional argument DIRECTORY is a location where new versions of
338this tool can be located.  If there is a versioning problem and
339DIRECTORY is provided, inversion will offer to download the file.
340Optional argument RESERVED is saved for later use."
341  (require package file)
342  (let ((err (inversion-test package version)))
343    (when err
344      (if directory
345	  (inversion-download-package-ask err package directory version)
346	(error err)))
347    ;; Return the package symbol that was required.
348    package))
349
350;;;###autoload
351(defun inversion-require-emacs (emacs-ver xemacs-ver sxemacs-ver)
352  "Declare that you need either EMACS-VER, XEMACS-VER or SXEMACS-ver.
353Only checks one based on which kind of Emacs is being run.
354
355This function is obsolete; do this instead:
356    (when (version<= \"28.1\" emacs-version) ...)"
357  (declare (obsolete nil "28.1"))
358  (let ((err (inversion-test 'emacs
359			     (cond ((featurep 'sxemacs)
360				    sxemacs-ver)
361				   ((featurep 'xemacs)
362				    xemacs-ver)
363				   (t
364				    emacs-ver)))))
365    (if err (error err)
366      ;; Something nice...
367      t)))
368
369(defconst inversion-find-data
370  '("(def\\(var\\|const\\)\\s-+%s-%s\\s-+\"\\([^\"]+\\)" 2)
371  "Regexp template and match data index of a version string.")
372
373(defun inversion-find-version (package)
374  "Search for the version and incompatible version of PACKAGE.
375Does not load PACKAGE nor requires that it has been previously loaded.
376Search in the directories in `load-path' for a PACKAGE.el library.
377Visit the file found and search for the declarations of variables or
378constants `PACKAGE-version' and `PACKAGE-incompatible-version'.  The
379value of these variables must be a version string.
380
381Return a pair (VERSION-STRING . INCOMPATIBLE-VERSION-STRING) where
382INCOMPATIBLE-VERSION-STRING can be nil.
383Return nil when VERSION-STRING was not found."
384  (let* ((file (locate-library (format "%s.el" package) t))
385	 (tag (car inversion-find-data))
386	 (idx (nth 1 inversion-find-data))
387	 version)
388    (when file
389      (with-temp-buffer
390	;; The 3000 is a bit arbitrary, but should cut down on
391	;; fileio as version info usually is at the very top
392	;; of a file.  After a long commentary could be bad.
393	(insert-file-contents-literally file nil 0 3000)
394	(goto-char (point-min))
395	(when (re-search-forward (format tag package 'version) nil t)
396	  (setq version (list (match-string idx)))
397	  (goto-char (point-min))
398	  (when (re-search-forward
399		 (format tag package 'incompatible-version) nil t)
400	    (setcdr version (match-string idx))))))
401    version))
402
403(defun inversion-add-to-load-path (package minimum
404					   &optional installdir
405					   &rest subdirs)
406  "Add the PACKAGE path to `load-path' if necessary.
407MINIMUM is the minimum version requirement of PACKAGE.
408Optional argument INSTALLDIR is the base directory where PACKAGE is
409installed.  It defaults to `default-directory'/PACKAGE.
410SUBDIRS are sub-directories to add to `load-path', following the main
411INSTALLDIR path."
412  (let ((ver (inversion-find-version package)))
413    ;; If PACKAGE not found or a bad version already in `load-path',
414    ;; prepend the new PACKAGE path, so it will be loaded first.
415    (when (or (not ver)
416              (and
417               (inversion-check-version (car ver) (cdr ver) minimum)
418               (message "Outdated %s %s shadowed to meet minimum version %s"
419                        package (car ver) minimum)
420               t))
421      (let* ((default-directory
422               (or installdir
423                   (expand-file-name (format "./%s" package))))
424             subdir)
425        (when (file-directory-p default-directory)
426          ;; Add SUBDIRS
427          (while subdirs
428            (setq subdir  (expand-file-name (car subdirs))
429                  subdirs (cdr subdirs))
430            (when (file-directory-p subdir)
431              ;;(message "%S added to `load-path'" subdir)
432              (add-to-list 'load-path subdir)))
433          ;; Add the main path
434          ;;(message "%S added to `load-path'" default-directory)
435          (add-to-list 'load-path default-directory))
436	;; We get to this point iff we do not accept or there is no
437	;; system file.  Let's check the version of what we just
438	;; installed... just to be safe.
439	(let ((newver (inversion-find-version package)))
440	  (if (not newver)
441	      (error "Failed to find version for newly installed %s"
442		     package))
443	  (if (inversion-check-version (car newver) (cdr newver) minimum)
444	      (error "Outdated %s %s just installed" package (car newver)))
445	  )))))
446
447;;; URL and downloading code
448;;
449(defun inversion-locate-package-files (package directory &optional version)
450  "Get a list of distributions of PACKAGE from DIRECTORY.
451DIRECTORY can be an ange-ftp compatible filename, such as:
452 \"/ftp@ftp1.sourceforge.net/pub/sourceforge/PACKAGE\"
453If it is a URL, wget will be used for download.
454Optional argument VERSION will restrict the list of available versions
455to the file matching VERSION exactly, or nil."
456;;DIRECTORY should also allow a URL:
457;; \"https://ftp1.sourceforge.net/PACKAGE\"
458;; but then I can get file listings easily.
459  (if (symbolp package) (setq package (symbol-name package)))
460  (directory-files directory t
461		   (if version
462		       (concat "^" package "-" version "\\>")
463		     package)))
464
465(defvar inversion-package-common-tails '( ".tar.gz"
466					 ".tar"
467					 ".zip"
468					 ".gz"
469					 )
470  "Common distribution mechanisms for Emacs Lisp packages.")
471
472(defun inversion-locate-package-files-and-split (package directory &optional version)
473  "Use `inversion-locate-package-files' to get a list of PACKAGE files.
474DIRECTORY is the location where distributions of PACKAGE are.
475VERSION is an optional argument specifying a version to restrict to.
476The return list is an alist with the version string in the CAR,
477and the full path name in the CDR."
478  (if (symbolp package) (setq package (symbol-name package)))
479  (let ((f (inversion-locate-package-files package directory version))
480	(out nil))
481    (while f
482      (let* ((file (car f))
483	     (dist (file-name-nondirectory file))
484	     (tails inversion-package-common-tails)
485	     (verstring nil))
486	(while (and tails (not verstring))
487	  (when (string-match (concat (car tails) "$") dist)
488	    (setq verstring
489		  (substring dist (1+ (length package)) (match-beginning 0))))
490	  (setq tails (cdr tails)))
491	(if (not verstring)
492	    (error "Cannot decode version for %s" dist))
493	(setq out
494	      (cons
495	       (cons verstring file)
496	       out))
497	(setq f (cdr f))))
498    out))
499
500(defun inversion-download-package-ask (err package directory version)
501  "Due to ERR, offer to download PACKAGE from DIRECTORY.
502The package should have VERSION available for download."
503  (if (symbolp package) (setq package (symbol-name package)))
504  (let ((files (inversion-locate-package-files-and-split
505		package directory version)))
506    (if (not files)
507	(error err)
508      (if (not (y-or-n-p (concat err ": Download update? ")))
509	  (error err)
510	(let ((dest (read-directory-name (format "Download %s to: "
511						 package)
512					 t)))
513	  (if (> (length files) 1)
514	      (setq files
515		    (list
516		     "foo" ;; ignored
517		     (read-file-name "Version to download: "
518				     directory
519				     files
520				     t
521				     (concat
522				      (file-name-as-directory directory)
523				      package)
524				     nil))))
525
526	  (copy-file (cdr (car files)) dest))))))
527
528(provide 'inversion)
529
530;;; inversion.el ends here
531