« get me outta code hell

repl.js « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/repl.js
blob: 26879be4a55dd7f3a5618f394c37748e2df6eed8 (plain)
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
import * as os from 'node:os';
import * as path from 'node:path';
import * as repl from 'node:repl';
import {fileURLToPath} from 'node:url';

import {logError, logWarn, parseOptions} from '#cli';
import {isMain} from '#node-utils';
import {processLanguageFile} from '#language';
import {bindOpts, showAggregate} from '#sugar';
import {generateURLs, urlSpec} from '#urls';
import {quickLoadAllFromYAML} from '#yaml';

import _find, {bindFind} from '#find';
import CacheableObject from '#cacheable-object';
import thingConstructors from '#things';
import * as serialize from '#serialize';
import * as sugar from '#sugar';
import * as wikiDataUtils from '#wiki-data';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export async function getContextAssignments({
  dataPath,
  mediaPath,
  wikiData,
}) {
  let urls;
  try {
    urls = generateURLs(urlSpec);
  } catch (error) {
    console.error(error);
    logWarn`Failed to generate URL mappings for built-in urlSpec`;
    logWarn`\`urls\` variable will be missing`;
  }

  let find;
  try {
    find = bindFind(wikiData);
  } catch (error) {
    console.error(error);
    logWarn`Failed to prepare wikiData-bound find() functions`;
    logWarn`\`find\` variable will be missing`;
  }

  let language;
  try {
    language = await processLanguageFile(
      path.join(
        path.dirname(fileURLToPath(import.meta.url)),
        'strings-default.json'));
  } catch (error) {
    console.error(error);
    logWarn`Failed to create Language object`;
    logWarn`\`language\` variable will be missing`;
    language = undefined;
  }

  return {
    dataPath,
    mediaPath,

    wikiData,
    ...wikiData,
    WD: wikiData,

    ...thingConstructors,
    CacheableObject,
    language,

    ...sugar,
    ...wikiDataUtils,

    serialize,
    S: serialize,

    urls,

    _find,
    find,
    bindFind,
  };
}

export default async function bootRepl({
  dataPath = process.env.HSMUSIC_DATA,
  mediaPath = process.env.HSMUSIC_MEDIA,
  disableHistory = false,
  showTraces = false,
}) {
  if (!dataPath) {
    logError`Expected --data-path option or HSMUSIC_DATA to be set`;
    return;
  }

  if (!mediaPath) {
    logError`Expected --media-path option or HSMUSIC_MEDIA to be set`;
    return;
  }

  console.log('HSMusic data REPL');

  const wikiData = await quickLoadAllFromYAML(dataPath, {
    showAggregate: bindOpts(showAggregate, {
      showTraces,
      pathToFileURL: (f) => path.relative(__dirname, fileURLToPath(f)),
    }),
  });

  const replServer = repl.start();

  Object.assign(replServer.context, await getContextAssignments({
    dataPath,
    mediaPath,
    wikiData,
  }));

  if (disableHistory) {
    console.log(`\rInput history disabled (--no-repl-history provided)`);
    replServer.displayPrompt(true);
  } else {
    const historyFile = path.join(os.homedir(), '.hsmusic_repl_history');
    replServer.setupHistory(historyFile, (err) => {
      if (err) {
        console.error(
          `\rFailed to begin locally logging input history to ${historyFile} (provide --no-repl-history to disable)`
        );
      } else {
        console.log(
          `\rLogging input history to ${historyFile} (provide --no-repl-history to disable)`
        );
      }
      replServer.displayPrompt(true);
    });
  }

  // Is this called breaking a promise?
  await new Promise(() => {});

  return true;
}

async function main() {
  const miscOptions = await parseOptions(process.argv.slice(2), {
    'data-path': {
      type: 'value',
    },

    'media-path': {
      type: 'value',
    },

    'no-repl-history': {
      type: 'flag',
    },

    'show-traces': {
      type: 'flag',
    },
  });

  return bootRepl({
    dataPath: miscOptions['data-path'],
    mediaPath: miscOptions['media-path'],
    disableHistory: miscOptions['no-repl-history'],
    showTraces: miscOptions['show-traces'],
  });
}

if (isMain(import.meta.url)) {
  main().catch((error) => {
    if (error instanceof AggregateError) {
      showAggregate(error);
    } else {
      console.error(error);
    }
  });
}