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