index all rss twitter github linkedin email

Álvaro Ramírez

11 October 2020 Emacs: create a Swift package/project

Been playing around with Swift Package Manager (SPM). Creating a new Swift package (ie. project) is pretty simple.

To create a library package, we can use the following:

swift package init --type library

Alternatively, to create a command-line utility use:

swift package init --type executable

Turns out, there are a few options: empty, library, executable, system-module, manifest.

With a little elisp, we can write a completing function to quickly generate a Swift package/project without the need to drop to the shell.

Bonus: I won't have to look up SPM options if I ever forget them.

swift-package.gif

(defun ar/swift-package-init ()
  "Execute `swift package init', with optional name and completing type."
  (interactive)
  (let* ((name (read-string "name (default): "))
         (type (completing-read
                "project type: "
                ;; Splits "--type empty|library|executable|system-module|manifest"
                (split-string
                 (nth 1 (split-string
                         (string-trim
                          (seq-find
                           (lambda (line)
                             (string-match "--type" line))
                           (process-lines "swift" "package" "init" "--help")))
                         "   "))
                 "|")))
         (command (format "swift package init --type %s" type)))
    (unless (string-empty-p name)
      (append command "--name " name))
    (shell-command command))
  (dired default-directory)
  (revert-buffer))