Skip to content

Commit

Permalink
feat: adapt universal picgo config path
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Mar 15, 2024
1 parent 9e4a6bc commit 07cc413
Show file tree
Hide file tree
Showing 15 changed files with 268 additions and 27 deletions.
3 changes: 2 additions & 1 deletion libs/Universal-PicGo-Core/package.json
Expand Up @@ -30,7 +30,8 @@
"vite-plugin-node-polyfills": "^0.21.0"
},
"dependencies": {
"zhi-lib-base": "^0.8.0"
"zhi-lib-base": "^0.8.0",
"universal-picgo-store": "workspace:*"
},
"publishConfig": {
"access": "public"
Expand Down
37 changes: 35 additions & 2 deletions libs/Universal-PicGo-Core/src/core/UniversalPicGo.ts
Expand Up @@ -27,6 +27,9 @@ import { PluginHandler } from "../lib/PluginHandler"
import _ from "lodash-es"
import getClipboardImage from "../utils/getClipboardImage"
import { IBuildInEvent } from "../utils/enums"
import DB from "../utils/db"
import { hasNodeEnv, win } from "universal-picgo-store"
import { ensureFileSync, pathExistsSync } from "../utils/nodeUtils"

/*
* 通用 PicGO 对象定义
Expand All @@ -37,6 +40,7 @@ import { IBuildInEvent } from "../utils/enums"
class UniversalPicGo extends EventEmitter implements IPicGo {
private _config!: IConfig
private lifecycle!: Lifecycle
private db!: DB
private _pluginLoader!: PluginLoader
configPath: string
baseDir!: string
Expand All @@ -48,6 +52,7 @@ class UniversalPicGo extends EventEmitter implements IPicGo {
pluginHandler: PluginHandler
i18n!: II18nManager
VERSION: string = process.env.PICGO_VERSION ?? "unknown"

// GUI_VERSION?: string

get pluginLoader(): IPluginLoader {
Expand Down Expand Up @@ -196,9 +201,37 @@ class UniversalPicGo extends EventEmitter implements IPicGo {

// ===================================================================================================================

private initConfigPath(): void {}
private initConfigPath(): void {
console.log("win =>", win)
console.log("hasNodeEnv =>", hasNodeEnv)
if (hasNodeEnv) {
const os = win.require("os")
const fs = win.fs
const path = win.require("path")
const { homedir } = os
if (this.configPath === "") {
this.configPath = homedir() + "/.picgo/config.json"
}
if (path.extname(this.configPath).toUpperCase() !== ".JSON") {
this.configPath = ""
throw Error("The configuration file only supports JSON format.")
}
this.baseDir = path.dirname(this.configPath)
const exist = pathExistsSync(fs, path, this.configPath)
if (!exist) {
ensureFileSync(fs, path, `${this.configPath}`)
}
} else {
if (this.configPath === "") {
this.configPath = `picgo-config-${this.VERSION}.json`
}
}
}

private initConfig(): void {}
private initConfig(): void {
// this.db = new DB(this)
// this._config = this.db.read(true) as IConfig
}

private init(): void {}
}
Expand Down
70 changes: 70 additions & 0 deletions libs/Universal-PicGo-Core/src/utils/db.ts
@@ -0,0 +1,70 @@
import { IConfig, IPicGo } from "../types"
import { JSONStore } from "universal-picgo-store/src"
import { IJSON } from "universal-picgo-store"

class DB {
private readonly ctx: IPicGo
private readonly db: JSONStore
constructor(ctx: IPicGo) {
this.ctx = ctx
this.db = new JSONStore(this.ctx.configPath)

if (!this.db.has("picBed")) {
try {
this.db.set("picBed", {
uploader: "smms",
current: "smms",
})
} catch (e: any) {
this.ctx.log.error(e)
throw e
}
}
if (!this.db.has("picgoPlugins")) {
try {
this.db.set("picgoPlugins", {})
} catch (e: any) {
this.ctx.log.error(e)
throw e
}
}
}

read(flush?: boolean): IJSON {
return this.db.read(flush)
}

get(key: ""): any {
this.read(true)
return this.db.get(key)
}

set(key: string, value: any): void {
this.read(true)
return this.db.set(key, value)
}

has(key: string): boolean {
this.read(true)
return this.db.has(key)
}

unset(key: string, value: any): boolean {
this.read(true)
return this.db.unset(key, value)
}

saveConfig(config: Partial<IConfig>): void {
Object.keys(config).forEach((name: string) => {
this.set(name, config[name])
})
}

removeConfig(config: IConfig): void {
Object.keys(config).forEach((name: string) => {
this.unset(name, config[name])
})
}
}

export default DB
45 changes: 45 additions & 0 deletions libs/Universal-PicGo-Core/src/utils/nodeUtils.ts
@@ -0,0 +1,45 @@
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/

/**
* 实现 fs.pathExistsSync 函数
*
* @param fs
* @param path
* @param filePath
*/
export const pathExistsSync = (fs: any, path: any, filePath: string) => {
try {
fs.accessSync(path.join(filePath), fs.constants.F_OK)
return true
} catch (err: any) {
if (err && err.code === "ENOENT") {
return false
} else {
throw err
}
}
}

/**
* 实现 fs.ensureFileSync 函数
*
* @param fs
* @param path
* @param filePath
*/
export const ensureFileSync = (fs: any, path: any, filePath: string) => {
const directory = path.dirname(filePath)
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true })
}
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "")
}
}
22 changes: 20 additions & 2 deletions libs/Universal-PicGo-Store/.eslintrc.cjs
@@ -1,4 +1,22 @@
module.exports = {
root: true,
extends: ["./node_modules/@terwer/eslint-config-custom/typescript/index.cjs"],
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended", "turbo", "prettier"],

parser: "@typescript-eslint/parser",

plugins: ["@typescript-eslint", "prettier"],

rules: {
// Note: you must disable the base rule as it can report incorrect errors
semi: "off",
quotes: "off",
"no-undef": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-function": "off",
"turbo/no-undeclared-env-vars": "off",
"prettier/prettier": "error",
},
}
3 changes: 2 additions & 1 deletion libs/Universal-PicGo-Store/.gitignore
@@ -1,2 +1,3 @@
.idea
.DS_Store
.DS_Store
dist
18 changes: 6 additions & 12 deletions libs/Universal-PicGo-Store/src/index.ts
@@ -1,13 +1,7 @@
import { simpleLogger, MainFunction } from "zhi-lib-base"
import { JSONStore } from "./lib/JSONStore"
import { win, hasNodeEnv } from "./lib/utils"
import { IJSON } from "./types"

