🔨 refactor: 创建 dir 符号链接;并编写 ps 脚本用于获取 windows 管理员权限

https://github.com/siyuan-note/siyuan/issues/12399
This commit is contained in:
frostime 2024-09-06 19:50:50 +08:00
parent da4c4ced8f
commit e345e18613
7 changed files with 327 additions and 355 deletions

24
scripts/elevate.ps1 Normal file
View file

@ -0,0 +1,24 @@
# Copyright (c) 2024 by frostime. All Rights Reserved.
# @Author : frostime
# @Date : 2024-09-06 19:15:53
# @FilePath : /scripts/elevate.ps1
# @LastEditTime : 2024-09-06 19:39:13
# @Description : Force to elevate the script to admin privilege.
param (
[string]$scriptPath
)
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$projectDir = Split-Path -Parent $scriptDir
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$args = "-NoProfile -ExecutionPolicy Bypass -File `"" + $MyInvocation.MyCommand.Path + "`" -scriptPath `"" + $scriptPath + "`""
Start-Process powershell.exe -Verb RunAs -ArgumentList $args -WorkingDirectory $projectDir
exit
}
Set-Location -Path $projectDir
& node $scriptPath
pause

View file

@ -1,106 +1,29 @@
/*
* Copyright (c) 2024 by frostime. All Rights Reserved.
* @Author : frostime
* @Date : 2023-07-15 15:31:31
* @FilePath : /scripts/make_dev_link.js
* @LastEditTime : 2024-09-06 18:13:53
* @Description :
*/
// make_dev_link.js
import fs from 'fs';
import http from 'node:http';
import readline from 'node:readline';
import { log, error, getSiYuanDir, chooseTarget, getThisPluginName, makeSymbolicLink } from './utils.js';
//************************************ Write you dir here ************************************
//Please write the "workspace/data/plugins" directory here
//请在这里填写你的 "workspace/data/plugins" 目录
let targetDir = '';
//Like this
// let targetDir = `H:\\SiYuanDevSpace\\data\\plugins`;
//********************************************************************************************
const log = (info) => console.log(`\x1B[36m%s\x1B[0m`, info);
const error = (info) => console.log(`\x1B[31m%s\x1B[0m`, info);
let POST_HEADER = {
// "Authorization": `Token ${token}`,
"Content-Type": "application/json",
}
async function myfetch(url, options) {
//使用 http 模块,从而兼容那些不支持 fetch 的 nodejs 版本
return new Promise((resolve, reject) => {
let req = http.request(url, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve({
ok: true,
status: res.statusCode,
json: () => JSON.parse(data)
});
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
async function getSiYuanDir() {
let url = 'http://127.0.0.1:6806/api/system/getWorkspaces';
let conf = {};
try {
let response = await myfetch(url, {
method: 'POST',
headers: POST_HEADER
});
if (response.ok) {
conf = await response.json();
} else {
error(`\tHTTP-Error: ${response.status}`);
return null;
}
} catch (e) {
error(`\tError: ${e}`);
error("\tPlease make sure SiYuan is running!!!");
return null;
}
return conf.data;
}
async function chooseTarget(workspaces) {
let count = workspaces.length;
log(`>>> Got ${count} SiYuan ${count > 1 ? 'workspaces' : 'workspace'}`)
for (let i = 0; i < workspaces.length; i++) {
log(`\t[${i}] ${workspaces[i].path}`);
}
if (count == 1) {
return `${workspaces[0].path}/data/plugins`;
} else {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let index = await new Promise((resolve, reject) => {
rl.question(`\tPlease select a workspace[0-${count-1}]: `, (answer) => {
resolve(answer);
});
});
rl.close();
return `${workspaces[index].path}/data/plugins`;
}
}
log('>>> Try to visit constant "targetDir" in make_dev_link.js...')
/**
* 1. Get the parent directory to install the plugin
*/
log('>>> Try to visit constant "targetDir" in make_dev_link.js...');
if (targetDir === '') {
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....')
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....');
let res = await getSiYuanDir();
if (res === null || res === undefined || res.length === 0) {
log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....');
// console.log(process.env)
if (!res || res.length === 0) {
log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....');
let env = process.env?.SIYUAN_PLUGIN_DIR;
if (env !== undefined && env !== null && env !== '') {
if (env) {
targetDir = env;
log(`\tGot target directory from environment variable "SIYUAN_PLUGIN_DIR": ${targetDir}`);
} else {
@ -111,76 +34,33 @@ if (targetDir === '') {
targetDir = await chooseTarget(res);
}
log(`>>> Successfully got target directory: ${targetDir}`);
}
//Check
if (!fs.existsSync(targetDir)) {
error(`Failed! plugin directory not exists: "${targetDir}"`);
error(`Please set the plugin directory in scripts/make_dev_link.js`);
error(`Failed! Plugin directory not exists: "${targetDir}"`);
error('Please set the plugin directory in scripts/make_dev_link.js');
process.exit(1);
}
//check if plugin.json exists
if (!fs.existsSync('./plugin.json')) {
//change dir to parent
process.chdir('../');
if (!fs.existsSync('./plugin.json')) {
error('Failed! plugin.json not found');
process.exit(1);
}
}
//load plugin.json
const plugin = JSON.parse(fs.readFileSync('./plugin.json', 'utf8'));
const name = plugin?.name;
if (!name || name === '') {
error('Failed! Please set plugin name in plugin.json');
process.exit(1);
}
//dev directory
/**
* 2. The dev directory, which contains the compiled plugin code
*/
const devDir = `${process.cwd()}/dev`;
//mkdir if not exists
if (!fs.existsSync(devDir)) {
fs.mkdirSync(devDir);
}
function cmpPath(path1, path2) {
path1 = path1.replace(/\\/g, '/');
path2 = path2.replace(/\\/g, '/');
// sepertor at tail
if (path1[path1.length - 1] !== '/') {
path1 += '/';
}
if (path2[path2.length - 1] !== '/') {
path2 += '/';
}
return path1 === path2;
}
/**
* 3. The target directory to make symbolic link to dev directory
*/
const name = getThisPluginName();
if (name === null) {
process.exit(1);
}
const targetPath = `${targetDir}/${name}`;
//如果已经存在,就退出
if (fs.existsSync(targetPath)) {
let isSymbol = fs.lstatSync(targetPath).isSymbolicLink();
if (isSymbol) {
let srcPath = fs.readlinkSync(targetPath);
if (cmpPath(srcPath, devDir)) {
log(`Good! ${targetPath} is already linked to ${devDir}`);
} else {
error(`Error! Already exists symbolic link ${targetPath}\nBut it links to ${srcPath}`);
}
} else {
error(`Failed! ${targetPath} already exists and is not a symbolic link`);
}
} else {
//创建软链接
fs.symlinkSync(devDir, targetPath, 'junction');
log(`Done! Created symlink ${targetPath}`);
}
/**
* 4. Make symbolic link
*/
makeSymbolicLink(devDir, targetPath);

View file

@ -1,191 +1,57 @@
/*
* Copyright (c) 2024 by frostime. All Rights Reserved.
* @Author : frostime
* @Date : 2024-03-28 20:03:59
* @FilePath : /scripts/make_install.js
* @LastEditTime : 2024-09-06 18:08:19
* @Description :
*/
// make_install.js
import fs from 'fs';
import path from 'path';
import http from 'node:http';
import readline from 'node:readline';
import { log, error, getSiYuanDir, chooseTarget, copyDirectory, getThisPluginName } from './utils.js';
let targetDir = '';
//************************************ Write you dir here ************************************
let targetDir = ''; // the target directory of the plugin, '*/data/plugin'
//********************************************************************************************
const log = (info) => console.log(`\x1B[36m%s\x1B[0m`, info);
const error = (info) => console.log(`\x1B[31m%s\x1B[0m`, info);
let POST_HEADER = {
// "Authorization": `Token ${token}`,
"Content-Type": "application/json",
}
async function myfetch(url, options) {
//使用 http 模块,从而兼容那些不支持 fetch 的 nodejs 版本
return new Promise((resolve, reject) => {
let req = http.request(url, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve({
ok: true,
status: res.statusCode,
json: () => JSON.parse(data)
});
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
async function getSiYuanDir() {
let url = 'http://127.0.0.1:6806/api/system/getWorkspaces';
let conf = {};
try {
let response = await myfetch(url, {
method: 'POST',
headers: POST_HEADER
});
if (response.ok) {
conf = await response.json();
} else {
error(`\tHTTP-Error: ${response.status}`);
return null;
}
} catch (e) {
error(`\tError: ${e}`);
error("\tPlease make sure SiYuan is running!!!");
return null;
}
return conf.data;
}
async function chooseTarget(workspaces) {
let count = workspaces.length;
log(`>>> Got ${count} SiYuan ${count > 1 ? 'workspaces' : 'workspace'}`)
for (let i = 0; i < workspaces.length; i++) {
log(`\t[${i}] ${workspaces[i].path}`);
}
if (count == 1) {
return `${workspaces[0].path}/data/plugins`;
} else {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let index = await new Promise((resolve, reject) => {
rl.question(`\tPlease select a workspace[0-${count-1}]: `, (answer) => {
resolve(answer);
});
});
rl.close();
return `${workspaces[index].path}/data/plugins`;
}
}
log('>>> Try to visit constant "targetDir" in make_install.js...')
/**
* 1. Get the parent directory to install the plugin
*/
log('>>> Try to visit constant "targetDir" in make_install.js...');
if (targetDir === '') {
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....')
log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....');
let res = await getSiYuanDir();
if (res === null || res === undefined || res.length === 0) {
error('>>> Can not get SiYuan directory automatically');
process.exit(1);
} else {
targetDir = await chooseTarget(res);
}
log(`>>> Successfully got target directory: ${targetDir}`);
}
//Check
if (!fs.existsSync(targetDir)) {
error(`Failed! plugin directory not exists: "${targetDir}"`);
error(`Please set the plugin directory in scripts/make_install.js`);
process.exit(1);
}
//check if plugin.json exists
if (!fs.existsSync('./plugin.json')) {
//change dir to parent
process.chdir('../');
if (!fs.existsSync('./plugin.json')) {
error('Failed! plugin.json not found');
process.exit(1);
}
}
//load plugin.json
const plugin = JSON.parse(fs.readFileSync('./plugin.json', 'utf8'));
const name = plugin?.name;
if (!name || name === '') {
error('Failed! Please set plugin name in plugin.json');
error(`Failed! Plugin directory not exists: "${targetDir}"`);
error('Please set the plugin directory in scripts/make_install.js');
process.exit(1);
}
/**
* 2. The dist directory, which contains the compiled plugin code
*/
const distDir = `${process.cwd()}/dist`;
//mkdir if not exists
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir);
}
function cmpPath(path1, path2) {
path1 = path1.replace(/\\/g, '/');
path2 = path2.replace(/\\/g, '/');
// sepertor at tail
if (path1[path1.length - 1] !== '/') {
path1 += '/';
}
if (path2[path2.length - 1] !== '/') {
path2 += '/';
}
return path1 === path2;
/**
* 3. The target directory to install the plugin
*/
const name = getThisPluginName();
if (name === null) {
process.exit(1);
}
const targetPath = `${targetDir}/${name}`;
function copyDirectory(srcDir, dstDir) {
if (!fs.existsSync(dstDir)) {
fs.mkdirSync(dstDir);
log(`Created directory ${dstDir}`);
}
//将 distDir 下的所有文件复制到 targetPath
fs.readdir(srcDir, { withFileTypes: true }, (err, files) => {
if (err) {
error('Error reading source directory:', err);
return;
}
// 遍历源目录中的所有文件和子目录
files.forEach((file) => {
const src = path.join(srcDir, file.name);
const dst = path.join(dstDir, file.name);
// 判断当前项是文件还是目录
if (file.isDirectory()) {
// 如果是目录,则递归调用复制函数复制子目录
copyDirectory(src, dst);
} else {
// 如果是文件,则复制文件到目标目录
fs.copyFile(src, dst, (err) => {
if (err) {
error('Error copying file:' + err);
} else {
log(`Copied file: ${src} --> ${dst}`);
}
});
}
});
log(`Copied ${distDir} to ${targetPath}`);
});
}
/**
* 4. Copy the compiled plugin code to the target directory
*/
copyDirectory(distDir, targetPath);

182
scripts/utils.js Normal file
View file

@ -0,0 +1,182 @@
/*
* Copyright (c) 2024 by frostime. All Rights Reserved.
* @Author : frostime
* @Date : 2024-09-06 17:42:57
* @FilePath : /scripts/utils.js
* @LastEditTime : 2024-09-06 19:23:12
* @Description :
*/
// common.js
import fs from 'fs';
import path from 'node:path';
import http from 'node:http';
import readline from 'node:readline';
// Logging functions
export const log = (info) => console.log(`\x1B[36m%s\x1B[0m`, info);
export const error = (info) => console.log(`\x1B[31m%s\x1B[0m`, info);
// HTTP POST headers
export const POST_HEADER = {
"Content-Type": "application/json",
};
// Fetch function compatible with older Node.js versions
export async function myfetch(url, options) {
return new Promise((resolve, reject) => {
let req = http.request(url, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve({
ok: true,
status: res.statusCode,
json: () => JSON.parse(data)
});
});
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
/**
* Fetch SiYuan workspaces from port 6806
* @returns {Promise<Object | null>}
*/
export async function getSiYuanDir() {
let url = 'http://127.0.0.1:6806/api/system/getWorkspaces';
let conf = {};
try {
let response = await myfetch(url, {
method: 'POST',
headers: POST_HEADER
});
if (response.ok) {
conf = await response.json();
} else {
error(`\tHTTP-Error: ${response.status}`);
return null;
}
} catch (e) {
error(`\tError: ${e}`);
error("\tPlease make sure SiYuan is running!!!");
return null;
}
return conf?.data; // 保持原始返回值
}
/**
* Choose target workspace
* @param {{path: string}[]} workspaces
* @returns {string} The path of the selected workspace
*/
export async function chooseTarget(workspaces) {
let count = workspaces.length;
log(`>>> Got ${count} SiYuan ${count > 1 ? 'workspaces' : 'workspace'}`);
workspaces.forEach((workspace, i) => {
log(`\t[${i}] ${workspace.path}`);
});
if (count === 1) {
return `${workspaces[0].path}/data/plugins`;
} else {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let index = await new Promise((resolve) => {
rl.question(`\tPlease select a workspace[0-${count - 1}]: `, (answer) => {
resolve(answer);
});
});
rl.close();
return `${workspaces[index].path}/data/plugins`;
}
}
/**
* Check if two paths are the same
* @param {string} path1
* @param {string} path2
* @returns {boolean}
*/
export function cmpPath(path1, path2) {
path1 = path1.replace(/\\/g, '/');
path2 = path2.replace(/\\/g, '/');
if (path1[path1.length - 1] !== '/') {
path1 += '/';
}
if (path2[path2.length - 1] !== '/') {
path2 += '/';
}
return path1 === path2;
}
export function getThisPluginName() {
if (!fs.existsSync('./plugin.json')) {
process.chdir('../');
if (!fs.existsSync('./plugin.json')) {
error('Failed! plugin.json not found');
return null;
}
}
const plugin = JSON.parse(fs.readFileSync('./plugin.json', 'utf8'));
const name = plugin?.name;
if (!name) {
error('Failed! Please set plugin name in plugin.json');
return null;
}
return name;
}
export function copyDirectory(srcDir, dstDir) {
if (!fs.existsSync(dstDir)) {
fs.mkdirSync(dstDir);
log(`Created directory ${dstDir}`);
}
fs.readdirSync(srcDir, { withFileTypes: true }).forEach((file) => {
const src = path.join(srcDir, file.name);
const dst = path.join(dstDir, file.name);
if (file.isDirectory()) {
copyDirectory(src, dst);
} else {
fs.copyFileSync(src, dst);
log(`Copied file: ${src} --> ${dst}`);
}
});
log(`All files copied!`);
}
export function makeSymbolicLink(srcPath, targetPath) {
if (!fs.existsSync(targetPath)) {
// fs.symlinkSync(srcPath, targetPath, 'junction');
//Go 1.23 no longer supports junctions as symlinks
//Please refer to https://github.com/siyuan-note/siyuan/issues/12399
fs.symlinkSync(srcPath, targetPath, 'dir');
log(`Done! Created symlink ${targetPath}`);
return;
}
//Check the existed target path
let isSymbol = fs.lstatSync(targetPath).isSymbolicLink();
if (!isSymbol) {
error(`Failed! ${targetPath} already exists and is not a symbolic link`);
return;
}
let existedPath = fs.readlinkSync(targetPath);
if (cmpPath(existedPath, srcPath)) {
log(`Good! ${targetPath} is already linked to ${srcPath}`);
} else {
error(`Error! Already exists symbolic link ${targetPath}\nBut it links to ${existedPath}`);
}
}