~bmp/hayom

hayom/config.ts -rw-r--r-- 1.9 KiB
9392a780Benjamin Pollack readme: add build status a month ago
                                                                                
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
import { path, toml } from "./deps.ts";

export interface Config {
  editor: string[];
  default: string;
  journals: {
    [name: string]: {
      journal: string;
    };
  };
}

function homeDir(): string {
  if (Deno.build.os === "windows") {
    const home = Deno.env.get("USERPROFILE");
    if (home == null) throw new Error("USERPROFILE missing");
    return home;
  } else {
    const home = Deno.env.get("HOME");
    if (home == null) throw new Error("$HOME missing");
    return home;
  }
}

function configDir(): string {
  if (Deno.build.os === "windows") {
    const profile = Deno.env.get("APPDATA");
    if (profile == null) throw new Error("APPDATA missing");
    return profile;
  } else {
    let configRoot = Deno.env.get("XDG_CONFIG_HOME");
    if (configRoot == null) {
      configRoot = path.join(homeDir(), ".config");
    }
    return configRoot;
  }
}

function defaultConfigPath(): string {
  return path.join(configDir(), "hayom", "hayom.toml");
}

function defaultJournalPath(): string {
  return path.join(
    homeDir(),
    Deno.build.os === "windows" ? "hayom.txt" : ".hayom",
  );
}

function defaultEditor(): string[] {
  const editor = Deno.env.get("EDITOR");
  if (editor != null) return editor.split(" ");
  // FIXME: should do something more reasonable than this
  if (Deno.build.os == "windows") return ["notepad.exe"];
  else return ["nano"];
}

export function loadConfig(): Config {
  const defaultConfig: Config = {
    default: "default",
    editor: defaultEditor(),
    journals: {
      default: {
        journal: defaultJournalPath(),
      },
    },
  };

  try {
    const userConfig = toml.parse(Deno.readTextFileSync(defaultConfigPath()));
    const mergedConfig = { ...defaultConfig, ...userConfig };
    if (typeof userConfig.editor === "string") {
      mergedConfig.editor = userConfig.editor.split(" ");
    }
    return mergedConfig;
  } catch {
    return defaultConfig;
  }
}