Subject: bug#61289: 30.0.50; Cannot reinstall language grammar after running `treesit-ready-p'

From: Eli Zaretskii <[email-masked]>
Date: Sun, 05 Feb 2023 11:13:37 +0200

> From: 牟 桐 <[email-masked]>
> Date: Sat, 4 Feb 2023 12:59:53 +0000
> 
> I'm using Windows, so I'll use `libtree-sitter-c.dll` as an example:
> 
> 1. `emacs -Q` to start a vanilla Emacs.
> 
> Run `M-x treesit-install-language-grammar`, then install the c
> parser to `~/.emacs.d/tree-sitter`. If there is already a
> `libtree-sitter-c.dll` there, the new installed library will
> overwrite the old library.
> 
> 2. Execute `(treesit-ready-p 'c)`, which returns t.
> 
> 3. Run `M-x treesit-install-language-grammar` again, there will be a
> warning:
> 
> ```
> ⛔ Warning (treesit): Error encountered when installing language grammar: (file-error Copying file Operation not permitted c:/Users/redacted/AppData/Local/Temp/treesit-workdir5HPGoS/repo/src/libtree-sitter-c.dll c:/Users/redacted/.emacs.d/tree-sitter/libtree-sitter-c.dll)
> ```
> 
> I don't know whether this is a bug or not, since I think it's reasonable
> to make the already used library not be able to be overwritten.
> 
> But someone reminded me that `treesit-ready-p` will be executed when you
> load the `xxx-ts-mode`. If the execution of `treesit-ready-p` made the
> `treesit-install-language-grammar` unusable, it means the design of that
> function has a little problem.

This is a basic issue on MS-Windows: it won't allow you to overwrite a
DLL that is being used by some program.

Can you try the patch below and see if it solves the problem?

diff --git a/lisp/treesit.el b/lisp/treesit.el
index 948016d..7e31da9 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -2884,7 +2884,17 @@ treesit--install-language-grammar-1
           ;; Copy out.
           (unless (file-exists-p out-dir)
             (make-directory out-dir t))
-          (copy-file lib-name (file-name-as-directory out-dir) t t)
+          (let* ((library-fname (expand-file-name lib-name out-dir))
+                 (old-fname (concat library-fname ".old")))
+            ;; Rename the existing shared library, if any, then
+            ;; install the new one, and try deleting the old one.
+            ;; This is for Windows systems, where we cannot simply
+            ;; overwrite a DLL that is being used.
+            (if (file-exists-p library-fname)
+                (rename-file library-fname old-fname t))
+            (copy-file lib-name (file-name-as-directory out-dir) t t)
+            ;; Ignore errors, in case the old version is still used.
+            (ignore-errors (delete-file old-fname)))
           (message "Library installed to %s/%s" out-dir lib-name))
       (when (file-exists-p workdir)
         (delete-directory workdir t)))))