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