Subject: bug#53970: 28.0.91; Issue when calling 'package-install' during init

From: Augusto Stoffel <[email-masked]>
Date: Sun, 13 Feb 2022 12:20:48 +0100

In the recent bug#53885, it was mentioned that the user may have good
reasons to call

```
(unless (package-installed-p 'some-package)
  (package-install 'some-package))
```

in their init file.

This works but has one glitch: when 'package-install' is called during
init time, 'package-selected-packages' is not updated accordingly
(unless it didn't have a saved custom value yet).

As an example, consider the following .emacs file:

```
(package-install 'eglot)
(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(package-selected-packages '(corfu devdocs)))
```

After starting Emacs, Eglot is installed but
'package-selected-packages' still has value '(corfu devdocs)'.

The least intrusive solution to this issue, in terms of number of
changed lines to packages.el, would be to add a :set parameter to
'package-selected-packages'.  Namely, something equivalent to the
following:

```
(require 'package)
(put 'package-selected-packages 'custom-set
     (lambda (_ val)
       (setq-default package-selected-packages
                     (append (unless after-init-time
                               (seq-difference package-selected-packages val))
                             val))))
(package-install 'eglot)
(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(package-selected-packages '(corfu devdocs)))
```

After starting a fresh Emacs with this as init file, one gets the
expected value for 'package-selected-packages', namely '(eglot corfu
devdocs)'.

Does that approach look reasonable?  Then I can prepare a patch.

By the way: I think the following function should be included in
package.el, to allow writing an init file that automatically bootstraps
Emacs to a usable state when copied to a new machine.

```
(defun package-ensure-installed (&rest packages)
  "Make sure PACKAGES are installed."
  (dolist (pkg packages)
    (unless (package-installed-p pkg)
      ;; Possibly call `package-refresh-contents' here
      (package-install pkg))))
```