linux.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const path = require('path');
  3. const execa = require('execa');
  4. const xsel = 'xsel';
  5. const xselFallback = path.join(__dirname, '../fallbacks/linux/xsel');
  6. const copyArguments = ['--clipboard', '--input'];
  7. const pasteArguments = ['--clipboard', '--output'];
  8. const makeError = (xselError, fallbackError) => {
  9. let error;
  10. if (xselError.code === 'ENOENT') {
  11. error = new Error('Couldn\'t find the `xsel` binary and fallback didn\'t work. On Debian/Ubuntu you can install xsel with: sudo apt install xsel');
  12. } else {
  13. error = new Error('Both xsel and fallback failed');
  14. error.xselError = xselError;
  15. }
  16. error.fallbackError = fallbackError;
  17. return error;
  18. };
  19. const xselWithFallback = async (argumentList, options) => {
  20. try {
  21. return await execa.stdout(xsel, argumentList, options);
  22. } catch (xselError) {
  23. try {
  24. return await execa.stdout(xselFallback, argumentList, options);
  25. } catch (fallbackError) {
  26. throw makeError(xselError, fallbackError);
  27. }
  28. }
  29. };
  30. const xselWithFallbackSync = (argumentList, options) => {
  31. try {
  32. return execa.sync(xsel, argumentList, options);
  33. } catch (xselError) {
  34. try {
  35. return execa.sync(xselFallback, argumentList, options);
  36. } catch (fallbackError) {
  37. throw makeError(xselError, fallbackError);
  38. }
  39. }
  40. };
  41. module.exports = {
  42. copy: async options => {
  43. await xselWithFallback(copyArguments, options);
  44. },
  45. copySync: options => {
  46. xselWithFallbackSync(copyArguments, options);
  47. },
  48. paste: options => xselWithFallback(pasteArguments, options),
  49. pasteSync: options => xselWithFallbackSync(pasteArguments, options)
  50. };