|
| 1 | +(ns orchard.directory |
| 2 | + "A port of BaseDirectories.java in soc/directories-jvm. |
| 3 | + https://github.com/soc/directories-jvm" |
| 4 | + {:author "Masashi Iizuka" |
| 5 | + :added "0.5.0"} |
| 6 | + (:require [clojure.java.io :as io] |
| 7 | + [clojure.string :as str] |
| 8 | + [orchard.misc :as u]) |
| 9 | + (:import (java.io BufferedReader))) |
| 10 | + |
| 11 | +(def file-separator (System/getProperty "file.separator")) |
| 12 | + |
| 13 | +(defn- run-commands [expected-result-lines commands] |
| 14 | + (let [commands ^"[Ljava.lang.String;" (into-array String commands) |
| 15 | + builder (ProcessBuilder. commands) |
| 16 | + process (.start builder)] |
| 17 | + (with-open [reader ^BufferedReader (io/reader (.getInputStream process))] |
| 18 | + (try |
| 19 | + (doall (repeatedly expected-result-lines #(.readLine reader))) |
| 20 | + (finally |
| 21 | + (.destroy process)))))) |
| 22 | + |
| 23 | +(defn- get-win-dirs [guids] |
| 24 | + (let [commands (concat ["& {" |
| 25 | + "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8" |
| 26 | + "Add-Type @\\\"" |
| 27 | + "using System;" |
| 28 | + "using System.Runtime.InteropServices;" |
| 29 | + "public class Dir {" |
| 30 | + " [DllImport(\\\"shell32.dll\\\")]" |
| 31 | + " private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);" |
| 32 | + " public static string GetKnownFolderPath(string rfid) {" |
| 33 | + " IntPtr pszPath;" |
| 34 | + " if (SHGetKnownFolderPath(new Guid(rfid), 0, IntPtr.Zero, out pszPath) != 0) return \\\"\\\";" |
| 35 | + " string path = Marshal.PtrToStringUni(pszPath);" |
| 36 | + " Marshal.FreeCoTaskMem(pszPath);" |
| 37 | + " return path;" |
| 38 | + " }" |
| 39 | + "}" |
| 40 | + "\\\"@"] |
| 41 | + (map #(str "[Dir]::GetKnownFolderPath(\\\"" % "\\\")") guids) |
| 42 | + ["}"])] |
| 43 | + (run-commands (count guids) ["powershell.exe" "-Command" (str/join "\n" commands)]))) |
| 44 | + |
| 45 | +(defn cache-dir |
| 46 | + "Returns the path to the user's cache directory. |
| 47 | +
|
| 48 | + macOS : $HOME/Library/Caches |
| 49 | + Windows: FOLDERID_LocalAppData\\cache |
| 50 | + Others : $XDG_CACHE_HOME or $HOME/.cache" |
| 51 | + {:added "0.5.0"} |
| 52 | + [] |
| 53 | + (case u/os-type |
| 54 | + ::u/os-mac |
| 55 | + (str/join file-separator [(System/getProperty "user.home") |
| 56 | + "Library" |
| 57 | + "Caches"]) |
| 58 | + |
| 59 | + ::u/os-windows |
| 60 | + (-> ["F1B32785-6FBA-4FCF-9D55-7B8E7F157091"] |
| 61 | + get-win-dirs |
| 62 | + first) |
| 63 | + |
| 64 | + (let [cache-home (System/getenv "XDG_CACHE_HOME")] |
| 65 | + (if (str/blank? cache-home) |
| 66 | + (str (System/getProperty "user.home") file-separator ".cache") |
| 67 | + cache-home)))) |
0 commit comments