aboutsummaryrefslogtreecommitdiff
path: root/lib/remote.js
blob: ad0a4fc77f2a71aa64dd8bd6856957c21708caa3 (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
import { readFile, writeFile } from 'fs/promises';
import { rmIfExists } from './utils.js';

import GitStrategy from './remotes/git.js';

const internals = {
  strings: {
    configurationNotFound: 'Remote configuration not set, consult help for more info.'
  },
  strategies: [
    GitStrategy
  ]
};

export default {
  async add(remoteConfig, remote) {

    await writeFile(remoteConfig, remote);
  },

  async remove(remoteConfig) {

    await rmIfExists(remoteConfig);
  },

  async syncUp(remoteConfig, blogDirectory) {

    await this._executeMethodOnStrategy(remoteConfig, 'syncUp', blogDirectory);
  },

  async syncDown(remoteConfig, blogDirectory) {

    await this._executeMethodOnStrategy(remoteConfig, 'syncDown', blogDirectory);
  },

  async _executeMethodOnStrategy(remoteConfig, method, blogDirectory) {

    const remote = await this._ensureConfiguration(remoteConfig);

    for (const strategy of internals.strategies) {
      if (strategy.canHandle(remote)) {
        await strategy[method](remote, blogDirectory);
      }
    }
  },

  async _ensureConfiguration(remoteConfig) {

    try {
      const configuration = await readFile(remoteConfig, { encoding: 'utf8' });
      return configuration;
    }
    catch {
      throw new Error(internals.strings.configurationNotFound);
    }
  }
};