Codespaces and Emacs TRAMP

While you can use Emacs in the browser using Codespaces, it involves getting all of your emacs config set up on Codespaces. By using the GitHub CLI you can also use emacs TRAMP over SSH to work in the Codespace instance from your local emacs.

To do that, update your init.el to create a new tramp method. (Copied this from the emacs-codeql readme).

(let ((ghcs (assoc "ghcs" tramp-methods))
      (ghcs-methods '((tramp-login-program "gh")
                      (tramp-login-args (("codespace") ("ssh") ("-c") ("%h")))
                      (tramp-remote-shell "/bin/sh")
                      (tramp-remote-shell-login ("-l"))
                      (tramp-remote-shell-args ("-c")))))
  ;; just for debugging the methods
  (if ghcs (setcdr ghcs ghcs-methods)
    (push (cons "ghcs" ghcs-methods) tramp-methods)))

;; provide codespace name completion for ghcs tramp method
;; use C-j if you use ivy to kick in host completion
(defun my/tramp-parse-codespaces (&optional nop)
  (let ((results '())
           "gh codespace list --json name -q '.[].name'"))))
    (dolist (name codespaces)
      ;; tramp completion expects a list of (user host)
      (add-to-list 'results (list nil name)))

(tramp-set-completion-function "ghcs" '((my/tramp-parse-codespaces "")))

Install the GitHub CLI, authenticate your machine, and create a codespace.

brew install gh
gh auth login
gh cs create

Now you can use TRAMP to open files directly in your Codespace! C-x C-f then type ghcs:/ and use autocomplete to choose your codespace.

Everything that works with TRAMP should work including eglot and magit.