summaryrefslogtreecommitdiff
path: root/packages/anastasis-cli/src/index.ts
blob: 7c011569facdc0819d09b8ab44feaaddae3ae398 (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
import { clk } from "@gnu-taler/taler-util/clk";
import {
  discoverPolicies,
  getBackupStartState,
  getRecoveryStartState,
  reduceAction,
} from "@gnu-taler/anastasis-core";
import fs from "fs";
import { j2s } from "@gnu-taler/taler-util";

export const reducerCli = clk.program("anastasis-cli", {
  help: "Command line interface for Anastasis.",
});

reducerCli
  .subcommand("reducer", "reduce", {
    help: "Run the anastasis reducer",
  })
  .flag("initBackup", ["-b", "--backup"])
  .flag("initRecovery", ["-r", "--restore"])
  .maybeOption("argumentsJson", ["-a", "--arguments"], clk.STRING)
  .maybeArgument("action", clk.STRING)
  .maybeArgument("stateFile", clk.STRING)
  .action(async (x) => {
    if (x.reducer.initBackup) {
      console.log(JSON.stringify(await getBackupStartState()));
      return;
    } else if (x.reducer.initRecovery) {
      console.log(JSON.stringify(await getRecoveryStartState()));
      return;
    }

    const action = x.reducer.action;
    if (!action) {
      console.log("action required");
      return;
    }

    let lastState: any;
    if (x.reducer.stateFile) {
      const s = fs.readFileSync(x.reducer.stateFile, { encoding: "utf-8" });
      lastState = JSON.parse(s);
    } else {
      const s = await read(process.stdin);
      lastState = JSON.parse(s);
    }

    let args: any;
    if (x.reducer.argumentsJson) {
      args = JSON.parse(x.reducer.argumentsJson);
    } else {
      args = {};
    }

    const nextState = await reduceAction(lastState, action, args);
    console.log(JSON.stringify(nextState));
  });

reducerCli
  .subcommand("discover", "discover", {
    help: "Run the anastasis reducer",
  })
  .maybeArgument("stateFile", clk.STRING)
  .action(async (args) => {
    let lastState: any;
    if (args.discover.stateFile) {
      const s = fs.readFileSync(args.discover.stateFile, { encoding: "utf-8" });
      lastState = JSON.parse(s);
    } else {
      const s = await read(process.stdin);
      lastState = JSON.parse(s);
    }
    const res = await discoverPolicies(lastState);
    console.log(j2s(res));
  });

async function read(stream: NodeJS.ReadStream): Promise<string> {
  const chunks = [];
  for await (const chunk of stream) {
    chunks.push(chunk);
  }
  return Buffer.concat(chunks).toString("utf8");
}

export function reducerCliMain() {
  reducerCli.run();
}