-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.lisp
executable file
·319 lines (263 loc) · 11.2 KB
/
main.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env sbcl --script
;; Copyright © 2023–2024 Hraban Luyat
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU Affero General Public License as published
;; by the Free Software Foundation, version 3 of the License.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU Affero General Public License for more details.
;;
;; You should have received a copy of the GNU Affero General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
(setf *compile-verbose* NIL)
(require "asdf")
(require "uiop")
(asdf:load-system "alexandria")
(asdf:load-system "cl-interpol")
(asdf:load-system "cl-json")
(asdf:load-system "inferior-shell")
(asdf:load-system "str")
(asdf:load-system "trivia")
(defpackage #:script
(:use #:cl)
(:local-nicknames (#:alex #:alexandria)
(#:sh #:inferior-shell)))
(in-package #:script)
(named-readtables:in-readtable :interpol-syntax)
(defparameter *plutil* "/usr/bin/plutil")
(defparameter *copyable-app-props*
'("CFBundleDevelopmentRegion"
"CFBundleDocumentTypes"
"CFBundleGetInfoString"
"CFBundleIconFile"
"CFBundleIdentifier"
"CFBundleInfoDictionaryVersion"
"CFBundleName"
"CFBundleShortVersionString"
"CFBundleURLTypes"
"NSAppleEventsUsageDescription"
"NSAppleScriptEnabled"
"NSDesktopFolderUsageDescription"
"NSDocumentsFolderUsageDescription"
"NSDownloadsFolderUsageDescription"
"NSPrincipalClass"
"NSRemovableVolumesUsageDescription"
"NSServices"
"UTExportedTypeDeclarations")
"Based on a hunch, nothing scientific.")
(defun non-empty-env-p (name)
(str:non-empty-string-p (uiop:getenv name)))
;; Extremely rudimentary support for DRY_RUN. It’s messy output, but what
;; matters is that it doesn’t actually change anything on the system.
(defparameter *dry-run* (non-empty-env-p "DRY_RUN"))
(defun rootp ()
"Am I the root user?"
(equal "root" (uiop:getenv "USER")))
(defun sh (&rest args)
(if *dry-run*
(format T "exec: ~A~%" (prin1-to-string (first args)))
;; This is my personal convention; set DEBUGSH to effect set -x
(apply #'sh:run `(,@args :show ,(non-empty-env-p "DEBUGSH")))))
(defun sh/ss (&rest args)
(apply #'sh `(,@args :output (:string :stripped t))))
(defgeneric rm-rf (p))
(defmethod rm-rf ((p string))
(rm-rf (uiop:parse-native-namestring p :ensure-directory t)))
(defmethod rm-rf ((p pathname))
(if *dry-run*
(format T "rm -rf ~A~%" p)
(uiop:delete-directory-tree
(uiop:ensure-directory-pathname p)
:validate t
:if-does-not-exist :ignore)))
(defmacro in-temp-dir (&body body)
(alex:with-gensyms (dir f)
`(flet ((,f () ,@body))
(if *dry-run*
(,f)
(let ((,dir (uiop:ensure-directory-pathname (sh/ss '(mktemp #\d)))))
(uiop:with-current-directory (,dir)
(unwind-protect (,f)
(rm-rf ,dir))))))))
(defun list-of-strings-p (l)
(and (consp l) (every #'stringp l)))
(deftype list-of-strings ()
`(satisfies list-of-strings-p))
;;; mktrampoline
(defun copy-file (from to)
(if *dry-run*
(format T "cp ~A ~A~%" from to)
(uiop:copy-file from to)))
(defun copy-paths (from to paths)
(declare (type list-of-strings paths))
(let ((keys (cl-json:encode-json-to-string *copyable-app-props*))
;; For an object, keep only those keys from list “keys”
(jqfilter "to_entries |[.[]| select(.key as $item| $keys | index($item) >= 0) ] | from_entries"))
(in-temp-dir
(copy-file from "orig")
(copy-file to "bare-wrapper")
(sh `(sh:and (,*plutil* -convert json -- orig)
(,*plutil* -convert json -- bare-wrapper)
(jq :argjson keys ,keys ,jqfilter (< orig) (> filtered))
(sh:pipe (cat bare-wrapper filtered)
(jq #\s add (> final)))
(,*plutil* -convert xml1 -- final)))
(copy-file "final" to))))
(defun resources (app)
#?"${app}/Contents/Resources/")
(defun infoplist (app)
#?"${app}/Contents/Info.plist")
(defun app-p (path)
"Is this path a .app bundle?"
(probe-file (infoplist path)))
(defun sync-icons (from to)
"Remove all icons from TO apps resources, and copy all icons FROM to it"
(destructuring-bind (from-cnts to-cnts) (mapcar #'resources (list from to))
(when (probe-file from-cnts)
;; 🤷
(sh `(sh:and
(find ,to-cnts -name "*.icns" -delete)
(rsync :include "*.icns" :exclude "*" :recursive ,from-cnts ,to-cnts))))))
(defun mktrampoline-app (app trampoline)
(let ((cmd (format NIL "do shell script \"open '~A'\"" app)))
(sh `("/usr/bin/osacompile" #\o ,trampoline #\e ,cmd))
(sync-icons app trampoline)
(copy-paths (infoplist app) (infoplist trampoline) *copyable-app-props*)))
(defun mktrampoline-bin (bin trampoline)
;; In order for applescript not to wait on the binary you must direct both
;; output pipes to null.
(let ((cmd (format NIL "do shell script \"'~A' &> /dev/null &\"" bin)))
(sh `("/usr/bin/osacompile" #\o ,trampoline #\e ,cmd))))
(defgeneric mktrampoline (from to))
(defmethod mktrampoline ((from string) (to string))
(let ((from-abs (probe-file from)))
(when (null from-abs)
(error "No such file: ~A" from))
(mktrampoline from-abs (uiop:ensure-pathname to
:ensure-absolute t
:defaults (uiop:getcwd)))))
(defmethod mktrampoline ((from pathname) (to pathname))
(uiop:ensure-pathname from :ensure-absolute t)
(uiop:ensure-pathname to :ensure-absolute t)
(if (uiop:directory-pathname-p from)
(if (app-p from)
(mktrampoline-app from to)
(error "Path ~A does not appear to be a Mac app (missing Info.plist)" from))
(mktrampoline-bin from to)))
;;; sync-dock
(defun realpath (f)
"Transform a string, optionally relative, into a an absolute path.
Also resolves symlinks, if relevant.
"
(uiop:ensure-pathname f
:want-pathname t
:ensure-absolute t
:defaults (uiop:getcwd)
:want-existing t
:resolve-symlinks t))
(defgeneric path-without-slash (p))
(defmethod path-without-slash ((p string))
(string-right-trim "/" p))
(defmethod path-without-slash ((p pathname))
(path-without-slash (namestring p)))
(defun sync-dock (apps)
"Every element must be a pathname to a real directory, not a symlink"
;; dockutil doesn't like acting under sudo and will fall back to the original
;; user. That’s sensible when using dockutil as an end user, but because this
;; tool /wraps/ it, it leads to unexpected results e.g. when used in a home
;; manager activation script. Just stick to the dumb default: act as the user
;; that invokes you, no special sudo tricks.
(setf (uiop:getenv "SUDO_USER") "")
;; Filtering for /nix/store is not technically part of the docs but let’s be
;; conservative for now.
(let* ((dockutil-args (when (rootp)
;; When run as root, it’s probably intended to affect every
;; actual end-user’s dock--not the root.
'(:allhomes)))
(persistents (sh `(sh:pipe (dockutil ,@dockutil-args #\L)
(grep "/nix/store")
;; Whatever, this works.
(grep "persistentApps")
;; I feel like using the bundle ID would be
;; cleaner (org.gnu.Emacs etc) but dockutil only
;; works reliably when I use the “bundle name”,
;; which is just the file’s basename without
;; extension. Ok.
(cut #\f 1))
:output :lines)))
(dolist (existing persistents)
(alex:when-let ((app (find existing
(mapcar #'path-without-slash apps)
:test #'equal
:key #'pathname-name)))
;; I was passed an app with the same name as an existing persistent dock
;; item. Yes this restarts after every item but I don’t know how to
;; only restart exactly once.
(sh `(dockutil
,@dockutil-args
:add ,(realpath app)
:replacing ,existing))))))
;;; sync-trampolines
(defun to-abs-dir (d)
"Transform d into an absolute directory pathname."
(uiop:ensure-pathname d
:ensure-absolute t
:defaults (uiop:getcwd)
:ensure-directory t))
(defun directory-name (d)
;; Weird lispism
(first (last (pathname-directory d))))
(defun gather-apps (dir)
(mapcan (lambda (pattern)
(directory (merge-pathnames pattern dir)))
;; Kind of a cheat, but I’ve noticed some apps nest themselves one
;; directory further, e.g. KDE apps in /Applications/Nix
;; Apps/KDE/Foo.app. There are many ways to deal with this, but
;; honestly just hard-coding one extra level of search is probably the
;; easiest. This nexting won’t survive in the trampoline directory,
;; but that doesn’t seem to matter.
'(#p "*.app" #p "*/*.app")))
(defun sync-trampolines (&rest args)
(destructuring-bind (from to) (mapcar #'to-abs-dir args)
(rm-rf to)
(ensure-directories-exist to)
(let ((apps (gather-apps from)))
(dolist (app apps)
(mktrampoline app (merge-pathnames (directory-name app) to)))
(sync-dock apps))))
;;; CLI
(defun print-usage ()
(format T "Usage:
mac-app-util mktrampoline FROM.app TO.app
mac-app-util sync-dock Foo.app Bar.app ...
mac-app-util sync-trampolines /my/nix/Applications /Applications/MyTrampolines/
mktrampline creates a “trampoline” application launcher that immediately
launches another application.
sync-dock updates persistent items in your dock if any of the given apps has the
same name. This can be used to programmatically keep pinned items in your dock
up to date with potential new versions of an app outside of the /Applications
directory, without having to check which one is pinned etc.
sync-trampolines is an all-in-1 solution that syncs an entire directory of *.app
files to another by creating a trampoline launcher for every app, deleting the
rest, and updating the dock.
"))
(defun main ()
(let ((args (uiop:command-line-arguments)))
(if (intersection args '("-h" "--help") :test #'equal)
(progn
(print-usage)
(uiop:quit 0))
(trivia:match args
((list "mktrampoline" from to)
(mktrampoline from to))
((list* "sync-dock" apps)
(sync-dock apps))
((list "sync-trampolines" from to)
(sync-trampolines from to))
(_
(print-usage)
(uiop:quit 1))))))
(main)