aboutsummaryrefslogtreecommitdiff
path: root/e2e/lib/clipboard.ts
blob: 13d95df83773da43b3e971ca1dfdb61ec58525e4 (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
import { spawn } from 'child_process';

const readLinux = (): Promise<string> => {
  let stdout = '', stderr = '';
  return new Promise((resolve) => {
    let 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<string> => {
  let stderr = '';
  return new Promise((resolve) => {
    let 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();
  });
};

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

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

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

export {
  read,
  write,
};