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
|
#!/usr/bin/env node
const { promises: { readFile, writeFile } } = require('fs')
const path = require('path')
const { homedir } = require('os')
const util = require('util');
const { exec } = require('child_process')
const JSON_FILE = path.resolve(homedir(), 'nixos/snippets.json')
const $ = async (cmd, input) => {
const stdout = await (new Promise((resolve, reject) => {
const ps = exec(cmd, (err, stdout) => err ? reject(err) : resolve(stdout))
if (typeof input === 'string') {
ps.stdin.end(input)
}
}))
return `${stdout}`.toString().trim()
}
const getSelection = () => $(`xclip -o`)
const saveToClipboard = text => $('xclip -i -selection clipboard', text)
const promptName = () => $(`sh -c 'echo -n "" | dmenu -p "Name :: "'`) // TODO: use input
// TODO: Show current tags
const promptTags = () => $(`sh -c 'echo -n "" | dmenu -p "Tags :: "'`)
.then(input => `${input}`.split(/\s+/g).filter(Boolean))
const getCurrentJson = async () => {
try {
const contents = await readFile(JSON_FILE, 'utf8')
return JSON.parse(contents.toString())
} catch(_) {
return {}
}
}
const setCurrentJson = (data) =>
writeFile(JSON_FILE, JSON.stringify(data, null, 2))
const promptSelect = async ls => $(`dmenu -p "Snippets :: "`, ls.join('\n'))
const saveSnippets = async () => {
const contents = await getSelection()
const currentSnippets = await getCurrentJson()
const name = await promptName()
const tags = await promptTags()
const data = {
...currentSnippets,
[name]: {
contents,
tags,
},
}
await setCurrentJson(data)
}
const loadSnippets = async () => {
const currentSnippets = await getCurrentJson()
const seperator = ' :: '
const menuInput = Object.entries(currentSnippets)
.map(([ name, { tags } ]) => `${name}${seperator}(${tags.join(', ')})`)
const selection = await promptSelect(menuInput)
if (selection) {
const name = selection.split(seperator)[0].trim()
const { contents } = currentSnippets[name] || {}
console.log(contents)
await saveToClipboard(contents)
}
}
const main = async () => {
try {
await saveToClipboard('foobaraa')
// await loadSnippets()
} catch(_) {
console.log('cancelled')
}
}
main()
|