aboutsummaryrefslogtreecommitdiff
path: root/e2e/lib/clipboard.ts
blob: 46da0b8bfb60311f3dec954a20e6dceea4d0a6b8 (plain) (blame)
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
import { spawn } from "child_process";

const readLinux = (): Promise<string> => {
  let stdout = "",
    stderr = "";
  return new Promise((resolve) => {
    const xsel = spawn("xsel", ["--clipboard", "--output"]);
    xsel.stdout.on("data", (data) => {
      stdout += data;
    });
    xsel.stderr.on("data", (data) => {
      stderr += data;
    });
    xsel.on("close", (code) => {
      if (code !== 0) {
        throw new Error(`xsel returns ${code}: ${stderr}`);
      }
      resolve(stdout);
    });
  });
};

const writeLinux = (data: string): Promise<void> => {
  let stderr = "";
  return new Promise((resolve) => {
    const xsel = spawn("xsel", ["--clipboard", "--input"]);
    xsel.stderr.on("data", (data) => {
      stderr += data;
    });
    xsel.on("close", (code) => {
      if (code !== 0) {
        throw new Error(`xsel returns ${code}: ${stderr}`);
      }
      resolve();
    });
    xsel.stdin.write(data);
    xsel.stdin.end();
  });
};

const readDarwin = (): Promise<string> => {
  let stdout = "",
    stderr = "";
  return new Promise((resolve) => {
    const pbpaste = spawn("pbpaste");
    pbpaste.stdout.on("data", (data) => {
      stdout += data;
    });
    pbpaste.stderr.on("data", (data) => {
      stderr += data;
    });
    pbpaste.on("close", (code) => {
      if (code !== 0) {
        throw new Error(`pbpaste returns ${code}: ${stderr}`);
      }
      resolve(stdout);
    });
  });
};

const writeDarwin = (data: string): Promise<void> => {
  let stderr = "";
  return new Promise((resolve) => {
    const pbcopy = spawn("pbcopy");
    pbcopy.stderr.on("data", (data) => {
      stderr += data;
    });
    pbcopy.on("close", (code) => {
      if (code !== 0) {
        throw new Error(`pbcopy returns ${code}: ${stderr}`);
      }
      resolve();
    });
    pbcopy.stdin.write(data);
    pbcopy.stdin.end();
  });
};

class UnsupportedError extends Error {
  constructor(platform: string) {
    super();
    this.message = `Unsupported platform: ${platform}`;
  }
}

const read = () => {
  switch (process.platform) {
    case "linux":
      return readLinux();
    case "darwin":
      return readDarwin();
  }
  throw new UnsupportedError(process.platform);
};

const write = (data: string) => {
  switch (process.platform) {
    case "linux":
      return writeLinux(data);
    case "darwin":
      return writeDarwin(data);
  }
  throw new UnsupportedError(process.platform);
};

export { read, write };