Skip to content

Commit e345e18

Browse files
committed
🔨 refactor: 创建 dir 符号链接;并编写 ps 脚本用于获取 windows 管理员权限
siyuan-note/siyuan#12399
1 parent da4c4ce commit e345e18

File tree

7 files changed

+329
-357
lines changed

7 files changed

+329
-357
lines changed

README.md

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,21 @@
2020

2121
## Get started
2222

23-
1. Make a copy of this repo as a template with the `Use this template` button, please note that the repo name must be the same as the plugin name, the default branch must be `main`
23+
1. Use the <kbd>Use this template</kbd> button to make a copy of this repo as a template. Note that the repository name should match the plugin name, and the default branch must be `main`.
24+
2. Clone your repository to the local development folder.
25+
* Note: Unlike `plugin-sample`, this example does not recommend directly downloading the code to `{workspace}/data/plugins/`.
26+
3. Install [NodeJS](https://nodejs.org/en/download) and [pnpm](https://pnpm.io/installation), then run `pnpm i` in the development folder to install the required dependencies.
27+
4. Run the `pnpm run make-link` command to create a symbolic link (Windows developers, please refer to the "make-link on Windows" section below).
28+
5. Execute `pnpm run dev` for real-time compilation.
29+
6. Open the marketplace in SiYuan and enable the plugin in the download tab.
2430

25-
2. Clone your repo to a local development folder at any place
26-
- Notice: we **don't recommand** you to place the folder under your `{workspace}/data/plugins/` folder.
31+
### Setting the Target Directory for the make-link Command
2732

28-
3. Install NodeJS and pnpm, then run pnpm i in the command line under your repo folder
29-
4. **Auto create development symbolic links**
30-
- Make sure that SiYuan is running
31-
- Run `pnpm run make-link`, the script will detect all the siyuan workspace, please select the targe workspace and the script will automatically create the symbolic link under the `{workspace}/data/plugins/` folder
33+
The `make-link` command creates a symbolic link that binds your `dev` directory to the SiYuan plugin directory. You can configure the target SiYuan workspace and create the symbolic link in three ways:
34+
35+
1. **Select Workspace**
36+
- Open SiYuan, ensure the SiYuan kernel is running.
37+
- Run `pnpm run make-link`, the script will automatically detect all SiYuan workspaces, please manually enter the number to select the workspace.
3238
```bash
3339
>>> pnpm run make-link
3440
> [email protected] make-link H:\SrcCode\开源项目\plugin-sample-vite-svelte
@@ -42,22 +48,24 @@
4248
Got target directory: H:\Media\SiYuan/data/plugins
4349
Done! Created symlink H:\Media\SiYuan/data/plugins/plugin-sample-vite-svelte
4450
```
45-
4. **Manually create development symbolic links**
46-
- Open `./scripts/make_dev_link.js` file, set `targetDir` to your SiYuan plugin directory `<siyuan workspace>/data/plugins`
47-
- Run `pnpm run make-link`, succeed if following message is shown:
48-
```bash
49-
>>> pnpm run make-link
50-
> [email protected] make-link H:\SrcCode\plugin-sample-vite-svelte
51-
> node ./scripts/make_dev_link.js
52-
53-
Done! Created symlink H:/SiYuanDevSpace/data/plugins/plugin-sample-vite-svelte
54-
```
55-
5. **Create development symbolic links by using environment variable**
56-
- You can set environment variable `SIYUAN_PLUGIN_DIR` as `/data/plugins`
57-
6. Execute pnpm run dev for real-time compilation
58-
7. Open SiYuan marketplace and enable plugin in downloaded tab
59-
60-
> Notice: as the `make-link` script rely on the `fetch` function, please **ensure that at least version v18 of nodejs is installed** if you want to use make-link script.
51+
2. **Manually Configure Target Directory**
52+
- Open the `./scripts/make_dev_link.js` file, change `targetDir` to the SiYuan plugin directory `<siyuan workspace>/data/plugins`.
53+
- Run the `pnpm run make-link` command. If you see a message similar to the one below, it indicates successful creation:
54+
55+
3. **Set Environment Variable to Create Symbolic Link**
56+
- Set the system environment variable `SIYUAN_PLUGIN_DIR` to the path `workspace/data/plugins`.
57+
58+
### make-link on Windows
59+
60+
Due to SiYuan upgrading to Go 1.23, the old version of junction links cannot be recognized normally on Windows, so it has been changed to create `dir` symbolic links.
61+
62+
> https://github.com/siyuan-note/siyuan/issues/12399
63+
64+
However, creating directory symbolic links on Windows using NodeJs may require administrator privileges. You have the following options:
65+
66+
1. Run `pnpm run make-link` in a command line with administrator privileges.
67+
2. Configure Windows settings, enable developer mode in [System Settings - Update & Security - Developer Mode] then run `pnpm run make-link`.
68+
3. Run `pnpm run make-link-win`, this command will use a PowerShell script to request administrator privileges, requiring the system to enable PowerShell script execution permissions.
6169
6270
## I18n
6371

README_zh_CN.md

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,19 @@
1818

1919
## 开始
2020

21-
1. 通过 <kbd>Use this template</kbd> 按钮将该库文件复制到你自己的库中,请注意库名必须和插件名称一致,默认分支必须为 `main`
21+
1. 通过 <kbd>Use this template</kbd> 按钮将该库文件复制到你自己的库中,请注意库名和插件名称一致,默认分支必须为 `main`
2222
2. 将你的库克隆到本地开发文件夹中
2323
* 注意: 同 `plugin-sample` 不同, 本样例并不推荐直接把代码下载到 `{workspace}/data/plugins/`
2424
3. 安装 [NodeJS](https://nodejs.org/en/download)[pnpm](https://pnpm.io/installation),然后在开发文件夹下执行 `pnpm i` 安装所需要的依赖
25-
3. **自动创建符号链接**
25+
4. 运行 `pnpm run make-link` 命令创建符号链接 (Windows 下的开发者请参阅下方「Windows 下的 make-link」小节)
26+
5. 执行 `pnpm run dev` 进行实时编译
27+
6. 在思源中打开集市并在下载选项卡中启用插件
28+
29+
### 设置 make-link 命令的目标目录
30+
31+
make-link 命令会创建符号链接将你的 `dev` 目录绑定到思源的插件目录下。你可以有三种方式来配置目标的思源工作空间并创建符号链接:
32+
33+
1. **选择工作空间**
2634
- 打开思源笔记, 确保思源内核正在运行
2735
- 运行 `pnpm run make-link`, 脚本会自动检测所有思源的工作空间, 请在命令行中手动输入序号以选择工作空间
2836
```bash
@@ -38,23 +46,26 @@
3846
Got target directory: H:\Media\SiYuan/data/plugins
3947
Done! Created symlink H:\Media\SiYuan/data/plugins/plugin-sample-vite-svelte
4048
```
41-
4. **手动创建符号链接**
49+
2. **手动配置目标目录**
4250
- 打开 `./scripts/make_dev_link.js` 文件,更改 `targetDir` 为思源的插件目录 `<siyuan workspace>/data/plugins`
4351
- 运行 `pnpm run make-link` 命令, 如果看到类似以下的消息,说明创建成功:
44-
```bash
45-
❯❯❯ pnpm run make-link
46-
> [email protected] make-link H:\SrcCode\plugin-sample-vite-svelte
47-
> node ./scripts/make_dev_link.js
4852
49-
Done! Created symlink H:/SiYuanDevSpace/data/plugins/plugin-sample-vite-svelte
50-
```
51-
5. **设置环境变量创建符号链接**
52-
- 你也可以设置系统的环境变量 `SIYUAN_PLUGIN_DIR``/data/plugins` 的路径
53-
6. 执行 `pnpm run dev` 进行实时编译
54-
7. 在思源中打开集市并在下载选项卡中启用插件
53+
3. **设置环境变量创建符号链接**
54+
- 设置系统的环境变量 `SIYUAN_PLUGIN_DIR``工作空间/data/plugins` 的路径
55+
56+
57+
### Windows 下的 make-link
58+
59+
由于思源升级了 Go 1.23,旧版创建的 junction link 在 windows 下无法被正常识别,故而改为创建 `dir` 符号链接。
60+
61+
> https://github.com/siyuan-note/siyuan/issues/12399
62+
5563
64+
不过 Windows 下使用 NodeJs 创建目录符号链接可能需要管理员权限,你可以有如下几种选择:
5665
57-
> 注意由于使用的 make-link 脚本依赖于 `fetch`,所以如果想要使用 make-link **请保证至少安装 v18 版本的 nodejs**
66+
1. 在具有管理员权限的命令行中运行 `pnpm run make-link`
67+
2. 配置 Windows 设置,在 [系统设置-更新与安全-开发者模式] 中启用开发者模式,然后再运行 `pnpm run make-link`
68+
3. 运行 `pnpm run make-link-win`,该命令会使用一个 powershell 脚本来寻求管理员权限,需要在系统中开启 PowerShell 脚本执行权限
5869
5970
6071
## 国际化

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"author": "frostime",
99
"license": "MIT",
1010
"scripts": {
11-
"make-link": "node --no-warnings ./scripts/make_dev_link.js",
11+
"make-link": "node --no-warnings ./scripts/make_dev_link.js",
12+
"make-link-win": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File ./scripts/elevate.ps1 -scriptPath ./scripts/make_dev_link.js",
1213
"dev": "vite build --watch",
1314
"build": "vite build",
1415
"make-install": "vite build && node --no-warnings ./scripts/make_install.js"

scripts/elevate.ps1

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright (c) 2024 by frostime. All Rights Reserved.
2+
# @Author : frostime
3+
# @Date : 2024-09-06 19:15:53
4+
# @FilePath : /scripts/elevate.ps1
5+
# @LastEditTime : 2024-09-06 19:39:13
6+
# @Description : Force to elevate the script to admin privilege.
7+
8+
param (
9+
[string]$scriptPath
10+
)
11+
12+
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
13+
$projectDir = Split-Path -Parent $scriptDir
14+
15+
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
16+
$args = "-NoProfile -ExecutionPolicy Bypass -File `"" + $MyInvocation.MyCommand.Path + "`" -scriptPath `"" + $scriptPath + "`""
17+
Start-Process powershell.exe -Verb RunAs -ArgumentList $args -WorkingDirectory $projectDir
18+
exit
19+
}
20+
21+
Set-Location -Path $projectDir
22+
& node $scriptPath
23+
24+
pause

scripts/make_dev_link.js

Lines changed: 34 additions & 154 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,29 @@
1+
/*
2+
* Copyright (c) 2024 by frostime. All Rights Reserved.
3+
* @Author : frostime
4+
* @Date : 2023-07-15 15:31:31
5+
* @FilePath : /scripts/make_dev_link.js
6+
* @LastEditTime : 2024-09-06 18:13:53
7+
* @Description :
8+
*/
9+
// make_dev_link.js
110
import fs from 'fs';
2-
import http from 'node:http';
3-
import readline from 'node:readline';
11+
import { log, error, getSiYuanDir, chooseTarget, getThisPluginName, makeSymbolicLink } from './utils.js';
412

5-
6-
//************************************ Write you dir here ************************************
7-
8-
//Please write the "workspace/data/plugins" directory here
9-
//请在这里填写你的 "workspace/data/plugins" 目录
1013
let targetDir = '';
11-
//Like this
12-
// let targetDir = `H:\\SiYuanDevSpace\\data\\plugins`;
13-
//********************************************************************************************
14-
15-
const log = (info) => console.log(`\x1B[36m%s\x1B[0m`, info);
16-
const error = (info) => console.log(`\x1B[31m%s\x1B[0m`, info);
17-
18-
let POST_HEADER = {
19-
// "Authorization": `Token ${token}`,
20-
"Content-Type": "application/json",
21-
}
22-
23-
async function myfetch(url, options) {
24-
//使用 http 模块,从而兼容那些不支持 fetch 的 nodejs 版本
25-
return new Promise((resolve, reject) => {
26-
let req = http.request(url, options, (res) => {
27-
let data = '';
28-
res.on('data', (chunk) => {
29-
data += chunk;
30-
});
31-
res.on('end', () => {
32-
resolve({
33-
ok: true,
34-
status: res.statusCode,
35-
json: () => JSON.parse(data)
36-
});
37-
});
38-
});
39-
req.on('error', (e) => {
40-
reject(e);
41-
});
42-
req.end();
43-
});
44-
}
45-
46-
async function getSiYuanDir() {
47-
let url = 'http://127.0.0.1:6806/api/system/getWorkspaces';
48-
let conf = {};
49-
try {
50-
let response = await myfetch(url, {
51-
method: 'POST',
52-
headers: POST_HEADER
53-
});
54-
if (response.ok) {
55-
conf = await response.json();
56-
} else {
57-
error(`\tHTTP-Error: ${response.status}`);
58-
return null;
59-
}
60-
} catch (e) {
61-
error(`\tError: ${e}`);
62-
error("\tPlease make sure SiYuan is running!!!");
63-
return null;
64-
}
65-
return conf.data;
66-
}
67-
68-
async function chooseTarget(workspaces) {
69-
let count = workspaces.length;
70-
log(`>>> Got ${count} SiYuan ${count > 1 ? 'workspaces' : 'workspace'}`)
71-
for (let i = 0; i < workspaces.length; i++) {
72-
log(`\t[${i}] ${workspaces[i].path}`);
73-
}
74-
75-
if (count == 1) {
76-
return `${workspaces[0].path}/data/plugins`;
77-
} else {
78-
const rl = readline.createInterface({
79-
input: process.stdin,
80-
output: process.stdout
81-
});
82-
let index = await new Promise((resolve, reject) => {
83-
rl.question(`\tPlease select a workspace[0-${count-1}]: `, (answer) => {
84-
resolve(answer);
85-
});
86-
});
87-
rl.close();
88-
return `${workspaces[index].path}/data/plugins`;
89-
}
90-
}
91-
92-
log('>>> Try to visit constant "targetDir" in make_dev_link.js...')
9314

15+
/**
16+
* 1. Get the parent directory to install the plugin
17+
*/
18+
log('>>> Try to visit constant "targetDir" in make_dev_link.js...');
9419
if (targetDir === '') {
95-
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....')
20+
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....');
9621
let res = await getSiYuanDir();
97-
98-
if (res === null || res === undefined || res.length === 0) {
99-
log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....');
10022

101-
// console.log(process.env)
23+
if (!res || res.length === 0) {
24+
log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....');
10225
let env = process.env?.SIYUAN_PLUGIN_DIR;
103-
if (env !== undefined && env !== null && env !== '') {
26+
if (env) {
10427
targetDir = env;
10528
log(`\tGot target directory from environment variable "SIYUAN_PLUGIN_DIR": ${targetDir}`);
10629
} else {
@@ -111,76 +34,33 @@ if (targetDir === '') {
11134
targetDir = await chooseTarget(res);
11235
}
11336

114-
11537
log(`>>> Successfully got target directory: ${targetDir}`);
11638
}
117-
118-
//Check
11939
if (!fs.existsSync(targetDir)) {
120-
error(`Failed! plugin directory not exists: "${targetDir}"`);
121-
error(`Please set the plugin directory in scripts/make_dev_link.js`);
40+
error(`Failed! Plugin directory not exists: "${targetDir}"`);
41+
error('Please set the plugin directory in scripts/make_dev_link.js');
12242
process.exit(1);
12343
}
12444

125-
126-
//check if plugin.json exists
127-
if (!fs.existsSync('./plugin.json')) {
128-
//change dir to parent
129-
process.chdir('../');
130-
if (!fs.existsSync('./plugin.json')) {
131-
error('Failed! plugin.json not found');
132-
process.exit(1);
133-
}
134-
}
135-
136-
//load plugin.json
137-
const plugin = JSON.parse(fs.readFileSync('./plugin.json', 'utf8'));
138-
const name = plugin?.name;
139-
if (!name || name === '') {
140-
error('Failed! Please set plugin name in plugin.json');
141-
process.exit(1);
142-
}
143-
144-
//dev directory
45+
/**
46+
* 2. The dev directory, which contains the compiled plugin code
47+
*/
14548
const devDir = `${process.cwd()}/dev`;
146-
//mkdir if not exists
14749
if (!fs.existsSync(devDir)) {
14850
fs.mkdirSync(devDir);
14951
}
15052

151-
function cmpPath(path1, path2) {
152-
path1 = path1.replace(/\\/g, '/');
153-
path2 = path2.replace(/\\/g, '/');
154-
// sepertor at tail
155-
if (path1[path1.length - 1] !== '/') {
156-
path1 += '/';
157-
}
158-
if (path2[path2.length - 1] !== '/') {
159-
path2 += '/';
160-
}
161-
return path1 === path2;
162-
}
163-
164-
const targetPath = `${targetDir}/${name}`;
165-
//如果已经存在,就退出
166-
if (fs.existsSync(targetPath)) {
167-
let isSymbol = fs.lstatSync(targetPath).isSymbolicLink();
168-
169-
if (isSymbol) {
170-
let srcPath = fs.readlinkSync(targetPath);
171-
172-
if (cmpPath(srcPath, devDir)) {
173-
log(`Good! ${targetPath} is already linked to ${devDir}`);
174-
} else {
175-
error(`Error! Already exists symbolic link ${targetPath}\nBut it links to ${srcPath}`);
176-
}
177-
} else {
178-
error(`Failed! ${targetPath} already exists and is not a symbolic link`);
179-
}
18053

181-
} else {
182-
//创建软链接
183-
fs.symlinkSync(devDir, targetPath, 'junction');
184-
log(`Done! Created symlink ${targetPath}`);
54+
/**
55+
* 3. The target directory to make symbolic link to dev directory
56+
*/
57+
const name = getThisPluginName();
58+
if (name === null) {
59+
process.exit(1);
18560
}
61+
const targetPath = `${targetDir}/${name}`;
18662

63+
/**
64+
* 4. Make symbolic link
65+
*/
66+
makeSymbolicLink(devDir, targetPath);

0 commit comments

Comments
 (0)