Skip to content

Commit

Permalink
chore: 使用软链接构建项目,提升效率
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Nov 7, 2023
1 parent 2b144ef commit c51abe8
Show file tree
Hide file tree
Showing 4 changed files with 193 additions and 37 deletions.
23 changes: 1 addition & 22 deletions esbuild.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,13 @@
*/

const path = require("path")
const os = require("os")
const minimist = require("minimist")
const stylePlugin = require("esbuild-style-plugin")
const { copy } = require("esbuild-plugin-copy")

const args = minimist(process.argv.slice(2))
const isWatch = args.watch || args.w || false
const isServe = args.serve || args.s || false
const isWindows = os.platform() === "win32"

let baseDir
if (isWatch || isServe) {
// Mac public
// baseDir = "/Users/terwer/Documents/mydocs/SiYuanWorkspace/public/data/plugins/siyuan-plugin-publisher"
// Mac
baseDir = "/Users/terwer/Documents/mydocs/SiYuanWorkspace/test/data/plugins/siyuan-plugin-publisher"
// Zhangyue
// baseDir = "/Users/zhangyue/Documents/terwer/SiyuanWorkspace/test/data/plugins/siyuan-plugin-publisher"
if (isWindows) {
// Home
// baseDir = "C:\\Users\\terwer\\Documents\\mydocs\\SiyuanWorkspace\\test\\data\\plugins\\siyuan-plugin-publisher"
// Bootcamp
baseDir = "C:\\Users\\Terwer\\Documents\\mydocs\\SiyuanWorkspace\\test\\data\\plugins\\siyuan-plugin-publisher"
}
} else {
baseDir = "./"
}
const distDir = isWatch || isServe ? baseDir : path.join(baseDir, "dist")
const distDir = "./dist"