/**
* 初始化入口
*
* @param args
*/
const main: MainFunction = async (args: any[]) => {
const logger = simpleLogger("main", "zhi", false)
return "ok"
}

export default main
export { type IJSON }
export { JSONStore }
export { win, hasNodeEnv }
40 changes: 40 additions & 0 deletions libs/Universal-PicGo-Store/src/lib/JSONStore.ts
@@ -0,0 +1,40 @@
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/

import { IJSON } from "../types"

class JSONStore {
constructor(dbPath: string) {
if (!dbPath) {
throw Error("Please provide valid dbPath")
}
}

read(flush = false): IJSON {
throw Error("Not Implemented")
}

get(key = ""): any {
throw Error("get Not Implemented for json store")
}

set(key: string, value: any): void {
throw Error("Not Implemented")
}

has(key: string): boolean {
throw Error("Not Implemented")
}

unset(key: string, value: any): boolean {
throw Error("Not Implemented")
}
}

export { JSONStore }
13 changes: 13 additions & 0 deletions libs/Universal-PicGo-Store/src/lib/utils.ts
@@ -0,0 +1,13 @@
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/

const currentWin = (window || globalThis || undefined) as any
const parentWin = (window?.parent || window?.top || window?.self || undefined) as any
export const win = currentWin?.fs ? currentWin : parentWin?.fs ? parentWin : currentWin
export const hasNodeEnv = typeof win?.fs !== "undefined"
12 changes: 12 additions & 0 deletions libs/Universal-PicGo-Store/src/types/index.d.ts
@@ -0,0 +1,12 @@
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/

export interface IJSON {
[propsName: string]: string | number | IJSON
}
6 changes: 4 additions & 2 deletions libs/Universal-PicGo-Store/tsconfig.json
Expand Up @@ -9,6 +9,7 @@
"DOM.Iterable"
],
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "Node",
// "allowImportingTsExtensions": true,
Expand All @@ -17,10 +18,11 @@
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"types": [
"node",
Expand Down
8 changes: 7 additions & 1 deletion libs/Universal-PicGo-Store/vite.config.ts
Expand Up @@ -6,6 +6,7 @@ import { viteStaticCopy } from "vite-plugin-static-copy"
import dts from "vite-plugin-dts"
import minimist from "minimist"
import livereload from "rollup-plugin-livereload"
import { nodePolyfills } from "vite-plugin-node-polyfills"

const args = minimist(process.argv.slice(2))
const isWatch = args.watch || args.w || false
Expand All @@ -20,6 +21,11 @@ export default defineConfig({
plugins: [
dts(),

nodePolyfills({
// Whether to polyfill `node:` protocol imports.
protocolImports: true,
}) as any,

viteStaticCopy({
targets: [
{
Expand Down Expand Up @@ -50,7 +56,7 @@ export default defineConfig({
formats: ["es"],
},
rollupOptions: {
plugins: [...(isWatch ? [livereload(devDistDir)] : [])],
plugins: [...(isWatch ? [livereload(devDistDir)] : [])] as any,
// make sure to externalize deps that shouldn't be bundled
// into your library
external: [],
Expand Down
3 changes: 0 additions & 3 deletions packages/picgo-plugin-app/scripts/dev.py
Expand Up @@ -6,8 +6,5 @@
# Windows 必须添加此设置
sys.stdout.reconfigure(encoding="utf-8")

# siyuan-plugin-bootstrap
# os.system("")

# picgo-app
os.system("vue-tsc && vite build --watch")
12 changes: 9 additions & 3 deletions packages/picgo-plugin-app/src/pages/PicGoIndex.vue
Expand Up @@ -10,14 +10,20 @@
<script setup lang="ts">
import { UniversalPicGo } from "universal-picgo"
import { createAppLogger } from "@/utils/appLogger.ts"
import { ElMessage } from "element-plus"
const logger = createAppLogger("picgo-index")
const handleTest = () => {
const picgo = new UniversalPicGo()
logger.debug("picgo =>", picgo)
try {
const picgo = new UniversalPicGo()
logger.debug("picgo =>", picgo)
picgo.upload()
picgo.upload()
ElMessage.success("success")
} catch (e: any) {
ElMessage.error(e.toString())
}
}
</script>

Expand Down

0 comments on commit 07cc413

Please sign in to comment.