forked from jhuckaby/clipdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·80 lines (64 loc) · 2.04 KB
/
index.js
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
#!/usr/bin/env node
// clipdown
// Convert rich HTML to Markdown in your clipboard.
// Currently only works on macOS.
// Copyright (c) 2019 Joseph Huckaby, PixlCore.com, MIT Licensed
const fs = require('fs');
const os = require('os');
const cp = require('child_process');
const breakdance = require('breakdance');
const sanitizeHTML = require('sanitize-html');
if (os.platform() !== 'darwin') {
throw new Error("Sorry, this tool only works on macOS.");
}
const Args = require('pixl-args');
var args = (new Args({})).get();
const PBCOPY_BIN = '/usr/bin/pbcopy';
const OSASCRIPT_BIN = '/usr/bin/osascript';
process.chdir( __dirname );
// first, get clipboard contents as hex-encoded HTML
cp.exec( OSASCRIPT_BIN + ` -e 'the clipboard as "HTML"'`, function(err, stdout, stderr) {
if (err) throw err;
// extract HTML and decode
if (!stdout.match(/data HTML([0-9A-F]+)/)) {
throw new Error("Error: Did not find any HTML in your clipboard.");
}
var hex = RegExp.$1;
var html = Buffer.from(hex, 'hex').toString();
var shtml = sanitizeHTML(html, {
// sanitize-html doesn't allow h1 or h2 by default (facepalm) so we have to add them
allowedTags: sanitizeHTML.defaults.allowedTags.concat([ 'h1', 'h2' ])
});
var md = breakdance(shtml, args).trim();
if (args.debug) {
console.log( "Raw HTML: " + html + "\n" );
console.log( "Sanitized HTML: " + shtml + "\n" );
console.log( "Markdown: " + md + "\n" );
process.exit(0);
}
var child = null;
var child_cmd = PBCOPY_BIN;
var child_args = [];
var child_opts = {
stdio: ['pipe', 'ignore', 'ignore']
};
// spawn child
try {
child = cp.spawn( child_cmd, child_args, child_opts );
}
catch (err) {
throw new Error("Error: Could not execute command: " + child_cmd + ": " + err);
}
child.on('error', function (err) {
// child error
throw new Error("Error: Could not execute command: " + child_cmd + ": " + err);
} );
child.on('exit', function (code, signal) {
// child exited
process.exit(0);
});
if (child.stdin) {
child.stdin.write( md );
}
child.stdin.end();
}); // osascript