module.exports = {
esbuildConfig: {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"author": "terwer",
"license": "MIT",
"scripts": {
"makeLink": "python scripts/make_dev_link.py",
"serve": "python scripts/serve.py",
"dev": "python scripts/dev.py",
"test": "vitest",
Expand Down
188 changes: 188 additions & 0 deletions scripts/make_dev_link.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
# Copyright (c) 2022-2023, terwer . All rights reserved.
# @author terwer on 2023/11/6

import json
import os
import sys
import urllib.parse
import urllib.request

import scriptutils

# ************************************ 在这里填写你的配置 ************************************
# 请在这里写下你的 "workspace/data/plugins" 目录
# 比如这样 targetDir = 'H:\\SiYuanDevSpace\\data\\plugins'
targetDir = ''
# dev 构建输出目录,相对于项目根路径
devOutDir = 'dist'
# ******************************************************************************************

POST_HEADER = {
"Authorization": f"Token ",
"Content-Type": "application/json",
}


def get_siyuan_dir():
url = 'http://127.0.0.1:6806/api/system/getWorkspaces'
try:
response = _myfetch(url, {
'method': 'POST',
'headers': POST_HEADER
})
if response['ok'] and 200 <= response['status'] < 300:
data = response['data']
conf = json.loads(data)
else:
_error(f'\tget_siyuan_dir HTTP-Error: {response["status"]}')
return None
except Exception as e:
_error(f'\tError: {e}')
_error('\tPlease make sure SiYuan is running!!!')
return None
return conf['data']


def choose_target(workspaces):
count = len(workspaces)
_log(f'>>> Got {count} SiYuan {"workspaces" if count > 1 else "workspace"}')
for i, workspace in enumerate(workspaces):
_log(f'\t[{i}] {workspace["path"]}')

if count == 1:
return f'{workspaces[0]["path"]}/data/plugins'
else:
index = input(f'\tPlease select a workspace[0-{count - 1}]: ')
return f'{workspaces[int(index)]["path"]}/data/plugins'


def get_plugin_name():
# 检查 plugin.json 是否存在
if not os.path.exists('./plugin.json'):
_error('失败!找不到 plugin.json')
sys.exit(1)
# 获取插件名称
# 加载 plugin.json
with open('./plugin.json', 'r') as file:
plugin = json.load(file)
plugin_name = plugin.get('name')
if not plugin_name or plugin_name == '':
_error('失败!请在 plugin.json 中设置插件名称')
sys.exit(1)
return plugin_name


def make_link(target_dir, plugin_name):
# dev 目录
dev_dir = f'{os.getcwd()}/{devOutDir}'
# 如果不存在则创建
if not os.path.exists(dev_dir):
os.makedirs(dev_dir)

target_path = f'{target_dir}/{plugin_name}'
# 如果已存在,则退出
if os.path.exists(target_path):
is_symbol = os.path.islink(target_path)

if is_symbol:
src_path = os.readlink(target_path)

if _cmp_path(src_path, dev_dir):
_log(f'Good! {target_path} 已经链接到 {dev_dir}')
else:
_error(f'Error! 符号链接 {target_path} 已存在\n但它链接到了 {src_path}')
else:
_error(f'失败!{target_path} 已经存在并且不是符号链接')

else:
# 创建符号链接
os.symlink(dev_dir, target_path, target_is_directory=True)
_log(f'Done! 创建符号链接 {target_path}')


# =====================
# private methods
# =====================
def _log(info):
print(f'\033[36m{info}\033[0m')


def _error(info):
print(f'\033[31m{info}\033[0m')


def _myfetch(url, options):
method = options['method'].upper()
headers = options['headers']

if method == 'GET':
query_params = options.get('params', {})
query_string = urllib.parse.urlencode(query_params)
full_url = f"{url}?{query_string}"
req = urllib.request.Request(full_url, headers=headers)
elif method == 'POST':
data = options.get('data', {})
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data=encoded_data, headers=headers)
else:
raise ValueError(f"Unsupported method: {method}")

with urllib.request.urlopen(req) as response:
data = response.read().decode('utf-8')
status = response.status

return {
'ok': True,
'status': status,
'data': data
}


def _cmp_path(path1, path2):
path1 = path1.replace('\\', '/')
path2 = path2.replace('\\', '/')
# 尾部添加分隔符
if path1[-1] != '/':
path1 += '/'
if path2[-1] != '/':
path2 += '/'
return path1 == path2


if __name__ == "__main__":
# 切换工作空间
scriptutils.switch_workdir()

# 获取当前路径
cwd = scriptutils.get_workdir()

# 获取插件目录
_log('>>> 尝试访问 make_dev_link.js 中的常量 "targetDir"...')
if targetDir == '':
_log('>>> 常量 "targetDir" 为空,尝试自动获取 SiYuan 目录...')
res = get_siyuan_dir()
if res is None or len(res) == 0:
_log('>>> 无法自动获取 SiYuan 目录,尝试访问环境变量 "SIYUAN_PLUGIN_DIR"...')

env = os.getenv('SIYUAN_PLUGIN_DIR')
if env is not None and env != '':
targetDir = env
_log(f'\t从环境变量 "SIYUAN_PLUGIN_DIR" 获取到目标目录: {targetDir}')
else:
_error('\t无法从环境变量 "SIYUAN_PLUGIN_DIR" 获取 SiYuan 目录,失败!')
sys.exit(1)
else:
targetDir = choose_target(res)
_log(f'>>> 成功获取到目标目录: {targetDir}')
# 检查目录是否存在
if not os.path.exists(targetDir):
_error(f'失败!插件目录不存在: "{targetDir}"')
_error('请在 scripts/make_dev_link.py 中设置插件目录')
sys.exit(1)

# 获取插件名称
name = get_plugin_name()
_log(f'>>> 成功获取到插件名称: {name}')

# 生成软连接
make_link(targetDir, name)
18 changes: 3 additions & 15 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,24 +61,12 @@ const debugMode = process.env.DEBUG_MODE === "true"
const isServe = process.env.IS_SERVE
const isWatch = args.watch || args.w || false
const isDev = isServe || isWatch || debugMode
const isWindows = process.platform === "win32"
// Mac public
// let devDistDir = "/Users/terwer/Documents/mydocs/SiYuanWorkspace/public/data/plugins/siyuan-plugin-publisher"
// Mac
let devDistDir = "/Users/terwer/Documents/mydocs/SiYuanWorkspace/test/data/plugins/siyuan-plugin-publisher"
// Zhangyue
// let devDistDir = "/Users/zhangyue/Documents/terwer/SiyuanWorkspace/test/data/plugins/siyuan-plugin-publisher"
if (isWindows) {
// Home
// devDistDir = "C:\\Users\\terwer\\Documents\\mydocs\\SiyuanWorkspace\\test\\data\\plugins\\siyuan-plugin-publisher"
// Bootcamp
devDistDir = "C:\\Users\\Terwer\\Documents\\mydocs\\SiyuanWorkspace\\test\\data\\plugins\\\\siyuan-plugin-publisher"
}

const isSiyuanBuild = process.env.BUILD_TYPE === "siyuan"
const isWidgetBuild = process.env.BUILD_TYPE === "widget"
const isStaticBuild = process.env.BUILD_TYPE === "static"
// const isChromeBuild = process.env.BUILD_TYPE === "chrome"
const distDir = isWatch ? devDistDir : isWidgetBuild ? "widget" : "./dist"
const distDir = isWidgetBuild ? "widget" : "./dist"
const appBase = getAppBase(isSiyuanBuild, isWidgetBuild, isStaticBuild)

console.log("isWatch=>", isWatch)
Expand Down Expand Up @@ -219,7 +207,7 @@ export default defineConfig({
plugins: [
...(isWatch
? [
livereload(devDistDir),
livereload(distDir),
{
//监听静态资源文件
name: "watch-external",
Expand Down

0 comments on commit c51abe8

Please sign in to comment.