forked from NotePlan/plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.js
More file actions
210 lines (191 loc) · 6.11 KB
/
shared.js
File metadata and controls
210 lines (191 loc) · 6.11 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
'use strict'
const fs = require('fs/promises')
const os = require('os')
const username = os.userInfo().username
const path = require('path')
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const inquirer = require('inquirer')
const JSON5 = require('json5')
const colors = require('colors')
const pluginPathFile = path.join(__dirname, '..', '.pluginpath')
/**
*
* @param {string} fullPath
* @returns {Promise<boolean>} whether file exists
*/
async function fileExists(fullPath) {
try {
await fs.stat(fullPath)
return true
} catch (e) {
return false
}
}
async function getFolderFromCommandLine(rootFolderPath, args, minimalOutput = false) {
// const args = process.argv.slice(2)
const limitToFolders = []
if (args.length) {
if (!minimalOutput) {
console.log(`[Shared] Script will be limited to: ${JSON.stringify(args)}`)
}
for (const arg of args) {
if (await fileExists(path.join(rootFolderPath, arg))) {
limitToFolders.push(arg)
// console.log(`stat returned: ${JSON.stringify(stat)}`)
} else {
console.log(
colors.red(
`\nERROR: Invalid Argument: "${arg}"\n \n Path: "${path.join(
rootFolderPath,
arg,
)}" does not exist.\n\n Make sure you are invoking with just the top-level folder name, \n e.g., jgclark.DailyJournal`,
),
)
process.exit(0)
}
}
}
return limitToFolders
}
async function runShellCommand(command) {
try {
const { error, stdout, stderr } = await exec(command)
if (error) console.log('runShellCommand error:', error)
// if (stdout.length) console.log('runShellCommand stdout:\n', stdout)
if (stderr.length) console.log('runShellCommand stderr:', stderr)
return String(stdout)
} catch (err) {
console.log(`\n**\n**\n**\n[shared.js] command "${command}" did not work.`)
console.error(err)
process.exit(0)
return ''
}
}
async function getPluginFileContents(pluginPath) {
let pluginFile, pluginObj
try {
pluginFile = await fs.readFile(pluginPath, 'utf8')
pluginObj = await JSON5.parse(pluginFile)
// pluginObj = await JSON.parse(pluginFile)
} catch (e) {
console.log(`getPluginFileContents: Problem reading JSON file:\n ${pluginPath}`)
console.log(`Often this is simply a non-standard trailing comma that the parser doesn't like.`)
console.log(e)
}
return pluginObj || {}
}
/**
* @param {string} pathToRead
* @param {string} pathToWrite
* @returns {Promise<void>}
* @description Copies plugin contents for distribution but minifies/removes comments first
*/
async function writeMinifiedPluginFileContents(pathToRead, pathToWrite) {
try {
const contents = await fs.readFile(pathToRead, 'utf8')
const j5 = JSON5.parse(contents)
await fs.writeFile(pathToWrite, JSON.stringify(j5, null, 2))
} catch (e) {
console.log(`writePluginFileContents: Problem writing JSON file: ${pathToWrite}`)
console.log(e)
}
}
async function getCopyTargetPath(dirents) {
const hasPluginPathFile = dirents.some((dirent) => dirent.name === '.pluginpath')
if (hasPluginPathFile) {
const path = await fs.readFile(pluginPathFile, 'utf8')
// Cleanup any newlines from the path value
return path.replace(/\r?\n|\r/g, '')
}
const { shouldCopy } = await inquirer.prompt([
{
type: 'list',
name: 'shouldCopy',
message: 'Could not a find a file called ".pluginpath". Do you want to auto-copy compiled plugins to the Noteplan plugin directory?',
choices: [
{ name: 'Yes', value: true },
{ name: 'No', value: false },
],
},
])
if (!shouldCopy) {
return null
}
let pluginPath
do {
const { inputPath } = await inquirer.prompt([
{
type: 'input',
name: 'inputPath',
default: `/Users/${username}/Library/Containers/co.noteplan.NotePlan3/Data/Library/Application Support/co.noteplan.NotePlan3/Plugins`,
message: `Enter the absolute path to the noteplan Plugins folder below. (Should start with "/" end with "/Plugins" -- No trailing slash and no escapes (backslashes, e.g. avoid "\\ ") in the path. On a Mac, it would be something like the suggestion below\n[type path or enter to accept this suggestion.]\n>>`,
},
])
pluginPath = inputPath
} while (!pluginPath.endsWith('/Plugins') || !pluginPath.startsWith('/'))
const { shouldCreateFile } = await inquirer.prompt([
{
type: 'list',
name: 'shouldCreateFile',
message: 'Do you want to save this file for later?',
choices: [
{ name: 'Yes', value: true },
{ name: 'No', value: false },
],
},
])
if (shouldCreateFile) {
await fs.writeFile(pluginPathFile, pluginPath)
}
return pluginPath
}
async function getPluginConfig(key = null, defaultValue = null) {
try {
const data = await fs.readFile('.pluginsrc')
if (data && !key) {
return data
} else {
if (data) {
const configData = await JSON5.parse(data)
return configData.hasOwnProperty(key) ? configData[key] : defaultValue || null
}
return defaultValue
}
} catch (error) {
//
}
}
function caseSensitiveImports() {
return {
name: 'case-sensitive-imports',
async resolveId(source, importer) {
if (!importer) {
// Entry module, skip checks
return null
}
const resolvedPath = path.resolve(path.dirname(importer), source)
try {
// Check if the file or directory exists
await fs.stat(resolvedPath)
} catch (err) {
return null
}
const actualName = (await fs.readdir(path.dirname(resolvedPath))).find((file) => file === path.basename(resolvedPath))
if (!actualName) {
this.warn(`Cannot find import '${resolvedPath}'. Check for missing file or case mismatch in file name.`)
}
return null // Let Rollup handle the normal resolution
},
}
}
module.exports = {
fileExists,
getPluginFileContents,
runShellCommand,
getFolderFromCommandLine,
writeMinifiedPluginFileContents,
getCopyTargetPath,
getPluginConfig,
caseSensitiveImports,
}