Contents in 1999-06-04-13 of release-21-2.
[chise/xemacs-chise.git.1] / lisp / package-get.el
1 ;;; package-get.el --- Retrieve XEmacs package
2
3 ;; Copyright (C) 1998 by Pete Ware
4
5 ;; Author: Pete Ware <ware@cis.ohio-state.edu>
6 ;; Heavy-Modifications: Greg Klanderman <greg@alphatech.com>
7 ;;                      Jan Vroonhof    <vroonhof@math.ethz.ch>
8 ;; Keywords: internal
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
24 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 ;; 02111-1307, USA.
26
27 ;;; Synched up with: Not in FSF
28
29 ;;; Commentary:
30
31 ;; package-get -
32 ;;      Retrieve a package and any other required packages from an archive
33 ;;
34 ;;
35 ;; Note (JV): Most of this no longer aplies!
36 ;;
37 ;; The idea:
38 ;;      A new XEmacs lisp-only release is generated with the following steps:
39 ;;      1. The maintainer runs some yet to be written program that
40 ;;         generates all the dependency information.  This should
41 ;;         determine all the require and provide statements and associate
42 ;;         them with a package.
43 ;;      2. All the packages are then bundled into their own tar balls
44 ;;         (or whatever format)
45 ;;      3. Maintainer automatically generates a new `package-get-base'
46 ;;         data structure which contains information such as the
47 ;;         package name, the file to be retrieved, an md5 checksum,
48 ;;         etc (see `package-get-base').
49 ;;      4. The maintainer posts an announcement with the new version
50 ;;         of `package-get-base'.
51 ;;      5. A user/system manager saves this posting and runs
52 ;;         `package-get-update' which uses the previously saved list
53 ;;         of packages, `package-get-here' that the user/site
54 ;;         wants to determine what new versions to download and
55 ;;         install.
56 ;;
57 ;;      A user/site manager can generate a new `package-get-here' structure
58 ;;      by using `package-get-setup' which generates a customize like
59 ;;      interface to the list of packages.  The buffer looks something
60 ;;      like:
61 ;;
62 ;;      gnus    - a mail and news reader
63 ;;      []      Always install
64 ;;      []      Needs updating
65 ;;      []      Required by other [packages]
66 ;;      version: 2.0
67 ;;
68 ;;      vm      - a mail reader
69 ;;      []      Always install
70 ;;      []      Needs updating
71 ;;      []      Required by other [packages]    
72 ;;
73 ;;      Where `[]' indicates a toggle box
74 ;;
75 ;;      - Clicking on "Always install" puts this into
76 ;;        `package-get-here' list.  "Needs updating" indicates a new
77 ;;        version is available.  Anything already in
78 ;;        `package-get-here' has this enabled.
79 ;;      - "Required by other" means some other packages are going to force
80 ;;        this to be installed.  Clicking on  [packages] gives a list
81 ;;        of packages that require this.
82 ;;      
83 ;;      The `package-get-base' should be installed in a file in
84 ;;      `data-directory'.  The `package-get-here' should be installed in
85 ;;      site-lisp.  Both are then read at run time.
86 ;;
87 ;; TODO:
88 ;;      - Implement `package-get-setup'
89 ;;      - Actually put `package-get-base' and `package-get-here' into
90 ;;        files that are read.
91 ;;      - Allow users to have their own packages that they want installed
92 ;;        in ~/.xemacs/.
93 ;;      - SOMEONE needs to write the programs that generate the
94 ;;        provides/requires database and makes it into a lisp data
95 ;;        structure suitable for `package-get-base'
96 ;;      - Handle errors such as no package providing a required symbol.
97 ;;      - Tie this into the `require' function to download packages
98 ;;        transparently.
99
100 ;;; Change Log
101
102 ;;; Code:
103
104 (require 'package-admin)
105 ;; (require 'package-get-base)
106
107 (defgroup package-tools nil
108   "Tools to manipulate packages."
109   :group 'emacs)
110
111 (defgroup package-get nil
112   "Automatic Package Fetcher and Installer."
113   :prefix "package-get"
114   :group 'package-tools)
115
116 ;;;###autoload  
117 (defvar package-get-base nil
118   "List of packages that are installed at this site.
119 For each element in the alist,  car is the package name and the cdr is
120 a plist containing information about the package.   Typical fields
121 kept in the plist are:
122
123 version         - version of this package
124 provides        - list of symbols provided
125 requires        - list of symbols that are required.
126                   These in turn are provided by other packages.
127 filename        - name of the file.
128 size            - size of the file (aka the bundled package)
129 md5sum          - computed md5 checksum
130 description     - What this package is for.
131 type            - Whether this is a 'binary (default) or 'single file package
132
133 More fields may be added as needed.  An example:
134
135 '(
136  (name
137   (version \"<version 2>\"
138    file \"filename\"
139    description \"what this package is about.\"
140    provides (<list>)
141    requires (<list>)
142    size <integer-bytes>
143    md5sum \"<checksum\"
144    type single
145    )
146   (version \"<version 1>\"
147    file \"filename\"
148    description \"what this package is about.\"
149    provides (<list>)
150    requires (<list>)
151    size <integer-bytes>
152    md5sum \"<checksum\"
153    type single
154    )
155    ...
156    ))
157
158 For version information, it is assumed things are listed in most
159 recent to least recent -- in other words, the version names don't have to
160 be lexically ordered.  It is debatable if it makes sense to have more than
161 one version of a package available.")
162
163 (defcustom package-get-dir (temp-directory)
164   "*Where to store temporary files for staging."
165   :tag "Temporary directory"
166   :type 'directory
167   :group 'package-get)
168
169 (define-widget 'host-name 'string
170   "A Host name."
171   :tag "Host")
172
173 (defcustom package-get-remote nil
174   "*List of remote sites to contact for downloading packages.
175 List format is '(site-name directory-on-site).  Each site is tried in
176 order until the package is found.  As a special case, `site-name' can be
177 `nil', in which case `directory-on-site' is treated as a local directory."
178   :tag "Package repository"
179   :type '(repeat (choice (list :tag "Local" (const :tag "Local" nil) directory )
180                          (list :tag "Remote" host-name directory) ))
181   :group 'package-get)
182
183 (defcustom package-get-download-sites
184   '(
185     ;; North America
186     ("xemacs.org" "ftp.xemacs.org" "pub/xemacs/packages")
187     ("cso.uiuc.edu" "ftp.cso.uiuc.edu" "pub/packages/xemacs/packages")
188
189     ;; South America
190     ("unicamp.br" "ftp.unicamp.br" "pub/xemacs/packages")
191
192     ;; Europe
193     ("sunsite.cnlab-switch.ch" "sunsite.cnlab-switch.ch" "mirror/xemacs/packages")
194     ("tu-darmstadt.de" "ftp.tu-darmstadt.de" "pub/editors/xemacs/packages")
195     ("sunsite.auc.dk" "sunsite.auc.dk" "pub/emacs/xemacs/packages")
196     ("pasteur.fr" "ftp.pasteur.fr" "pub/computing/xemacs/packages")
197     ("cenatls.cena.dgac.fr" "ftp.cenatls.cena.dgac.fr" "pub/Emacs/xemacs/packages")
198     ("kfki.hu" "ftp.kfki.hu" "pub/packages/xemacs/packages")
199     ("uniroma2.it" "ftp.uniroma2.it" "unix/misc/dist/XEMACS/packages")
200     ("icm.edu.pl" "ftp.icm.edu.pl" "pub/unix/editors/xemacs/packages")
201     ("sunet.se" "ftp.sunet.se" "pub/gnu/xemacs/packages")
202     ("doc.ic.ac.uk" "sunsite.doc.ic.ac.uk" "packages/xemacs/packages")
203     ("srcc.msu.su" "ftp1.srcc.msu.su" "mirror/ftp.xemacs.org/packages")
204
205     ;; Asia
206     ("usyd.edu.au" "ftp.usyd.edu.au" "pub/Xemacs/packages")
207     ("netlab.is.tsukuba.ac.jp" "ftp.netlab.is.tsukuba.ac.jp" "pub/GNU/xemacs/packages")
208     ("jaist.ac.jp" "ftp.jaist.ac.jp" "pub/GNU/xemacs/packages")
209     ("ring.aist.go.jp" "ring.aist.go.jp" "pub/text/xemacs/packages")
210     ("ring.asahi-net.or.jp" "ring.asahi-net.or.jp" "pub/text/xemacs/packages")
211     ("SunSITE.sut.ac.jp" "SunSITE.sut.ac.jp" "pub/archives/packages/xemacs/packages")
212     ("dti.ad.jp" "ftp.dti.ad.jp" "pub/unix/editor/xemacs/packages")
213     ("kreonet.re.kr" "ftp.kreonet.re.kr" "pub/tools/emacs/xemacs/packages")
214     )
215   "*List of remote sites available for downloading packages.
216 List format is '(site-description site-name directory-on-site).
217 SITE-DESCRIPTION is a textual description of the site.  SITE-NAME
218 is the internet address of the download site.  DIRECTORY-ON-SITE
219 is the directory on the site in which packages may be found.
220 This variable is used to initialize `package-get-remote', the
221 variable actually used to specify package download sites."
222   :tag "Package download sites"
223   :type '(repeat (list hostname directory))
224   :group 'package-get)
225
226 (defcustom package-get-remove-copy t
227   "*After copying and installing a package, if this is T, then remove the
228 copy.  Otherwise, keep it around."
229   :type 'boolean
230   :group 'package-get)
231
232 ;; #### it may make sense for this to be a list of names.
233 ;; #### also, should we rename "*base*" to "*index*" or "*db*"?
234 ;;      "base" is a pretty poor name.
235 (defcustom package-get-base-filename "package-index.LATEST.pgp"
236   "*Name of the default package-get database file.
237 This may either be a relative path, in which case it is interpreted
238 with respect to `package-get-remote', or an absolute path."
239   :type 'file
240   :group 'package-get)
241
242 (defcustom package-get-always-update nil
243   "*If Non-nil always make sure we are using the latest package index (base).
244 Otherwise respect the `force-current' argument of `package-get-require-base'."
245   :type 'boolean
246   :group 'package-get)
247
248 (defcustom package-get-require-signed-base-updates t
249   "*If set to a non-nil value, require explicit user confirmation for updates
250 to the package-get database which cannot have their signature verified via PGP.
251 When nil, updates which are not PGP signed are allowed without confirmation."
252   :type 'boolean
253   :group 'package-get)
254
255 (defvar package-get-was-current nil
256   "Non-nil we did our best to fetch a current database.")
257
258
259 ;Shouldn't this be in package-ui?
260 ;;;###autoload
261 (defun package-get-download-menu ()
262   "Build the `Add Download Site' menu."
263   (mapcar (lambda (site)
264             (vector (car site)
265                `(package-ui-add-site (quote ,(cdr site)))
266                     :style 'toggle :selected
267                     `(member (quote ,(cdr site)) package-get-remote)))
268           package-get-download-sites))
269
270 ;;;###autoload
271 (defun package-get-require-base (&optional force-current)
272   "Require that a package-get database has been loaded.
273 If the optional FORCE-CURRENT argument or the value of
274 `package-get-always-update' is Non-nil, try to update the database
275 from a location in `package-get-remote'. Otherwise a local copy is used
276 if available and remote access is never done.
277
278 Please use FORCE-CURRENT only when the user is explictly dealing with packages
279 and remote access is likely in the near future."
280   (setq force-current (or force-current package-get-always-update))
281   (unless (and (boundp 'package-get-base)
282                package-get-base
283                (or (not force-current) package-get-was-current))
284     (package-get-update-base nil force-current))
285   (if (or (not (boundp 'package-get-base))
286           (not package-get-base))
287       (error "Package-get database not loaded")
288     (setq package-get-was-current force-current)))
289
290 (defconst package-get-pgp-signed-begin-line "^-----BEGIN PGP SIGNED MESSAGE-----"
291   "Text for start of PGP signed messages.")
292 (defconst package-get-pgp-signature-begin-line "^-----BEGIN PGP SIGNATURE-----"
293   "Text for beginning of PGP signature.")
294 (defconst package-get-pgp-signature-end-line "^-----END PGP SIGNATURE-----"
295   "Text for end of PGP signature.")
296
297 ;;;###autoload
298 (defun package-get-update-base-entry (entry)
299   "Update an entry in `package-get-base'."
300   (let ((existing (assq (car entry) package-get-base)))
301     (if existing
302         (setcdr existing (cdr entry))
303       (setq package-get-base (cons entry package-get-base))
304       (package-get-custom-add-entry (car entry) (car (cdr entry))))))
305
306 (defun package-get-locate-file (file &optional nil-if-not-found no-remote)
307   "Locate an existing FILE with respect to `package-get-remote'.
308 If FILE is an absolute path or is not found, simply return FILE.
309 If optional argument NIL-IF-NOT-FOUND is non-nil, return nil
310 if FILE can not be located.
311 If NO-REMOTE is non-nil never search remote locations."
312   (if (file-name-absolute-p file)
313       file
314     (let ((entries package-get-remote)
315           (expanded nil))
316       (while entries
317         (unless (and no-remote (caar entries))
318           (let ((expn (package-get-remote-filename (car entries) file)))
319             (if (and expn (file-exists-p expn))
320                 (setq entries  nil
321                       expanded expn))))
322         (setq entries (cdr entries)))
323       (or expanded
324           (and (not nil-if-not-found)
325                file)))))
326
327 (defun package-get-locate-index-file (no-remote)
328   "Locate the package-get index file.  Do not return remote paths if NO-REMOTE
329 is non-nil."
330   (or (package-get-locate-file package-get-base-filename t no-remote)
331       (locate-data-file package-get-base-filename)
332       package-get-base-filename))
333
334 (defvar package-get-user-package-location user-init-directory)
335
336 (defun package-get-maybe-save-index (filename)
337   "Offer to save the current buffer as the local package index file,
338 if different."
339   (let ((location (package-get-locate-index-file t)))
340     (unless (and filename (equal filename location))
341       (unless (equal (md5 (current-buffer))
342                      (with-temp-buffer
343                        (insert-file-contents location)
344                        (md5 (current-buffer))))
345         (unless (file-writable-p location)
346           (setq location (expand-file-name package-get-base-filename
347                 (expand-file-name "etc/" package-get-user-package-location))))
348         (when (y-or-n-p (concat "Update package index in" location "? "))
349           (write-file location))))))
350       
351
352 ;;;###autoload
353 (defun package-get-update-base (&optional db-file force-current)
354   "Update the package-get database file with entries from DB-FILE.
355 Unless FORCE-CURRENT is non-nil never try to update the database."
356   (interactive
357    (let ((dflt (package-get-locate-index-file nil)))
358      (list (read-file-name "Load package-get database: "
359                            (file-name-directory dflt)
360                            dflt
361                            t
362                            (file-name-nondirectory dflt)))))
363   (setq db-file (expand-file-name (or db-file
364                                       (package-get-locate-index-file
365                                          (not force-current)))))
366   (if (not (file-exists-p db-file))
367       (error "Package-get database file `%s' does not exist" db-file))
368   (if (not (file-readable-p db-file))
369       (error "Package-get database file `%s' not readable" db-file))
370   (let ((buf (get-buffer-create "*package database*")))
371     (unwind-protect
372         (save-excursion
373           (set-buffer buf)
374           (erase-buffer buf)
375           (insert-file-contents-internal db-file)
376           (package-get-update-base-from-buffer buf)
377           (if (file-remote-p db-file)
378               (package-get-maybe-save-index db-file)))
379       (kill-buffer buf))))
380
381 ;;;###autoload
382 (defun package-get-update-base-from-buffer (&optional buf)
383   "Update the package-get database with entries from BUFFER.
384 BUFFER defaults to the current buffer.  This command can be
385 used interactively, for example from a mail or news buffer."
386   (interactive)
387   (setq buf (or buf (current-buffer)))
388   (let (content-beg content-end beg end)
389     (save-excursion
390       (set-buffer buf)
391       (goto-char (point-min))
392       (setq content-beg (point))
393       (setq content-end (save-excursion (goto-char (point-max)) (point)))
394       (when (re-search-forward package-get-pgp-signed-begin-line nil t)
395         (setq beg (match-beginning 0))
396         (setq content-beg (match-end 0)))
397       (when (re-search-forward package-get-pgp-signature-begin-line nil t)
398         (setq content-end (match-beginning 0)))
399       (when (re-search-forward package-get-pgp-signature-end-line nil t)
400         (setq end (point)))
401       (if (not (and content-beg content-end beg end))
402           (or (not package-get-require-signed-base-updates)
403               (yes-or-no-p "Package-get entries not PGP signed, continue? ")
404               (error "Package-get database not updated")))
405       (if (and content-beg content-end beg end)
406           (if (not (condition-case nil
407                        (or (fboundp 'mc-pgp-verify-region)
408                            (load-library "mc-pgp")
409                            (fboundp 'mc-pgp-verify-region))
410                      (error nil)))
411               (or (not package-get-require-signed-base-updates)
412                   (yes-or-no-p
413                    "No mailcrypt; can't verify package-get DB signature, continue? ")
414                   (error "Package-get database not updated"))))
415       (if (and beg end
416                (fboundp 'mc-pgp-verify-region)
417                (or (not
418                     (condition-case err
419                         (mc-pgp-verify-region beg end)
420                       (file-error
421                        (and (string-match "No such file" (nth 2 err))
422                             (or (not package-get-require-signed-base-updates)
423                                 (yes-or-no-p
424                                  (concat "Can't find PGP, continue without "
425                                          "package-get DB verification? ")))))
426                       (t nil)))))
427           (error "Package-get PGP signature failed to verify"))
428       ;; ToDo: We shoud call package-get-maybe-save-index on the region
429       (package-get-update-base-entries content-beg content-end)
430       (message "Updated package-get database"))))
431
432 (defun package-get-update-base-entries (beg end)
433   "Update the package-get database with the entries found between
434 BEG and END in the current buffer."
435   (save-excursion
436     (goto-char beg)
437     (if (not (re-search-forward "^(package-get-update-base-entry" nil t))
438         (error "Buffer does not contain package-get database entries"))
439     (beginning-of-line)
440     (let ((count 0))
441       (while (and (< (point) end)
442                   (re-search-forward "^(package-get-update-base-entry" nil t))
443         (beginning-of-line)
444         (let ((entry (read (current-buffer))))
445           (if (or (not (consp entry))
446                   (not (eq (car entry) 'package-get-update-base-entry)))
447               (error "Invalid package-get database entry found"))
448           (package-get-update-base-entry
449            (car (cdr (car (cdr entry)))))
450           (setq count (1+ count))))
451       (message "Got %d package-get database entries" count))))
452
453 ;;;###autoload
454 (defun package-get-save-base (file)
455   "Write the package-get database to FILE.
456
457 Note: This database will be unsigned of course."
458   (interactive "FSave package-get database to: ")
459   (package-get-require-base t)
460   (let ((buf (get-buffer-create "*package database*")))
461     (unwind-protect
462         (save-excursion
463           (set-buffer buf)
464           (erase-buffer buf)
465           (goto-char (point-min))
466           (let ((entries package-get-base) entry plist)
467             (insert ";; Package Index file -- Do not edit manually.\n")
468             (insert ";;;@@@\n")
469             (while entries
470               (setq entry (car entries))
471               (setq plist (car (cdr entry)))
472               (insert "(package-get-update-base-entry (quote\n")
473               (insert (format "(%s\n" (symbol-name (car entry))))
474               (while plist
475                 (insert (format "  %s%s %S\n"
476                                 (if (eq plist (car (cdr entry))) "(" " ")
477                                 (symbol-name (car plist))
478                                 (car (cdr plist))))
479                 (setq plist (cdr (cdr plist))))
480               (insert "))\n))\n;;;@@@\n")
481               (setq entries (cdr entries))))
482           (insert ";; Package Index file ends here\n")
483           (write-region (point-min) (point-max) file))
484       (kill-buffer buf))))
485
486 (defun package-get-interactive-package-query (get-version package-symbol)
487   "Perform interactive querying for package and optional version.
488 Query for a version if GET-VERSION is non-nil.  Return package name as
489 a symbol instead of a string if PACKAGE-SYMBOL is non-nil.
490 The return value is suitable for direct passing to `interactive'."
491   (package-get-require-base t)
492   (let ( (table (mapcar '(lambda (item)
493                            (let ( (name (symbol-name (car item))) )
494                              (cons name name)
495                              ))
496                         package-get-base)) 
497          package package-symbol default-version version)
498     (save-window-excursion
499       (setq package (completing-read "Package: " table nil t))
500       (setq package-symbol (intern package))
501       (if get-version
502           (progn
503             (setq default-version 
504                   (package-get-info-prop 
505                    (package-get-info-version
506                     (package-get-info-find-package package-get-base
507                                                    package-symbol) nil)
508                    'version))
509             (while (string=
510                     (setq version (read-string "Version: " default-version))
511                     "")
512               )
513             (if package-symbol
514                 (list package-symbol version)
515               (list package version))
516             )
517         (if package-symbol
518             (list package-symbol)
519           (list package)))
520       )))
521
522 ;;;###autoload
523 (defun package-get-delete-package (package &optional pkg-topdir)
524   "Delete an installation of PACKAGE below directory PKG-TOPDIR.
525 PACKAGE is a symbol, not a string.
526 This is just an interactive wrapper for `package-admin-delete-binary-package'."
527   (interactive (package-get-interactive-package-query nil t))
528   (package-admin-delete-binary-package package pkg-topdir))
529
530 ;;;###autoload
531 (defun package-get-update-all ()
532   "Fetch and install the latest versions of all currently installed packages."
533   (interactive)
534   (package-get-require-base t)
535   ;; Load a fresh copy
536   (catch 'exit
537     (mapcar (lambda (pkg)
538               (if (not (package-get (car pkg) nil 'never))
539                   (throw 'exit nil)             ;; Bail out if error detected
540                   ))
541             packages-package-list)))
542
543 ;;;###autoload
544 (defun package-get-all (package version &optional fetched-packages install-dir)
545   "Fetch PACKAGE with VERSION and all other required packages.
546 Uses `package-get-base' to determine just what is required and what
547 package provides that functionality.  If VERSION is nil, retrieves
548 latest version.  Optional argument FETCHED-PACKAGES is used to keep
549 track of packages already fetched.  Optional argument INSTALL-DIR,
550 if non-nil, specifies the package directory where fetched packages
551 should be installed.
552
553 Returns nil upon error."
554   (interactive (package-get-interactive-package-query t nil))
555   (let* ((the-package (package-get-info-find-package package-get-base
556                                                      package))
557          (this-package (package-get-info-version
558                         the-package version))
559          (this-requires (package-get-info-prop this-package 'requires))
560          )
561     (catch 'exit
562       (setq version (package-get-info-prop this-package 'version))
563       (unless (package-get-installedp package version)
564         (if (not (package-get package version nil install-dir))
565             (progn
566               (setq fetched-packages nil)
567               (throw 'exit nil))))
568       (setq fetched-packages
569             (append (list package)
570                     (package-get-info-prop this-package 'provides)
571                     fetched-packages))
572       ;; grab everything that this package requires plus recursively
573       ;; grab everything that the requires require.  Keep track
574       ;; in `fetched-packages' the list of things provided -- this
575       ;; keeps us from going into a loop
576       (while this-requires
577         (if (not (member (car this-requires) fetched-packages))
578             (let* ((reqd-package (package-get-package-provider
579                                   (car this-requires) t))
580                    (reqd-version (cadr reqd-package))
581                    (reqd-name (car reqd-package)))
582               (if (null reqd-name)
583                   (error "Unable to find a provider for %s"
584                          (car this-requires)))
585               (if (not (setq fetched-packages
586                              (package-get-all reqd-name reqd-version
587                                               fetched-packages
588                                               install-dir)))
589                   (throw 'exit nil)))
590           )
591         (setq this-requires (cdr this-requires)))
592       )
593     fetched-packages
594     ))
595
596 ;;;###autoload
597 (defun package-get-dependencies (packages)
598   "Compute dependencies for PACKAGES.
599 Uses `package-get-base' to determine just what is required and what
600 package provides that functionality.  Returns the list of packages
601 required by PACKAGES."
602   (package-get-require-base t)
603   (let ((orig-packages packages)
604         dependencies provided)
605     (while packages
606       (let* ((package (car packages))
607              (the-package (package-get-info-find-package
608                            package-get-base package))
609              (this-package (package-get-info-version
610                             the-package nil))
611              (this-requires (package-get-info-prop this-package 'requires))
612              (new-depends   (set-difference
613                              (mapcar
614                               #'(lambda (reqd)
615                                   (let* ((reqd-package (package-get-package-provider reqd))
616                                          (reqd-version (cadr reqd-package))
617                                          (reqd-name    (car reqd-package)))
618                                     (if (null reqd-name)
619                                         (error "Unable to find a provider for %s" reqd))
620                                     reqd-name))
621                               this-requires)
622                              dependencies))
623              (this-provides (package-get-info-prop this-package 'provides)))
624         (setq dependencies
625               (union dependencies new-depends))
626         (setq provided
627               (union provided (union (list package) this-provides)))
628         (setq packages
629               (union new-depends (cdr packages)))))
630     (set-difference dependencies orig-packages)))
631
632 (defun package-get-load-package-file (lispdir file)
633   (let (pathname)
634     (setq pathname (expand-file-name file lispdir))
635     (condition-case err
636         (progn
637           (load pathname t)
638           t)
639       (t
640        (message "Error loading package file \"%s\" %s!" pathname err)
641        nil))
642     ))
643
644 (defun package-get-init-package (lispdir)
645   "Initialize the package.
646 This really assumes that the package has never been loaded.  Updating
647 a newer package can cause problems, due to old, obsolete functions in
648 the old package.
649
650 Return `t' upon complete success, `nil' if any errors occurred."
651   (progn
652     (if (and lispdir
653              (file-accessible-directory-p lispdir))
654         (progn
655           ;; Add lispdir to load-path if it doesn't already exist.
656           ;; NOTE: this does not take symlinks, etc., into account.
657           (if (let ( (dirs load-path) )
658                 (catch 'done
659                   (while dirs
660                     (if (string-equal (car dirs) lispdir)
661                         (throw 'done nil))
662                     (setq dirs (cdr dirs))
663                     )
664                   t))
665               (setq load-path (cons lispdir load-path)))
666           (if (not (package-get-load-package-file lispdir "auto-autoloads"))
667               (package-get-load-package-file lispdir "_pkg"))
668           t)
669       nil)
670     ))
671
672 ;;;###autoload
673 (defun package-get (package &optional version conflict install-dir)
674   "Fetch PACKAGE from remote site.
675 Optional arguments VERSION indicates which version to retrieve, nil
676 means most recent version.  CONFLICT indicates what happens if the
677 package is already installed.  Valid values for CONFLICT are:
678 'always always retrieve the package even if it is already installed
679 'never  do not retrieve the package if it is installed.
680 INSTALL-DIR, if non-nil, specifies the package directory where
681 fetched packages should be installed.
682
683 The value of `package-get-base' is used to determine what files should 
684 be retrieved.  The value of `package-get-remote' is used to determine
685 where a package should be retrieved from.  The sites are tried in
686 order so one is better off listing easily reached sites first.
687
688 Once the package is retrieved, its md5 checksum is computed.  If that
689 sum does not match that stored in `package-get-base' for this version
690 of the package, an error is signalled.
691
692 Returns `t' upon success, the symbol `error' if the package was
693 successfully installed but errors occurred during initialization, or
694 `nil' upon error."
695   (interactive (package-get-interactive-package-query nil t))
696   (catch 'skip-update
697   (let* ((this-package
698           (package-get-info-version
699            (package-get-info-find-package package-get-base
700                                           package) version))
701          (latest (package-get-info-prop this-package 'version))
702          (installed (package-get-key package :version))
703          (this-requires (package-get-info-prop this-package 'requires))
704          (found nil)
705          (search-dirs package-get-remote)
706          (base-filename (package-get-info-prop this-package 'filename))
707          (package-status t)
708          filenames full-package-filename)
709     (if (null this-package)
710         (if package-get-remote
711             (error "Couldn't find package %s with version %s"
712                    package version)
713           (error "No download sites or local package locations specified.")))
714     (if (null base-filename)
715         (error "No filename associated with package %s, version %s"
716                package version))
717     (setq install-dir
718           (package-admin-get-install-dir package install-dir
719                 (or (eq package 'mule-base) (memq 'mule-base this-requires))))
720
721     ;; If they asked for the latest using version=nil, don't get an older
722     ;; version than we already have.
723     (if installed
724         (if (> (if (stringp installed)
725                    (string-to-number installed)
726                  installed)
727                (if (stringp latest)
728                    (string-to-number latest)
729                  latest))
730             (if (not (null version))
731                 (warn "Installing %s package version %s, you had a newer version %s"
732                       package latest installed)
733               (warn "Skipping %s package, you have a newer version %s"
734                     package installed)
735               (throw 'skip-update t))))
736
737     ;; Contrive a list of possible package filenames.
738     ;; Ugly.  Is there a better way to do this?
739     (setq filenames (cons base-filename nil))
740     (if (string-match "^\\(..*\\)\.tar\.gz$" base-filename)
741         (setq filenames (append filenames
742                                 (list (concat (match-string 1 base-filename)
743                                               ".tgz")))))
744
745     (setq version latest)
746     (unless (and (eq conflict 'never)
747                  (package-get-installedp package version))
748       ;; Find the package from the search list in package-get-remote
749       ;; and copy it into the staging directory.  Then validate
750       ;; the checksum.  Finally, install the package.
751       (catch 'done
752         (let (search-filenames current-dir-entry host dir current-filename
753                                dest-filename)
754           ;; In each search directory ...
755           (while search-dirs
756             (setq current-dir-entry (car search-dirs)
757                   host (car current-dir-entry)
758                   dir (car (cdr current-dir-entry))
759                   search-filenames filenames
760                   )
761
762             ;; Look for one of the possible package filenames ...
763             (while search-filenames
764               (setq current-filename (car search-filenames)
765                     dest-filename (package-get-staging-dir current-filename))
766               (cond
767                ;; No host means look on the current system.
768                ( (null host)
769                  (setq full-package-filename
770                        (substitute-in-file-name
771                         (expand-file-name current-filename
772                                           (file-name-as-directory dir))))
773                  )
774
775                ;; If it's already on the disk locally, and the size is
776                ;; greater than zero ...
777                ( (and (file-exists-p dest-filename)
778                       (let (attrs)
779                         ;; file-attributes could return -1 for LARGE files,
780                         ;; but, hopefully, packages won't be that large.
781                         (and (setq attrs (file-attributes dest-filename))
782                              (> (nth 7 attrs) 0))))
783                  (setq full-package-filename dest-filename)
784                  )
785
786                ;; If the file exists on the remote system ...
787                ( (file-exists-p (package-get-remote-filename
788                                  current-dir-entry current-filename))
789                  ;; Get it
790                  (setq full-package-filename dest-filename)
791                  (message "Retrieving package `%s' ..." 
792                           current-filename)
793                  (sit-for 0)
794                  (copy-file (package-get-remote-filename current-dir-entry
795                                                          current-filename)
796                             full-package-filename t)
797                  )
798                )
799
800               ;; If we found it, we're done.
801               (if (and full-package-filename
802                        (file-exists-p full-package-filename))
803                   (throw 'done nil))
804               ;; Didn't find it.  Try the next possible filename.
805               (setq search-filenames (cdr search-filenames))
806               )
807             ;; Try looking in the next possible directory ...
808             (setq search-dirs (cdr search-dirs))
809             )
810           ))
811
812       (if (or (not full-package-filename)
813               (not (file-exists-p full-package-filename)))
814           (if package-get-remote
815               (error "Unable to find file %s" base-filename)
816             (error
817              "No download sites or local package locations specified.")))
818       ;; Validate the md5 checksum
819       ;; Doing it with XEmacs removes the need for an external md5 program
820       (message "Validating checksum for `%s'..." package) (sit-for 0)
821       (with-temp-buffer
822         ;; What ever happened to i-f-c-literally
823         (let (file-name-handler-alist)
824           (insert-file-contents-internal full-package-filename))
825         (if (not (string= (md5 (current-buffer))
826                           (package-get-info-prop this-package
827                                                  'md5sum)))
828             (error "Package %s does not match md5 checksum" base-filename)))
829
830       (package-admin-delete-binary-package package install-dir)
831
832       (message "Installing package `%s' ..." package) (sit-for 0)
833       (let ((status
834              (package-admin-add-binary-package full-package-filename
835                                                install-dir)))
836         (if (= status 0)
837             (progn
838               ;; clear messages so that only messages from
839               ;; package-get-init-package are seen, below.
840               (clear-message)
841               (if (package-get-init-package (package-admin-get-lispdir
842                                              install-dir package))
843                   (progn
844                     (message "Added package `%s'" package)
845                     (sit-for 0)
846                     )
847                 (progn
848                   ;; display message only if there isn't already one.
849                   (if (not (current-message))
850                       (progn
851                         (message "Added package `%s' (errors occurred)"
852                                  package)
853                         (sit-for 0)
854                         ))
855                   (if package-status
856                       (setq package-status 'errors))
857                   ))
858               )
859           (message "Installation of package %s failed." base-filename)
860           (sit-for 0)
861           (switch-to-buffer package-admin-temp-buffer)
862           (setq package-status nil)
863           ))
864       (setq found t))
865     (if (and found package-get-remove-copy)
866         (delete-file full-package-filename))
867     package-status
868     )))
869
870 (defun package-get-info-find-package (which name)
871   "Look in WHICH for the package called NAME and return all the info
872 associated with it.  See `package-get-base' for info on the format
873 returned.
874
875  To access fields returned from this, use
876 `package-get-info-version' to return information about particular a
877 version.  Use `package-get-info-find-prop' to find particular property 
878 from a version returned by `package-get-info-version'."
879   (interactive "xPackage list: \nsPackage Name: ")
880   (if which
881       (if (eq (caar which) name)
882           (cdar which)
883         (if (cdr which)
884             (package-get-info-find-package (cdr which) name)))))
885
886 (defun package-get-info-version (package version)
887   "In PACKAGE, return the plist associated with a particular VERSION of the
888   package.  PACKAGE is typically as returned by
889   `package-get-info-find-package'.  If VERSION is nil, then return the 
890   first (aka most recent) version.  Use `package-get-info-find-prop'
891   to retrieve a particular property from the value returned by this."
892   (interactive (package-get-interactive-package-query t t))
893   (while (and version package (not (string= (plist-get (car package) 'version) version)))
894     (setq package (cdr package)))
895   (if package (car package)))
896
897 (defun package-get-info-prop (package-version property)
898   "In PACKAGE-VERSION, return the value associated with PROPERTY.
899 PACKAGE-VERSION is typically returned by `package-get-info-version'
900 and PROPERTY is typically (although not limited to) one of the
901 following:
902
903 version         - version of this package
904 provides                - list of symbols provided
905 requires                - list of symbols that are required.
906                   These in turn are provided by other packages.
907 size            - size of the bundled package
908 md5sum          - computed md5 checksum"
909   (interactive "xPackage Version: \nSProperty")
910   (plist-get package-version property))
911
912 (defun package-get-info-version-prop (package-list package version property)
913   "In PACKAGE-LIST, search for PACKAGE with this VERSION and return
914   PROPERTY value."
915   (package-get-info-prop
916    (package-get-info-version
917     (package-get-info-find-package package-list package) version) property))
918
919 (defun package-get-set-version-prop (package-list package version
920                                                   property value)
921   "A utility to make it easier to add a VALUE for a specific PROPERTY
922   in this VERSION of a specific PACKAGE kept in the PACKAGE-LIST.
923 Returns the modified PACKAGE-LIST.  Any missing fields are created."
924   )
925
926 (defun package-get-staging-dir (filename)
927   "Return a good place to stash FILENAME when it is retrieved.
928 Use `package-get-dir' for directory to store stuff.
929 Creates `package-get-dir'  it it doesn't exist."
930   (interactive "FPackage filename: ")
931   (if (not (file-exists-p package-get-dir))
932       (make-directory package-get-dir))
933   (expand-file-name
934    (file-name-nondirectory (or (and (fboundp 'efs-ftp-path)
935                                     (nth 2 (efs-ftp-path filename)))
936                                filename))
937    (file-name-as-directory package-get-dir)))
938
939 (defun package-get-remote-filename (search filename)
940   "Return FILENAME as a remote filename.
941 It first checks if FILENAME already is a remote filename.  If it is
942 not, then it uses the (car search) as the remote site-name and the (cadr
943 search) as the remote-directory and concatenates filename.  In other
944 words
945         site-name:remote-directory/filename.
946
947 If (car search) is nil, (cadr search is interpreted as  a local directory).
948 "
949   (if (file-remote-p filename)
950       filename
951     (let ((dir (cadr search)))
952       (concat (when (car search)
953                 (concat
954                  (if (string-match "@" (car search))
955                      "/"
956                    "/anonymous@")
957                  (car search) ":"))
958               (if (string-match "/$" dir)
959                   dir
960                 (concat dir "/"))
961               filename))))
962
963
964 (defun package-get-installedp (package version)
965   "Determine if PACKAGE with VERSION has already been installed.
966 I'm not sure if I want to do this by searching directories or checking 
967 some built in variables.  For now, use packages-package-list."
968   ;; Use packages-package-list which contains name and version
969   (equal (plist-get
970           (package-get-info-find-package packages-package-list
971                                          package) ':version)
972          (if (floatp version) version (string-to-number version))))
973
974 ;;;###autoload
975 (defun package-get-package-provider (sym &optional force-current)
976   "Search for a package that provides SYM and return the name and
977   version.  Searches in `package-get-base' for SYM.   If SYM is a
978   consp, then it must match a corresponding (provide (SYM VERSION)) from 
979   the package.
980
981 If FORCE-CURRENT is non-nil make sure the database is up to date. This might
982 lead to Emacs accessing remote sites."
983   (interactive "SSymbol: ")
984   (package-get-require-base force-current)
985   (let ((packages package-get-base)
986         (done nil)
987         (found nil))
988     (while (and (not done) packages)
989       (let* ((this-name (caar packages))
990              (this-package (cdr (car packages)))) ;strip off package name
991         (while (and (not done) this-package)
992           (if (or (eq this-name sym)
993                   (eq (cons this-name
994                           (package-get-info-prop (car this-package) 'version))
995                       sym)
996                   (member sym
997                         (package-get-info-prop (car this-package) 'provides)))
998               (progn (setq done t)
999                      (setq found
1000                        (list (caar packages)
1001                          (package-get-info-prop (car this-package) 'version))))
1002             (setq this-package (cdr this-package)))))
1003       (setq packages (cdr packages)))
1004     found))
1005
1006 ;;
1007 ;; customize interfaces.
1008 ;; The group is in this file so that custom loads includes this file.
1009 ;;
1010 (defgroup packages nil
1011   "Configure XEmacs packages."
1012   :group 'emacs)
1013
1014 ;;;###autoload
1015 (defun package-get-custom ()
1016   "Fetch and install the latest versions of all customized packages."
1017   (interactive)
1018   (package-get-require-base t)
1019   (mapcar (lambda (pkg)
1020             (if (eval (intern (concat (symbol-name (car pkg)) "-package")))
1021                 (package-get (car pkg) nil))
1022             t)
1023           package-get-base))
1024
1025 (defun package-get-ever-installed-p (pkg &optional notused)
1026   (string-match "-package$" (symbol-name pkg))
1027   (custom-initialize-set 
1028    pkg 
1029    (if (package-get-info-find-package 
1030         packages-package-list 
1031         (intern (substring (symbol-name pkg) 0 (match-beginning 0))))
1032        t)))
1033
1034 (defvar package-get-custom-groups nil
1035   "List of package-get-custom groups")
1036
1037 (defun package-get-custom-add-entry (package props)
1038   (let* ((category (plist-get props 'category))
1039          (group (intern (concat category "-packages")))
1040          (custom-var (intern (concat (symbol-name package) "-package")))
1041          (description (plist-get props 'description)))
1042     (when (not (memq group package-get-custom-groups))
1043       (setq package-get-custom-groups (cons group
1044                                             package-get-custom-groups))
1045       (eval `(defgroup ,group nil
1046                ,(concat category " package group")
1047                :group 'packages)))
1048     (eval `(defcustom ,custom-var nil
1049              ,description
1050              :group ',group
1051              :initialize 'package-get-ever-installed-p
1052              :type 'boolean))))
1053
1054
1055 (provide 'package-get)
1056 ;;; package-get.el ends here