An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve built-in Pandoc storage and upgrade compatibility https://github.com/siyuan-note/siyuan/issues/18437
Daniel729879195021
diff --git a/app/package.json b/app/package.jsonindex 75618704d2..92d4ef6c38 100644--- a/app/package.json+++ b/app/package.json@@ -85,6 +85,7 @@"sharp": "^0.35.3","tsx": "^4.22.4","typescript": "^4.9.5",+ "unzipper": "0.12.5","webpack": "^5.104.1","webpack-bundle-analyzer": "^4.5.0","webpack-cli": "^4.10.0"diff --git a/app/pnpm-lock.yaml b/app/pnpm-lock.yamlindex 23cbb64feb..f49870f212 100644--- a/app/pnpm-lock.yaml+++ b/app/pnpm-lock.yaml@@ -114,6 +114,9 @@ importers:typescript:specifier: ^4.9.5version: 4.9.5+ unzipper:+ specifier: 0.12.5+ version: 0.12.5webpack:specifier: ^5.104.1version: 5.106.2([email protected])([email protected])diff --git a/app/scripts/afterPack.js b/app/scripts/afterPack.jsindex b6bd723f1b..3262d89c4b 100644--- a/app/scripts/afterPack.js+++ b/app/scripts/afterPack.js@@ -1,22 +1,59 @@-const fsPromises = require("fs").promises;+const fs = require("fs");+const fsPromises = fs.promises;const path = require("path");+const unzipper = require("unzipper");const { trimChangelogs } = require("./trimChangelogs");module.exports = async function afterPack(context) {const {appOutDir, electronPlatformName, packager} = context;+ await extractPackagedPandoc(appOutDir, packager, electronPlatformName);await removeLanguagePacks(appOutDir, packager, electronPlatformName);await trimPackagedChangelogs(appOutDir, packager, electronPlatformName);};-// 打包时裁剪 changelog,只保留当前版本 changelogs/v{version}/,详见 trimChangelogs.js。-async function trimPackagedChangelogs(appOutDir, packager, platform) {- let changelogsDir;+async function extractPackagedPandoc(appOutDir, packager, platform) {+ const resourcePath = getPackagedResourcePath(appOutDir, packager, platform);+ const archivePath = path.join(resourcePath, "pandoc.zip");+ try {+ await fsPromises.access(archivePath);+ } catch (error) {+ if (error.code === "ENOENT") {+ return;+ }+ throw error;+ }++ const pandocDir = path.join(resourcePath, "pandoc");+ const pandocBin = path.join(pandocDir, "bin", platform === "win32" ? "pandoc.exe" : "pandoc");+ try {+ await fsPromises.rm(pandocDir, {force: true, recursive: true});+ await fsPromises.mkdir(pandocDir, {recursive: true});+ await fs.createReadStream(archivePath).pipe(unzipper.Extract({path: pandocDir})).promise();++ const stat = await fsPromises.stat(pandocBin);+ if (!stat.isFile() || stat.size === 0) {+ throw new Error(`invalid Pandoc executable: ${pandocBin}`);+ }+ if (platform !== "win32") {+ await fsPromises.chmod(pandocBin, 0o755);+ }+ await fsPromises.rm(archivePath);+ console.log(`Extracted packaged Pandoc: ${pandocBin}`);+ } catch (error) {+ throw new Error(`Failed to extract packaged Pandoc: ${error.message}`);+ }+}++function getPackagedResourcePath(appOutDir, packager, platform) {if (platform === "darwin") {- const appName = packager.appInfo.productFilename;- changelogsDir = path.join(appOutDir, `${appName}.app`, "Contents", "Resources", "changelogs");- } else {- changelogsDir = path.join(appOutDir, "resources", "changelogs");+ return path.join(appOutDir, `${packager.appInfo.productFilename}.app`, "Contents", "Resources");}+ return path.join(appOutDir, "resources");+}++// 打包时裁剪 changelog,只保留当前版本 changelogs/v{version}/,详见 trimChangelogs.js。+async function trimPackagedChangelogs(appOutDir, packager, platform) {+ const changelogsDir = path.join(getPackagedResourcePath(appOutDir, packager, platform), "changelogs");try {const result = await trimChangelogs(changelogsDir, packager.appInfo.version);@@ -145,3 +182,4 @@ function formatBytes(bytes) {return `${formattedSize} ${sizes[i]}`;}+module.exports.extractPackagedPandoc = extractPackagedPandoc;diff --git a/app/scripts/afterPack.test.js b/app/scripts/afterPack.test.jsnew file mode 100644index 0000000000..84eea4b4fa--- /dev/null+++ b/app/scripts/afterPack.test.js@@ -0,0 +1,35 @@+const assert = require("node:assert/strict");+const fs = require("node:fs").promises;+const os = require("node:os");+const path = require("node:path");+const test = require("node:test");+const {extractPackagedPandoc} = require("./afterPack");++const PANDOC_ZIP = "UEsDBBQAAAAIAFxK/lz1kGVQDQAAAAsAAAAOAAAAYmluL3BhbmRvYy5leGUrSS0u0S1IzEvJTwYAUEsDBBQAAAAIAFxK/lzzFYE4CwAAAAkAAAANAAAAQ09QWVJJR0hULnR4dEvOL6gsykzPKAEAUEsBAhQAFAAAAAgAXEr+XPWQZVANAAAACwAAAA4AAAAAAAAAAAAAAIABAAAAAGJpbi9wYW5kb2MuZXhlUEsBAhQAFAAAAAgAXEr+XPMVgTgLAAAACQAAAA0AAAAAAAAAAAAAAIABOQAAAENPUFlSSUdIVC50eHRQSwUGAAAAAAIAAgB3AAAAbwAAAAAA";++test("extractPackagedPandoc extracts the executable and removes the archive", async () => {+ const appOutDir = await fs.mkdtemp(path.join(os.tmpdir(), "siyuan-after-pack-"));+ try {+ const resourcesDir = path.join(appOutDir, "resources");+ await fs.mkdir(resourcesDir, {recursive: true});+ await fs.writeFile(path.join(resourcesDir, "pandoc.zip"), Buffer.from(PANDOC_ZIP, "base64"));++ await extractPackagedPandoc(appOutDir, {appInfo: {productFilename: "SiYuan"}}, "win32");++ assert.equal(await fs.readFile(path.join(resourcesDir, "pandoc", "bin", "pandoc.exe"), "utf8"), "test-pandoc");+ assert.equal(await fs.readFile(path.join(resourcesDir, "pandoc", "COPYRIGHT.txt"), "utf8"), "copyright");+ await assert.rejects(fs.access(path.join(resourcesDir, "pandoc.zip")));+ } finally {+ await fs.rm(appOutDir, {force: true, recursive: true});+ }+});++test("extractPackagedPandoc skips platforms without an archive", async () => {+ const appOutDir = await fs.mkdtemp(path.join(os.tmpdir(), "siyuan-after-pack-"));+ try {+ await fs.mkdir(path.join(appOutDir, "resources"), {recursive: true});+ await extractPackagedPandoc(appOutDir, {appInfo: {productFilename: "SiYuan"}}, "win32");+ } finally {+ await fs.rm(appOutDir, {force: true, recursive: true});+ }+});diff --git a/app/src/config/tabs/exportRuntime.ts b/app/src/config/tabs/exportRuntime.tsindex 318be4b18d..70bd19f887 100644--- a/app/src/config/tabs/exportRuntime.ts+++ b/app/src/config/tabs/exportRuntime.ts@@ -4,7 +4,7 @@ const applyExportConfig = (data: Config.IExport) => {window.siyuan.config.export = data;const pathDisplay = document.getElementById("pandocBinPathDisplay");if (pathDisplay) {- pathDisplay.textContent = data.pandocBin;+ pathDisplay.textContent = data.pandocBin || `${window.siyuan.languages.builtIn} Pandoc`;}};diff --git a/app/src/config/tabs/exportTab.ts b/app/src/config/tabs/exportTab.tsindex 2ff612d93e..dd87464313 100644--- a/app/src/config/tabs/exportTab.ts+++ b/app/src/config/tabs/exportTab.ts@@ -146,7 +146,9 @@ const registerExportPandocGroup = (tab: SettingTabBuilder) => {],afterMount: mountExportPandocStack,}, (stack) => {- stack.title(`${window.siyuan.languages.export19}<span class="fn__space"></span><a href="javascript:void(0)" id="pandocBinPathDisplay" style="word-break: break-all">${Lute.EscapeHTMLStr(window.siyuan.config.export.pandocBin)}</a>`);+ const pandocBinLabel = window.siyuan.config.export.pandocBin ?+ Lute.EscapeHTMLStr(window.siyuan.config.export.pandocBin) : `${window.siyuan.languages.builtIn} Pandoc`;+ stack.title(`${window.siyuan.languages.export19}<span class="fn__space"></span><a href="javascript:void(0)" id="pandocBinPathDisplay" style="word-break: break-all">${pandocBinLabel}</a>`);stack.button({id: "pandocBinReset",label: window.siyuan.languages.reset,diff --git a/kernel/api/setting.go b/kernel/api/setting.goindex 0a790a9ef9..e1a79f6f99 100644--- a/kernel/api/setting.go+++ b/kernel/api/setting.go@@ -482,25 +482,16 @@ func setExport(c *gin.Context) {return}- // 重置为空字符串表示恢复内置 Pandoc:先落盘清空自定义路径,再重新初始化并写回默认路径- if "" == export.PandocBin {- model.Conf.Export = export- model.Conf.Save()- util.InitPandoc()- export.PandocBin = util.PandocBinPath- }-if "" != export.PandocBin {if !util.IsValidPandocBin(export.PandocBin) {util.PushErrMsg(fmt.Sprintf(model.Conf.Language(117), export.PandocBin), 5000)- export.PandocBin = util.PandocBinPath- } else {- util.PandocBinPath = export.PandocBin+ export.PandocBin = model.Conf.Export.PandocBin}}model.Conf.Export = exportmodel.Conf.Save()+ util.InitPandoc(export.PandocBin)ret.Data = model.Conf.Export}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 76f4283768..7a474cb8bc 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -33,7 +33,6 @@ import ("github.com/88250/lute""github.com/88250/lute/ast""github.com/Xuanwo/go-locale"- "github.com/siyuan-note/eventbus""github.com/siyuan-note/filelock""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/conf"@@ -439,10 +438,6 @@ func InitConf() {// 锚点哈希模式和脚注模式合并 https://github.com/siyuan-note/siyuan/issues/13331Conf.Export.BlockRefMode = 4 // 改为脚注+锚点哈希}- if "" == Conf.Export.PandocBin {- Conf.Export.PandocBin = util.PandocBinPath- }-if nil == Conf.Graph || nil == Conf.Graph.Local || nil == Conf.Graph.Global {Conf.Graph = conf.NewGraph()}@@ -512,6 +507,9 @@ func InitConf() {Conf.Export.DocxTemplate = ""Conf.Save()}+ if migratePandocConfig(Conf.Export) {+ Conf.Save()+ }if nil == Conf.Snippet {Conf.Snippet = conf.NewSnpt()@@ -770,7 +768,7 @@ func InitConf() {util.SetNetworkProxy(Conf.System.NetworkProxy.String())- go util.InitPandoc()+ go util.InitPandoc(Conf.Export.PandocBin)go util.InitTesseract()}@@ -1496,28 +1494,6 @@ func closeUserGuide() {}}-func init() {- subscribeConfEvents()-}--func subscribeConfEvents() {- eventbus.Subscribe(util.EvtConfPandocInitialized, func() {- logging.LogInfof("pandoc initialized, set pandoc bin to [%s]", util.PandocBinPath)- Conf.Export.PandocBin = util.PandocBinPath-- params := util.RemoveInvalid(Conf.Export.PandocParams)- if !strings.Contains(params, "--reference-doc") && "" != util.PandocTemplatePath && !Conf.System.IsMicrosoftStore {- params += " --reference-doc"- params += " \"" + util.PandocTemplatePath + "\""- Conf.Export.PandocParams = strings.TrimSpace(params)- }-- logging.LogInfof("pandoc params set to [%s]", Conf.Export.PandocParams)- logging.LogInfof("pandoc resources [%s, %s]", util.PandocTemplatePath, util.PandocColorFilterPath)- Conf.Save()- })-}-// NotebookCryptoEnabled 返回加密笔记本功能是否已启用(线程安全)。func NotebookCryptoEnabled() bool {Conf.m.RLock()diff --git a/kernel/model/export.go b/kernel/model/export.goindex 81266f7a0e..6bb2e231cf 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -990,10 +990,11 @@ func ExportPreview(id string, fillCSSVar bool) (retStdHTML string) {func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string, err error) {err = withExportReadLockByBlockID(id, func() error {- if !util.IsValidPandocBin(Conf.Export.PandocBin) {- Conf.Export.PandocBin = util.PandocBinPath- Conf.Save()- if !util.IsValidPandocBin(Conf.Export.PandocBin) {+ pandocBinPath := util.GetPandocBinPath()+ if !util.IsValidPandocBin(pandocBinPath) {+ util.InitPandoc(Conf.Export.PandocBin)+ pandocBinPath = util.GetPandocBinPath()+ if !util.IsValidPandocBin(pandocBinPath) {return errors.New(Conf.Language(115))}}@@ -1030,29 +1031,15 @@ func ExportDocx(id, savePath string, removeAssets, merge bool) (fullPath string,}}- hasLuaFilter := false- for i := 0; i < len(args)-1; i++ {- if "--lua-filter" == args[i] {- hasLuaFilter = true- break- }- }- if !hasLuaFilter {+ if !hasPandocOption(args, "--lua-filter") && "" != util.PandocColorFilterPath {args = append(args, "--lua-filter", util.PandocColorFilterPath)}- hasReferenceDoc := false- for i := 0; i < len(args)-1; i++ {- if "--reference-doc" == args[i] {- hasReferenceDoc = true- break- }- }- if !hasReferenceDoc {+ if !hasPandocOption(args, "--reference-doc") && "" != util.PandocTemplatePath {args = append(args, "--reference-doc", util.PandocTemplatePath)}- pandoc := exec.Command(Conf.Export.PandocBin, args...)+ pandoc := exec.Command(pandocBinPath, args...)gulu.CmdAttr(pandoc)pandoc.Stdin = bytes.NewBufferString(content)output, pandocErr := pandoc.CombinedOutput()diff --git a/kernel/model/pandoc_config.go b/kernel/model/pandoc_config.gonew file mode 100644index 0000000000..ab60e3a729--- /dev/null+++ b/kernel/model/pandoc_config.go@@ -0,0 +1,127 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "path/filepath"+ "runtime"+ "strings"++ shellquote "github.com/kballard/go-shellquote"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func migratePandocConfig(export *conf.Export) bool {+ if nil == export {+ return false+ }++ changed := false+ if isPathWithin(filepath.Join(util.TempDir, "pandoc"), export.PandocBin) {+ export.PandocBin = ""+ changed = true+ }++ if params, migrated := removeBuiltinPandocTemplateParam(export.PandocParams); migrated {+ export.PandocParams = params+ changed = true+ }+ return changed+}++func removeBuiltinPandocTemplateParam(params string) (ret string, migrated bool) {+ args, err := shellquote.Split(params)+ if err != nil {+ return params, false+ }++ retArgs := make([]string, 0, len(args))+ for i := 0; i < len(args); i++ {+ arg := args[i]+ if "--reference-doc" == arg && i+1 < len(args) && isBuiltinPandocTemplatePath(args[i+1]) {+ i+++ migrated = true+ continue+ }+ if strings.HasPrefix(arg, "--reference-doc=") &&+ isBuiltinPandocTemplatePath(strings.TrimPrefix(arg, "--reference-doc=")) {+ migrated = true+ continue+ }+ retArgs = append(retArgs, arg)+ }+ if !migrated {+ return params, false+ }+ return shellquote.Join(retArgs...), true+}++func hasPandocOption(args []string, option string) bool {+ for _, arg := range args {+ if option == arg || strings.HasPrefix(arg, option+"=") {+ return true+ }+ }+ return false+}++func isBuiltinPandocTemplatePath(templatePath string) bool {+ templatePath = strings.TrimSpace(templatePath)+ if "" == templatePath {+ return false+ }++ candidates := []string{+ filepath.Join(util.WorkingDir, "pandoc-resources", "pandoc-template.docx"),+ filepath.Join(util.WorkingDir, "pandoc", "pandoc-resources", "pandoc-template.docx"),+ }+ for _, candidate := range candidates {+ if sameFilePath(candidate, templatePath) {+ return true+ }+ }++ normalized := strings.ToLower(strings.ReplaceAll(templatePath, "\\", "/"))+ parts := strings.Split(normalized, "/")+ for i, part := range parts {+ if strings.HasPrefix(part, "89c2a984.siyuan_") && strings.HasSuffix(part, "__1qfd3tsw4ngc2") {+ return strings.Join(parts[i+1:], "/") ==+ "app/resources/pandoc-resources/pandoc-template.docx"+ }+ }+ return false+}++func sameFilePath(a, b string) bool {+ a, b = filepath.Clean(a), filepath.Clean(b)+ if "windows" == runtime.GOOS {+ return strings.EqualFold(a, b)+ }+ return a == b+}++func isPathWithin(root, target string) bool {+ if "" == root || "" == target {+ return false+ }+ rel, err := filepath.Rel(filepath.Clean(root), filepath.Clean(target))+ if err != nil {+ return false+ }+ return "." == rel || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))+}diff --git a/kernel/model/pandoc_config_test.go b/kernel/model/pandoc_config_test.gonew file mode 100644index 0000000000..3575a4a3f7--- /dev/null+++ b/kernel/model/pandoc_config_test.go@@ -0,0 +1,154 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "path/filepath"+ "testing"++ shellquote "github.com/kballard/go-shellquote"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestMigratePandocConfig(t *testing.T) {+ oldTempDir, oldWorkingDir := util.TempDir, util.WorkingDir+ util.TempDir, util.WorkingDir = t.TempDir(), t.TempDir()+ defer func() {+ util.TempDir, util.WorkingDir = oldTempDir, oldWorkingDir+ }()++ export := &conf.Export{+ PandocBin: filepath.Join(util.TempDir, "pandoc", "bin", "pandoc.exe"),+ PandocParams: `--toc --reference-doc "C:\Program Files\WindowsApps\89C2A984.SiYuan_3.5.5.0_x64__1qfd3tsw4ngc2\app\resources\pandoc-resources\pandoc-template.docx" ` ++ `--metadata title=test`,+ }+ if !migratePandocConfig(export) {+ t.Fatal("expected Pandoc configuration migration")+ }+ if "" != export.PandocBin {+ t.Fatalf("legacy built-in Pandoc path was not cleared: %q", export.PandocBin)+ }++ args, err := shellquote.Split(export.PandocParams)+ if err != nil {+ t.Fatalf("split migrated Pandoc parameters failed: %v", err)+ }+ expected := []string{"--toc", "--metadata", "title=test"}+ if len(args) != len(expected) {+ t.Fatalf("unexpected migrated Pandoc parameters: %#v", args)+ }+ for i, arg := range args {+ if expected[i] != arg {+ t.Fatalf("unexpected migrated Pandoc argument at %d: %q", i, arg)+ }+ }+}++func TestMigratePandocConfigPreservesCustomPaths(t *testing.T) {+ oldTempDir, oldWorkingDir := util.TempDir, util.WorkingDir+ util.TempDir, util.WorkingDir = t.TempDir(), t.TempDir()+ defer func() {+ util.TempDir, util.WorkingDir = oldTempDir, oldWorkingDir+ }()++ export := &conf.Export{+ PandocBin: filepath.Join(t.TempDir(), "pandoc.exe"),+ PandocParams: `--reference-doc "data/storage/template.docx" --toc`,+ }+ if migratePandocConfig(export) {+ t.Fatalf("custom Pandoc configuration was unexpectedly migrated: %#v", export)+ }+}++func TestRemoveBuiltinPandocTemplateParam(t *testing.T) {+ oldWorkingDir := util.WorkingDir+ util.WorkingDir = t.TempDir()+ defer func() {+ util.WorkingDir = oldWorkingDir+ }()++ currentTemplate := filepath.Join(util.WorkingDir, "pandoc-resources", "pandoc-template.docx")+ tests := []struct {+ name string+ params string+ migrated bool+ }{+ {+ name: "current built-in template",+ params: shellquote.Join("--reference-doc", currentTemplate, "--toc"),+ migrated: true,+ },+ {+ name: "Microsoft Store equals syntax",+ params: `--reference-doc="C:\Program Files\WindowsApps\89C2A984.SiYuan_3.5.6.0_x64__1qfd3tsw4ngc2` ++ `\app\resources\pandoc-resources\pandoc-template.docx"`,+ migrated: true,+ },+ {+ name: "relative template",+ params: `--reference-doc "data/storage/template.docx"`,+ migrated: false,+ },+ {+ name: "custom absolute template",+ params: shellquote.Join("--reference-doc", filepath.Join(t.TempDir(), "template.docx")),+ migrated: false,+ },+ {+ name: "malformed parameters",+ params: `--reference-doc "unterminated`,+ migrated: false,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ params, migrated := removeBuiltinPandocTemplateParam(test.params)+ if test.migrated != migrated {+ t.Fatalf("unexpected migration result: %v, params: %q", migrated, params)+ }+ if !test.migrated && test.params != params {+ t.Fatalf("parameters changed without migration: %q", params)+ }+ if test.migrated && hasPandocOption(mustSplitPandocParams(t, params), "--reference-doc") {+ t.Fatalf("built-in reference document parameter was not removed: %q", params)+ }+ })+ }+}++func TestHasPandocOption(t *testing.T) {+ if !hasPandocOption([]string{"--reference-doc", "template.docx"}, "--reference-doc") {+ t.Fatal("separate Pandoc option was not detected")+ }+ if !hasPandocOption([]string{"--reference-doc=template.docx"}, "--reference-doc") {+ t.Fatal("equals-style Pandoc option was not detected")+ }+ if hasPandocOption([]string{"--reference-document", "template.docx"}, "--reference-doc") {+ t.Fatal("unrelated Pandoc option was detected")+ }+}++func mustSplitPandocParams(t *testing.T, params string) []string {+ t.Helper()+ args, err := shellquote.Split(params)+ if err != nil {+ t.Fatalf("split Pandoc parameters failed: %v", err)+ }+ return args+}diff --git a/kernel/util/pandoc.go b/kernel/util/pandoc.goindex a231d02a98..8280d8e4e7 100644--- a/kernel/util/pandoc.go+++ b/kernel/util/pandoc.go@@ -24,21 +24,22 @@ import ("path/filepath""runtime""strings"+ "sync""github.com/88250/gulu"- "github.com/siyuan-note/eventbus""github.com/siyuan-note/logging")var ErrPandocNotFound = errors.New("not found executable pandoc")func ConvertPandoc(dir string, args ...string) (path string, err error) {- if "" == PandocBinPath || ContainerStd != Container {+ pandocBinPath := GetPandocBinPath()+ if "" == pandocBinPath || ContainerStd != Container {err = ErrPandocNotFoundreturn}- pandoc := exec.Command(PandocBinPath, args...)+ pandoc := exec.Command(pandocBinPath, args...)gulu.CmdAttr(pandoc)path = filepath.Join("temp", "convert", "pandoc", dir)absPath := filepath.Join(WorkspaceDir, path)@@ -65,7 +66,8 @@ func Pandoc(from, to, o, content string) (err error) {return}- if "" == PandocBinPath || ContainerStd != Container {+ pandocBinPath := GetPandocBinPath()+ if "" == pandocBinPath || ContainerStd != Container {err = ErrPandocNotFoundreturn}@@ -90,7 +92,7 @@ func Pandoc(from, to, o, content string) (err error) {"-o", o,}- pandoc := exec.Command(PandocBinPath, args...)+ pandoc := exec.Command(pandocBinPath, args...)gulu.CmdAttr(pandoc)output, err := pandoc.CombinedOutput()if err != nil {@@ -101,18 +103,25 @@ func Pandoc(from, to, o, content string) (err error) {}var (- PandocBinPath string // Pandoc 可执行文件路径+ activePandocBinPath string // 当前使用的 Pandoc 可执行文件路径PandocTemplatePath string // Pandoc Docx 模板文件路径PandocColorFilterPath string // Pandoc 颜色过滤器路径+ pandocInitMutex sync.Mutex)-func InitPandoc() {+func GetPandocBinPath() string {+ pandocInitMutex.Lock()+ defer pandocInitMutex.Unlock()+ return activePandocBinPath+}++func InitPandoc(customPandocBinPath string) {if ContainerStd != Container {return}- defer eventbus.Publish(EvtConfPandocInitialized)-+ pandocInitMutex.Lock()+ defer pandocInitMutex.Unlock()PandocTemplatePath = filepath.Join(WorkingDir, "pandoc-resources", "pandoc-template.docx")if !gulu.File.IsExist(PandocTemplatePath) {PandocTemplatePath = filepath.Join(WorkingDir, "pandoc", "pandoc-resources", "pandoc-template.docx")@@ -131,38 +140,35 @@ func InitPandoc() {logging.LogWarnf("pandoc color filter file [%s] not found", PandocColorFilterPath)}+ activePandocBinPath = ""+tempPandocDir := filepath.Join(TempDir, "pandoc")- if confPath := filepath.Join(ConfDir, "conf.json"); gulu.File.IsExist(confPath) {- // Workspace built-in Pandoc is no longer initialized after customizing Pandoc path https://github.com/siyuan-note/siyuan/issues/8377- if data, err := os.ReadFile(confPath); err == nil {- conf := map[string]any{}- if err = gulu.JSON.UnmarshalJSON(data, &conf); err == nil && nil != conf["export"] {- export := conf["export"].(map[string]any)- if customPandocBinPath := export["pandocBin"].(string); !strings.HasPrefix(customPandocBinPath, tempPandocDir) {- if pandocVer := getPandocVer(customPandocBinPath); "" != pandocVer {- PandocBinPath = customPandocBinPath- logging.LogInfof("custom pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)- return- }- }+ installedPandocBinPath := pandocBinPath(filepath.Join(WorkingDir, "pandoc"))+ installedPandocVer := getPandocVer(installedPandocBinPath)++ customPandocBinPath = strings.TrimSpace(customPandocBinPath)+ if "" != customPandocBinPath && !isPathWithin(tempPandocDir, customPandocBinPath) {+ if pandocVer := getPandocVer(customPandocBinPath); "" != pandocVer {+ activePandocBinPath = customPandocBinPath+ logging.LogInfof("custom pandoc [ver=%s, bin=%s]", pandocVer, activePandocBinPath)+ if "" != installedPandocVer {+ removeLegacyPandocDir(tempPandocDir)}+ return}}- if gulu.OS.IsWindows() {- if "amd64" == runtime.GOARCH {- PandocBinPath = filepath.Join(tempPandocDir, "bin", "pandoc.exe")- }- } else if gulu.OS.IsDarwin() {- PandocBinPath = filepath.Join(tempPandocDir, "bin", "pandoc")- } else if gulu.OS.IsLinux() {- if "amd64" == runtime.GOARCH {- PandocBinPath = filepath.Join(tempPandocDir, "bin", "pandoc")- }+ if "" != installedPandocVer {+ activePandocBinPath = installedPandocBinPath+ logging.LogInfof("built-in pandoc [ver=%s, bin=%s]", installedPandocVer, activePandocBinPath)+ removeLegacyPandocDir(tempPandocDir)+ return}- pandocVer := getPandocVer(PandocBinPath)++ activePandocBinPath = pandocBinPath(tempPandocDir)+ pandocVer := getPandocVer(activePandocBinPath)if "" != pandocVer {- logging.LogInfof("built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)+ logging.LogInfof("built-in pandoc [ver=%s, bin=%s]", pandocVer, activePandocBinPath)return}@@ -188,21 +194,62 @@ func InitPandoc() {}if !gulu.File.IsExist(pandocZip) {- PandocBinPath = ""+ activePandocBinPath = ""logging.LogErrorf("pandoc zip [%s] not found", pandocZip)return}if err := gulu.Zip.Unzip(pandocZip, tempPandocDir); err != nil {+ activePandocBinPath = ""logging.LogErrorf("unzip pandoc failed: %s", err)return}if gulu.OS.IsDarwin() || gulu.OS.IsLinux() {- exec.Command("chmod", "+x", PandocBinPath).CombinedOutput()+ exec.Command("chmod", "+x", activePandocBinPath).CombinedOutput()+ }+ pandocVer = getPandocVer(activePandocBinPath)+ if "" == pandocVer {+ activePandocBinPath = ""+ logging.LogErrorf("initialized built-in pandoc is invalid")+ return+ }+ logging.LogInfof("initialized built-in pandoc [ver=%s, bin=%s]", pandocVer, activePandocBinPath)+}++func pandocBinPath(pandocDir string) string {+ if gulu.OS.IsWindows() {+ if "amd64" == runtime.GOARCH {+ return filepath.Join(pandocDir, "bin", "pandoc.exe")+ }+ } else if gulu.OS.IsDarwin() {+ return filepath.Join(pandocDir, "bin", "pandoc")+ } else if gulu.OS.IsLinux() {+ return filepath.Join(pandocDir, "bin", "pandoc")+ }+ return ""+}++func isPathWithin(root, target string) bool {+ if "" == root || "" == target {+ return false+ }+ rel, err := filepath.Rel(filepath.Clean(root), filepath.Clean(target))+ if err != nil {+ return false+ }+ return "." == rel || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))+}++func removeLegacyPandocDir(tempPandocDir string) {+ if !gulu.File.IsExist(tempPandocDir) {+ return+ }+ if err := os.RemoveAll(tempPandocDir); err != nil {+ logging.LogWarnf("remove legacy pandoc folder [%s] failed: %s", tempPandocDir, err)+ return}- pandocVer = getPandocVer(PandocBinPath)- logging.LogInfof("initialized built-in pandoc [ver=%s, bin=%s]", pandocVer, PandocBinPath)+ logging.LogInfof("removed legacy pandoc folder [%s]", tempPandocDir)}func getPandocVer(binPath string) (ret string) {diff --git a/kernel/util/runtime.go b/kernel/util/runtime.goindex b537107713..3eb79e2ea5 100644--- a/kernel/util/runtime.go+++ b/kernel/util/runtime.go@@ -502,8 +502,6 @@ func existAvailabilityStatus(workspaceAbsPath string) bool {}const (- EvtConfPandocInitialized = "conf.pandoc.initialized"-EvtSQLHistoryRebuild = "sql.history.rebuild"EvtSQLAssetContentRebuild = "sql.assetContent.rebuild")