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