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