comparison src/name/blackcap/clipman/Files.kt @ 0:be282c48010a

Incomplete; checking it in as a backup.
author David Barts <n5jrn@me.com>
date Tue, 14 Jan 2020 14:07:19 -0800
parents
children 33fbe3a78d84
comparison
equal deleted inserted replaced
-1:000000000000 0:be282c48010a
1 /*
2 * For dealing with files.
3 * BUG: does not ensure directories exist
4 */
5 package name.blackcap.clipman
6
7 import java.io.BufferedReader
8 import java.io.File
9 import java.io.FileReader
10 import java.util.Properties
11 import java.util.logging.FileHandler
12 import java.util.logging.Level
13 import java.util.logging.Logger
14 import java.util.logging.SimpleFormatter
15
16 /* OS Type */
17
18 enum class OS {
19 MAC, UNIX, WINDOWS, OTHER;
20 companion object {
21 private val rawType = System.getProperty("os.name")?.toLowerCase()
22 val type = if (rawType == null) {
23 OTHER
24 } else if (rawType.contains("win")) {
25 WINDOWS
26 } else if (rawType.contains("mac")) {
27 MAC
28 } else if (rawType.contains("nix") || rawType.contains("nux") || rawType.contains("aix") || rawType.contains("sunos")) {
29 UNIX
30 } else {
31 OTHER
32 }
33 }
34 }
35
36 /* joins path name components to java.io.File */
37
38 fun joinPath(base: String, vararg rest: String) = rest.fold(File(base), ::File)
39
40 /* file names */
41
42 private val SHORTNAME = "clipman"
43 private val LONGNAME = "name.blackcap." + SHORTNAME
44 private val HOME = System.getenv("HOME")
45 private val APPDATA = System.getenv("APPDATA")
46 private val PF_DIR = when (OS.type) {
47 OS.MAC -> joinPath(HOME, "Library", "Application Support", LONGNAME)
48 OS.WINDOWS -> joinPath(APPDATA, "Roaming", LONGNAME)
49 else -> joinPath(HOME, "." + SHORTNAME)
50 }
51 private val LF_DIR = when (OS.type) {
52 OS.MAC -> joinPath(HOME, "Library", "Application Support", LONGNAME)
53 OS.WINDOWS -> joinPath(APPDATA, "Local", LONGNAME)
54 else -> joinPath(HOME, "." + SHORTNAME)
55 }
56 val PROP_FILE = File(PF_DIR, SHORTNAME + ".properties")
57 val LOG_FILE = File(LF_DIR, SHORTNAME + ".log")
58
59 /* make some needed directories */
60
61 private fun File.makeIfNeeded() = if (exists()) { true } else { mkdirs() }
62
63 /* make some usable objects */
64
65 val PROPERTIES = run {
66 PF_DIR.makeIfNeeded()
67 PROP_FILE.createNewFile()
68 Properties().apply {
69 BufferedReader(FileReader(PROP_FILE)).use { load(it) }
70 }
71 }
72
73 val LOGGER = run {
74 LF_DIR.makeIfNeeded()
75 Logger.getLogger(LONGNAME).apply {
76 addHandler(FileHandler(LOG_FILE.toString()).apply {
77 formatter = SimpleFormatter() })
78 level = Level.CONFIG
79 useParentHandlers = false
80 }
81 }