From a7861be39abb5b81065f3f1ad26d8cf50fc22502 Mon Sep 17 00:00:00 2001 From: dragonwocky Date: Tue, 6 Dec 2022 15:37:21 +1100 Subject: [PATCH] feat(cli): --quiet flag, split --dev into --json/--debug flags + added %PROGRAMW6432%/Notion/resources to potential resource paths (#779) + clearer separation of programmatic enhancement and cli interface + dep on vercel/arg for improved arg parsing --- .gitignore | 8 +- .yarnrc.yml | 4 + bin.mjs | 163 +++++++++++++++++++ package.json | 27 +-- {src/desktop => scripts}/apply.mjs | 50 +++--- {src/desktop => scripts}/cli.mjs | 0 scripts/electron.mjs | 110 +++++++++++++ {src/desktop => scripts}/helpers.mjs | 0 {src/desktop => scripts}/remove.mjs | 0 src/browser/.github/workflows/submodules.yml | 20 --- src/desktop/bin.mjs | 144 ---------------- src/desktop/check.mjs | 63 ------- 12 files changed, 318 insertions(+), 271 deletions(-) create mode 100644 .yarnrc.yml create mode 100755 bin.mjs rename {src/desktop => scripts}/apply.mjs (65%) rename {src/desktop => scripts}/cli.mjs (100%) create mode 100644 scripts/electron.mjs rename {src/desktop => scripts}/helpers.mjs (100%) rename {src/desktop => scripts}/remove.mjs (100%) delete mode 100644 src/browser/.github/workflows/submodules.yml delete mode 100755 src/desktop/bin.mjs delete mode 100644 src/desktop/check.mjs diff --git a/.gitignore b/.gitignore index dbf0821..424379b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ -node_modules/* \ No newline at end of file +# dependencies +node_modules/ + +# yarn +yarn.lock +.yarn/ +.pnp.* \ No newline at end of file diff --git a/.yarnrc.yml b/.yarnrc.yml new file mode 100644 index 0000000..36e01b3 --- /dev/null +++ b/.yarnrc.yml @@ -0,0 +1,4 @@ +nodeLinker: node-modules +yarnPath: .yarn/releases/yarn-3.3.0.cjs + +enableMessageNames: false diff --git a/bin.mjs b/bin.mjs new file mode 100755 index 0000000..3e7594a --- /dev/null +++ b/bin.mjs @@ -0,0 +1,163 @@ +#!/usr/bin/env node + +/** + * notion-enhancer + * (c) 2022 dragonwocky (https://dragonwocky.me/) + * (https://notion-enhancer.github.io/) under the MIT license + */ + +import arg from "arg"; +import chalk from "chalk-template"; +import os from "node:os"; +import { createRequire } from "node:module"; +import { checkEnhancementStatus, setNotionPath } from "./scripts/electron.mjs"; + +let __quiet = false; +const nodeRequire = createRequire(import.meta.url), + manifest = nodeRequire("./package.json"), + stdout = (...args) => __quiet || process.stdout.write(chalk(...args)), + stdoutRaw = (value) => __quiet || console.log(value); + +const commands = [ + // ["command", "description"] + ["apply", "add enhancements to the notion app"], + ["remove", "return notion to its pre-enhanced/pre-modded state"], + ["check", "check the current state of the notion app"], + ], + options = [ + // ["comma, separated, aliases", [type, "description"]] + [ + "--path=", + [String, "provide notion installation location (defaults to auto-detected)"], + ], + ["--backup", [Boolean, ""]], + ["--overwrite", [Boolean, ""]], + ["-y, --yes", [Boolean, 'skip prompts; assume "yes" and run non-interactively']], + ["-n, --no", [Boolean, 'skip prompts; assume "no" and run non-interactively']], + ["-q, --quiet", [Boolean, "hide all output"]], + ["-d, --debug", [Boolean, "show detailed error messages"]], + ["-j, --json", [Boolean, "display json output"]], + ["-h, --help", [Boolean, "display usage information"]], + ["-v, --version", [Boolean, "display version number"]], + ], + compileOptsToArgSpec = () => { + const args = {}; + for (const [opt, [type]] of options) { + const aliases = opt.split(", ").map((alias) => alias.split("=")[0]), + param = aliases[1] ?? aliases[0]; + args[param] = type; + for (let i = 0; i < aliases.length; i++) { + if (aliases[i] === param) continue; + args[aliases[i]] = param; + } + } + return args; + }; + +const args = arg(compileOptsToArgSpec(options)), + printHelp = () => { + const cmdPad = Math.max(...commands.map(([cmd]) => cmd.length)), + optPad = Math.max(...options.map((opt) => opt[0].length)), + parseCmd = (cmd) => chalk` ${cmd[0].padEnd(cmdPad)} {grey :} ${cmd[1]}`, + parseOpt = (opt) => chalk` ${opt[0].padEnd(optPad)} {grey :} ${opt[1][1]}`; + stdout`{bold.rgb(245,245,245) ${manifest.name} v${manifest.version}} + {grey ${manifest.homepage}} + \n{bold.rgb(245,245,245) USAGE} + {yellow $} ${manifest.name} [options] + \n{bold.rgb(245,245,245) COMMANDS}\n${commands.map(parseCmd).join("\n")} + \n{bold.rgb(245,245,245) OPTIONS}\n${options.map(parseOpt).join("\n")}\n`; + }, + printVersion = () => { + if (args["--json"]) { + stdoutRaw({ + [manifest.name]: manifest.version, + node: process.version.slice(1), + platform: process.platform, + architecture: process.arch, + os: os.release(), + }); + } else { + const enhancerVersion = `${manifest.name}@v${manifest.version}`, + nodeVersion = `node@${process.version}`, + osVersion = `${process.platform}-${process.arch}/${os.release()}`; + stdout`${enhancerVersion} via ${nodeVersion} on ${osVersion}\n`; + } + }; +if (args["--quiet"]) __quiet = true; +if (args["--help"]) [printHelp(), process.exit()]; +if (args["--version"]) [printVersion(), process.exit()]; +if (args["--path"]) setNotionPath(args["--path"]); +switch (args["_"][0]) { + case "apply": { + break; + } + case "remove": { + break; + } + // case "apply": { + // stdout`{bold.rgb(245,245,245) [NOTION-ENHANCER] APPLY}`; + // const res = await apply(notionPath, { + // overwritePrevious: promptRes, + // patchPrevious: opts.get("patch") ? true : false, + // takeBackup: opts.get("no-backup") ? false : true, + // }); + // if (res) { + // log`{bold.rgb(245,245,245) SUCCESS} {green ✔}`; + // } else log`{bold.rgb(245,245,245) CANCELLED} {red ✘}`; + // break; + // } + // case "remove": { + // log`{bold.rgb(245,245,245) [NOTION-ENHANCER] REMOVE}`; + // const res = await remove(notionPath, { delCache: promptRes }); + // if (res) { + // log`{bold.rgb(245,245,245) SUCCESS} {green ✔}`; + // } else log`{bold.rgb(245,245,245) CANCELLED} {red ✘}`; + // break; + // } + case "check": + const status = checkEnhancementStatus(); + if (args["--json"]) [stdoutRaw(status), process.exit()]; + stdout`{bold.rgb(245,245,245) [NOTION-ENHANCER] CHECK:} `; + if (manifest.version === status.insertVersion) { + stdout`notion-enhancer v${manifest.version} applied.\n`; + } else if (status.insertVersion) { + stdout`notion-enhancer v${manifest.version} applied != v${status.insertVersion} cli.\n`; + } else if (status.appPath) { + stdout`notion-enhancer has not been applied (notion installation found).\n`; + } else { + stdout`notion installation not found (corrupted or nonexistent).\n`; + } + break; + default: + printHelp(); +} + +// function handleError(err) { +// if (opts.get("dev")) { +// const strs = [], +// tags = [], +// stack = err.stack.split("\n"); +// for (let i = 0; i < stack.length; i++) { +// const text = stack[i].replace(/^ /, " "); +// if (i === 0) { +// const [type, msg] = text.split(/:((.+)|$)/); +// strs.push("{bold.red "); +// tags.push(type); +// strs.push(":} "); +// tags.push(msg); +// } else { +// strs.push("{grey "); +// tags.push(text); +// strs.push("}"); +// tags.push(""); +// } +// if (i !== stack.length - 1) { +// strs.push("\n"); +// tags.push(""); +// } +// } +// log(strs, ...tags); +// } else { +// log`{bold.red Error:} ${err.message} {grey (run with -d for more information)}`; +// } +// } diff --git a/package.json b/package.json index b837521..cc64f3f 100644 --- a/package.json +++ b/package.json @@ -1,28 +1,21 @@ { "name": "notion-enhancer", - "version": "0.11.0", + "version": "0.11.1-dev", "author": "dragonwocky (https://dragonwocky.me/)", "description": "an enhancer/customiser for the all-in-one productivity workspace notion.so", - "homepage": "https://github.com/notion-enhancer/desktop", + "homepage": "https://notion-enhancer.github.io", + "repository": "github:notion-enhancer/desktop", + "bugs": "https://github.com/notion-enhancer/desktop/issues", + "funding": "https://github.com/sponsors/dragonwocky", "license": "MIT", - "bin": { - "notion-enhancer": "bin.mjs" - }, + "bin": "bin.mjs", "type": "module", "engines": { "node": ">=16.x.x" }, - "scripts": { - "test": "echo \"no test specified\"", - "preuninstall": "node bin.js remove -n" - }, "dependencies": { - "asar": "^3.1.0", - "chalk": "^4.1.2" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/notion-enhancer/desktop.git" + "arg": "^5.0.2", + "chalk-template": "^0.4.0" }, "keywords": [ "windows", @@ -40,7 +33,5 @@ "notion", "notion-enhancer" ], - "bugs": { - "url": "https://github.com/notion-enhancer/desktop/issues" - } + "packageManager": "yarn@3.3.0" } diff --git a/src/desktop/apply.mjs b/scripts/apply.mjs similarity index 65% rename from src/desktop/apply.mjs rename to scripts/apply.mjs index 859e399..9045932 100644 --- a/src/desktop/apply.mjs +++ b/scripts/apply.mjs @@ -1,19 +1,19 @@ /** * notion-enhancer - * (c) 2021 dragonwocky (https://dragonwocky.me/) + * (c) 2022 dragonwocky (https://dragonwocky.me/) * (https://notion-enhancer.github.io/) under the MIT license */ -import fs from 'fs'; -import fsp from 'fs/promises'; -import path from 'path'; -import asar from 'asar'; +import fs from "fs"; +import fsp from "fs/promises"; +import path from "path"; +import asar from "asar"; -import { log, line, spinner } from './cli.mjs'; -import { __dirname, pkg, findNotion, copyDir, readDirDeep } from './helpers.mjs'; +import { log, line, spinner } from "./cli.mjs"; +import { __dirname, pkg, findNotion, copyDir, readDirDeep } from "./helpers.mjs"; -import check from './check.mjs'; -import remove from './remove.mjs'; +import check from "./check.mjs"; +import remove from "./remove.mjs"; export default async function ( notionFolder = findNotion(), @@ -33,42 +33,42 @@ export default async function ( break; case 3: // diff version already applied log` * ${status.message}`; - const prompt = ['Y', 'y', 'N', 'n', ''], + const prompt = ["Y", "y", "N", "n", ""], res = prompt.includes(overwritePrevious) ? overwritePrevious - : await line.read(' {inverse > overwrite? [Y/n]:} ', prompt); - if (res.toLowerCase() === 'n') { + : await line.read(" {inverse > overwrite? [Y/n]:} ", prompt); + if (res.toLowerCase() === "n") { log` * keeping previous version: exiting`; return false; } - await remove(notionFolder, { cache: 'n' }); + await remove(notionFolder, { cache: "n" }); status = await check(notionFolder); } let s; - if (status.executable.endsWith('.asar')) { - s = spinner(' * unpacking app files').loop(); - asar.extractAll(status.executable, status.executable.replace(/\.asar$/, '')); + if (status.executable.endsWith(".asar")) { + s = spinner(" * unpacking app files").loop(); + asar.extractAll(status.executable, status.executable.replace(/\.asar$/, "")); s.stop(); } if (status.code === 0 && takeBackup) { - s = spinner(' * backing up default app').loop(); - if (status.executable.endsWith('.asar')) { - await fsp.rename(status.executable, status.executable + '.bak'); - status.executable = status.executable.replace(/\.asar$/, ''); + s = spinner(" * backing up default app").loop(); + if (status.executable.endsWith(".asar")) { + await fsp.rename(status.executable, status.executable + ".bak"); + status.executable = status.executable.replace(/\.asar$/, ""); } else { - await copyDir(status.executable, status.executable + '.bak'); + await copyDir(status.executable, status.executable + ".bak"); } s.stop(); } - s = spinner(' * inserting enhancements').loop(); + s = spinner(" * inserting enhancements").loop(); if (status.code === 0) { const notionFiles = (await readDirDeep(status.executable)) .map((file) => file.path) - .filter((file) => file.endsWith('.js') && !file.includes('node_modules')); + .filter((file) => file.endsWith(".js") && !file.includes("node_modules")); for (const file of notionFiles) { - const target = file.slice(status.executable.length + 1, -3).replace(/\\/g, '/'), + const target = file.slice(status.executable.length + 1, -3).replace(/\\/g, "/"), replacer = path.resolve(`${__dirname(import.meta)}/replacers/${target}.mjs`); if (fs.existsSync(replacer)) { await (await import(`./replacers/${target}.mjs`)).default(file); @@ -83,7 +83,7 @@ export default async function ( await copyDir(`${__dirname(import.meta)}/../insert`, node_modules); s.stop(); - s = spinner(' * recording version').loop(); + s = spinner(" * recording version").loop(); await fsp.writeFile( path.resolve(`${node_modules}/package.json`), `{ diff --git a/src/desktop/cli.mjs b/scripts/cli.mjs similarity index 100% rename from src/desktop/cli.mjs rename to scripts/cli.mjs diff --git a/scripts/electron.mjs b/scripts/electron.mjs new file mode 100644 index 0000000..48133db --- /dev/null +++ b/scripts/electron.mjs @@ -0,0 +1,110 @@ +/** + * notion-enhancer + * (c) 2022 dragonwocky (https://dragonwocky.me/) + * (https://notion-enhancer.github.io/) under the MIT license + */ + +import chalk from "chalk-template"; +import os from "node:os"; +import { promises as fsp, existsSync } from "node:fs"; +import { resolve } from "node:path"; +import { execSync } from "node:child_process"; +import { createRequire } from "node:module"; + +let __notionResources, __enhancerCache; +const nodeRequire = createRequire(import.meta.url), + platform = + process.platform === "linux" && os.release().toLowerCase().includes("microsoft") + ? "wsl" + : process.platform, + polyfillWslEnv = (name) => { + if (platform !== "wsl" || process.env[name]) return process.env[name]; + // adds a windows environment variable to process.env + // in a wsl environment, inc. path conversion + const value = execSync(`cmd.exe /c echo %${name}%`, { + encoding: "utf8", + stdio: "pipe", + }).trim(), + isAbsolutePath = /^[a-zA-Z]:[\\\/]/.test(value), + onSystemDrive = /^[\\\/]/.test(value); + if (isAbsolutePath) { + // e.g. C:\Program Files + const drive = value[0].toLowerCase(), + path = value.slice(2).replace(/\\/g, "/"); + process.env[name] = `/mnt/${drive}${path}`; + } else if (onSystemDrive) { + // e.g. \Program Files + const drive = polyfillWslEnv("SYSTEMDRIVE")[0].toLowerCase(), + path = value.replace(/\\/g, "/"); + process.env[name] = `/mnt/${drive}${path}`; + } else process.env[name] = value; + return process.env[name]; + }; + +const setNotionPath = (path) => { + // sets notion resource path to user provided value + // e.g. from cli + __notionResources = path; + }, + getNotionResources = () => { + if (__notionResources) return __notionResources; + polyfillWslEnv("LOCALAPPDATA"); + polyfillWslEnv("PROGRAMW6432"); + const potentialPaths = [ + // [["targeted", "platforms"], "/path/to/notion/resources"] + [["darwin"], `/Users/${process.env.USER}/Applications/Notion.app/Contents/Resources`], + [["darwin"], "/Applications/Notion.app/Contents/Resources"], + [["win32", "wsl"], resolve(`${process.env.LOCALAPPDATA}/Programs/Notion/resources`)], + [["win32", "wsl"], resolve(`${process.env.PROGRAMW6432}/Notion/resources`)], + // https://aur.archlinux.org/packages/notion-app/ + [["linux"], "/opt/notion-app"], + ]; + for (const [targetPlatforms, testPath] of potentialPaths) { + if (!targetPlatforms.includes(platform)) continue; + if (!existsSync(testPath)) continue; + __notionResources = testPath; + return __notionResources; + } + }, + getEnhancerCache = () => { + if (__enhancerCache) return __enhancerCache; + const home = platform === "wsl" ? polyfillWslEnv("HOMEPATH") : os.homedir(); + __enhancerCache = resolve(`${home}/.notion-enhancer`); + return __enhancerCache; + }; + +const checkEnhancementStatus = () => { + const resourcePath = (path) => resolve(`${getNotionResources()}/${path}`), + doesResourceExist = (path) => existsSync(resourcePath(path)); + + const isAppUnpacked = doesResourceExist("app"), + isAppPacked = doesResourceExist("app.asar"), + isBackupUnpacked = doesResourceExist("app.bak"), + isBackupPacked = doesResourceExist("app.asar.bak"), + isEnhancerInserted = doesResourceExist("app/node_module/notion-enhancer"), + enhancerInsertManifest = isEnhancerInserted + ? resourcePath("app/node_module/notion-enhancer/package.json") + : undefined; + + // prefer unpacked if both exist: extraction is slow + return { + appPath: isAppUnpacked + ? resourcePath("app") + : isAppPacked + ? resourcePath("app.asar") + : undefined, + backupPath: isBackupUnpacked + ? resourcePath("app.bak") + : isBackupPacked + ? resourcePath("app.asar.bak") + : undefined, + cachePath: existsSync(getEnhancerCache()) // + ? getEnhancerCache() + : undefined, + insertVersion: isEnhancerInserted + ? nodeRequire(enhancerInsertManifest).version + : undefined, + }; +}; + +export { checkEnhancementStatus, setNotionPath }; diff --git a/src/desktop/helpers.mjs b/scripts/helpers.mjs similarity index 100% rename from src/desktop/helpers.mjs rename to scripts/helpers.mjs diff --git a/src/desktop/remove.mjs b/scripts/remove.mjs similarity index 100% rename from src/desktop/remove.mjs rename to scripts/remove.mjs diff --git a/src/browser/.github/workflows/submodules.yml b/src/browser/.github/workflows/submodules.yml deleted file mode 100644 index 463aa5e..0000000 --- a/src/browser/.github/workflows/submodules.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: 'update submodules' - -on: - workflow_dispatch: - -jobs: - sync: - name: 'update submodules' - runs-on: ubuntu-latest - steps: - - name: checkout repo - uses: actions/checkout@v2 - with: - submodules: true - - name: pull updates - run: | - git pull --recurse-submodules - git submodule update --remote --recursive - - name: commit changes - uses: stefanzweifel/git-auto-commit-action@v4 diff --git a/src/desktop/bin.mjs b/src/desktop/bin.mjs deleted file mode 100755 index b9d17d5..0000000 --- a/src/desktop/bin.mjs +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env node - -/** - * notion-enhancer - * (c) 2021 dragonwocky (https://dragonwocky.me/) - * (https://notion-enhancer.github.io/) under the MIT license - */ - -'use strict'; - -import os from 'os'; - -import { pkg, findNotion } from './pkg/helpers.mjs'; -import { line, options, log, help, args, lastSpinner } from './pkg/cli.mjs'; - -import apply from './pkg/apply.mjs'; -import remove from './pkg/remove.mjs'; -import check from './pkg/check.mjs'; - -const manifest = pkg(), - opts = options({ - y: 'yes', - n: 'no', - d: 'dev', - h: 'help', - v: 'version', - }), - promptRes = opts.get('yes') ? 'y' : opts.get('no') ? 'n' : undefined; - -const displayHelp = () => { - help({ - name: manifest.name, - version: manifest.version, - link: manifest.homepage, - commands: [ - ['apply', 'add enhancements to the notion app'], - ['remove', 'return notion to its pre-enhanced/pre-modded state'], - ['check, status', 'check the current state of the notion app'], - ], - options: [ - ['-y, --yes', 'skip prompts'], - ['-n, --no', 'skip prompts'], - ['-d, --dev', 'show detailed error messages (for debug purposes)'], - [ - '--path=', - 'provide a file location to enhance (otherwise auto-picked)', - ], - ['--no-backup', 'skip backup (faster enhancement, but disables removal)'], - ['--patch', 'overwrite inserted files (useful for quick development/testing)'], - ['-h, --help', 'display usage information'], - ['-v, --version', 'display version number'], - ], - }); -}; -if (opts.get('help')) { - displayHelp(); - process.exit(0); -} - -if (opts.get('version')) { - log( - `${manifest.name}/${manifest.version} ${ - process.platform - }-${os.arch()}/${os.release()} node/${process.version}` - ); - process.exit(0); -} - -function handleError(err) { - if (opts.get('dev')) { - const strs = [], - tags = [], - stack = err.stack.split('\n'); - for (let i = 0; i < stack.length; i++) { - const text = stack[i].replace(/^ /, ' '); - if (i === 0) { - const [type, msg] = text.split(/:((.+)|$)/); - strs.push('{bold.red '); - tags.push(type); - strs.push(':} '); - tags.push(msg); - } else { - strs.push('{grey '); - tags.push(text); - strs.push('}'); - tags.push(''); - } - if (i !== stack.length - 1) { - strs.push('\n'); - tags.push(''); - } - } - log(strs, ...tags); - } else { - log`{bold.red Error:} ${err.message} {grey (run with -d for more information)}`; - } -} - -try { - const notionPath = opts.get('path') || findNotion(); - - switch (args()[0]) { - case 'apply': { - log`{bold.rgb(245,245,245) [NOTION-ENHANCER] APPLY}`; - const res = await apply(notionPath, { - overwritePrevious: promptRes, - patchPrevious: opts.get('patch') ? true : false, - takeBackup: opts.get('no-backup') ? false : true, - }); - if (res) { - log`{bold.rgb(245,245,245) SUCCESS} {green ✔}`; - } else log`{bold.rgb(245,245,245) CANCELLED} {red ✘}`; - break; - } - case 'remove': { - log`{bold.rgb(245,245,245) [NOTION-ENHANCER] REMOVE}`; - const res = await remove(notionPath, { delCache: promptRes }); - if (res) { - log`{bold.rgb(245,245,245) SUCCESS} {green ✔}`; - } else log`{bold.rgb(245,245,245) CANCELLED} {red ✘}`; - break; - } - case 'check': - case 'status': { - log`{bold.rgb(245,245,245) [NOTION-ENHANCER] CHECK}`; - const status = check(notionPath); - line.prev(); - if (opts.get('dev')) { - line.forward(24); - console.log(status); - } else { - line.forward(23); - line.write(': ' + status.message + '\r\n'); - } - break; - } - default: - displayHelp(); - } -} catch (err) { - if (lastSpinner) lastSpinner.stop(); - handleError(err); - process.exit(1); -} diff --git a/src/desktop/check.mjs b/src/desktop/check.mjs deleted file mode 100644 index 473dc4f..0000000 --- a/src/desktop/check.mjs +++ /dev/null @@ -1,63 +0,0 @@ -/** - * notion-enhancer - * (c) 2021 dragonwocky (https://dragonwocky.me/) - * (https://notion-enhancer.github.io/) under the MIT license - */ - -import fs from 'fs'; -import path from 'path'; - -import { pkg, findNotion, findEnhancerCache } from './helpers.mjs'; - -export default function (notionFolder = findNotion()) { - const resolvePath = (filepath) => path.resolve(`${notionFolder}/${filepath}`), - pathExists = (filepath) => fs.existsSync(resolvePath(filepath)), - enhancerVersion = pkg().version; - - const executableApp = pathExists('app'), - executableAsar = pathExists('app.asar'), - executable = executableApp ? 'app' : executableAsar ? 'app.asar' : undefined, - backupApp = pathExists('app.bak'), - backupAsar = pathExists('app.asar.bak'), - backup = backupApp ? 'app.bak' : backupAsar ? 'app.asar.bak' : undefined, - insert = pathExists('app/node_modules/notion-enhancer'), - insertVersion = insert - ? pkg(resolvePath('app/node_modules/notion-enhancer/package.json')).version - : undefined, - insertCache = findEnhancerCache(); - - const res = { - executable: executable ? resolvePath(executable) : undefined, - backup: backup ? resolvePath(backup) : undefined, - cache: fs.existsSync(insertCache) ? insertCache : undefined, - installation: path.resolve( - resolvePath('.') - .split(path.sep) - .reduceRight((prev, val) => { - if (val.toLowerCase().includes('notion') || prev.toLowerCase().includes('notion')) - prev = `${val}/${prev}`; - return prev; - }, '') - ), - }; - if (insert) { - if (insertVersion === enhancerVersion) { - res.code = 2; - res.version = enhancerVersion; - res.message = `notion-enhancer v${enhancerVersion} applied.`; - } else { - res.code = 3; - res.version = insertVersion; - res.message = `notion-enhancer v${insertVersion} found applied != v${enhancerVersion} package.`; - } - } else { - if (executable) { - res.code = 0; - res.message = 'notion-enhancer has not been applied.'; - } else { - res.code = 1; - res.message = 'notion installation has been corrupted, no executable found.'; - } - } - return res; -}