/
textexpander-to-alfred3.js
92 lines (73 loc) · 2.33 KB
/
textexpander-to-alfred3.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
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')
const archiver = require('archiver')
const sanitize = require('sanitize-filename')
const plist = require('plist')
const program = require('commander')
program
.version('0.1.2')
.usage('<file>')
.option('<file>', '.textexpander source file')
.parse(process.argv)
// show help by default
if (!process.argv.slice(2).length) {
program.outputHelp()
} else {
main()
}
function transformSnippet (snippet) {
const name = !snippet.label || snippet.label === '' ? snippet.abbreviation.slice(0, 10) : snippet.label
return {
filename: sanitize(name) + ' [' + snippet.uuidString + '].json',
usable: Boolean(snippet.plainText),
content: JSON.stringify({
alfredsnippet: {
snippet: snippet.plainText ? snippet.plainText.replace(/%clipboard/g, '{clipboard}').replace(/%\|/g, '{cursor}') : false,
name: name,
uid: snippet.uuidString,
keyword: snippet.abbreviation
}
}, null, 2)
}
}
function main () {
let plistPath = program.args[0]
if (!path.isAbsolute(plistPath)) {
plistPath = path.join(process.cwd(), program.args[0])
}
fs.readFile(plistPath, 'utf-8', function (err, plistString) {
if (err) { throw err }
const basename = path.basename(program.args[0], '.textexpander')
const outFile = path.join(process.cwd(), (basename + '.alfredsnippets'))
const output = fs.createWriteStream(outFile)
const archive = textexpander2Alfred(plistString)
archive.pipe(output)
output.on('close', function () {
console.log(`Wrote file ${outFile}`)
})
})
}
function textexpander2Alfred (plistString) {
const parsedPlist = plist.parse(plistString)
const archive = archiver('zip')
// Use the TextExpander 3 snippet collection, if available.
// The `snippetsTE2` key is included in the v3 snippet plist file
// with a warning message in case someone using TextExpander v2 tries
// to import a v3 snippet file.
const snippets = parsedPlist.snippetsTE3 || parsedPlist.snippetsTE2
snippets
.map(transformSnippet)
.filter((snippet) => {
return snippet.usable
})
.forEach(function (snippet) {
archive.append(snippet.content, {
name: snippet.filename
})
})
archive.finalize()
return archive
}
module.exports = textexpander2Alfred