Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Command Line Interface https://github.com/siyuan-note/siyuan/issues/17674

Daniel490ede88f6c9
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 1592061bdf..ea0ec6bd82 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -57,12 +57,7 @@ func moveLocalShorthands(c *gin.Context) {
return
}
- model.FlushTxQueue()
- box := model.Conf.Box(notebook)
- for _, id := range ids {
- b, _ := model.GetBlock(id, nil)
- pushCreate(box, b.Path, arg)
- }
+ ret.Data = ids
}
func listDocTree(c *gin.Context) {
@@ -694,10 +689,7 @@ func duplicateDoc(c *gin.Context) {
}
notebook := tree.Box
- box := model.Conf.Box(notebook)
model.DuplicateDoc(tree)
- arg["listDocTree"] = true
- pushCreate(box, tree.Path, arg)
ret.Data = map[string]any{
"id": tree.Root.ID,
@@ -728,7 +720,7 @@ func createDoc(c *gin.Context) {
}
}
- tree, err := model.CreateDocByMd(notebook, p, title, md, sorts)
+ tree, err := model.CreateDocByMd(notebook, p, title, md, sorts, arg)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
@@ -736,10 +728,6 @@ func createDoc(c *gin.Context) {
return
}
- model.FlushTxQueue()
- box := model.Conf.Box(notebook)
- pushCreate(box, p, arg)
-
ret.Data = map[string]any{
"id": tree.Root.ID,
}
@@ -856,18 +844,13 @@ func createDocWithMd(c *gin.Context) {
clippingHref = clippingHrefArg.(string)
}
- id, err := model.CreateWithMarkdown(tags, notebook, hPath, markdown, parentID, id, withMath, clippingHref)
+ id, err := model.CreateWithMarkdown(tags, notebook, hPath, markdown, parentID, id, withMath, clippingHref, arg)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
return
}
ret.Data = id
-
- model.FlushTxQueue()
- box := model.Conf.Box(notebook)
- b, _ := model.GetBlock(id, nil)
- pushCreate(box, b.Path, arg)
}
func getDocCreateSavePath(c *gin.Context) {
@@ -1264,22 +1247,6 @@ func getDoc(c *gin.Context) {
}
}
-func pushCreate(box *model.Box, p string, arg map[string]any) {
- evt := util.NewCmdResult("create", 0, util.PushModeBroadcast)
- listDocTree := false
- listDocTreeArg := arg["listDocTree"]
- if nil != listDocTreeArg {
- listDocTree = listDocTreeArg.(bool)
- }
-
- evt.Data = map[string]any{
- "box": box,
- "path": p,
- "listDocTree": listDocTree,
- }
- util.PushEvent(evt)
-}
-
func setPublishAccess(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/cli/build.bat b/kernel/cli/build.bat
new file mode 100644
index 0000000000..1ee6ebe30c
--- /dev/null
+++ b/kernel/cli/build.bat
@@ -0,0 +1,123 @@
+@echo off
+echo.
+echo Building SiYuan CLI
+echo.
+cd /d "%~dp0..\"
+if errorlevel 1 (
+ exit /b %errorlevel%
+)
+
+set GO111MODULE=on
+set CGO_ENABLED=1
+
+if "%1"=="" (
+ set TARGET=local
+) else (
+ set TARGET=%1
+)
+
+if "%TARGET%"=="local" (
+ echo Building for local platform...
+ go build -tags fts5 -ldflags "-s -w" -o siyuan.exe ./cli
+ if errorlevel 1 (
+ echo Build failed
+ exit /b %errorlevel%
+ )
+ echo Done: siyuan.exe
+ goto :end
+)
+
+if "%TARGET%"=="windows" (
+ echo Building Windows amd64...
+ set GOOS=windows
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-win-amd64.exe ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-win-amd64.exe
+)
+
+if "%TARGET%"=="linux" (
+ echo Building Linux amd64...
+ set GOOS=linux
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-amd64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-linux-amd64
+
+ echo Building Linux arm64...
+ set GOOS=linux
+ set GOARCH=arm64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-arm64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-linux-arm64
+)
+
+if "%TARGET%"=="darwin" (
+ echo Building macOS amd64...
+ set GOOS=darwin
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-amd64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-darwin-amd64
+
+ echo Building macOS arm64...
+ set GOOS=darwin
+ set GOARCH=arm64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-arm64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-darwin-arm64
+)
+
+if "%TARGET%"=="all" (
+ call :build_windows
+ call :build_linux
+ call :build_darwin
+ goto :end
+)
+
+goto :end
+
+:build_windows
+ echo Building Windows amd64...
+ set GOOS=windows
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-win-amd64.exe ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-win-amd64.exe
+ exit /b
+
+:build_linux
+ echo Building Linux amd64...
+ set GOOS=linux
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-amd64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-linux-amd64
+
+ echo Building Linux arm64...
+ set GOOS=linux
+ set GOARCH=arm64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-arm64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-linux-arm64
+ exit /b
+
+:build_darwin
+ echo Building macOS amd64...
+ set GOOS=darwin
+ set GOARCH=amd64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-amd64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-darwin-amd64
+
+ echo Building macOS arm64...
+ set GOOS=darwin
+ set GOARCH=arm64
+ go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-arm64 ./cli
+ if errorlevel 1 ( exit /b %errorlevel% )
+ echo Done: siyuan-darwin-arm64
+ exit /b
+
+:end
+echo.
+echo Build complete.
diff --git a/kernel/cli/build.sh b/kernel/cli/build.sh
new file mode 100644
index 0000000000..774c5dfad0
--- /dev/null
+++ b/kernel/cli/build.sh
@@ -0,0 +1,67 @@
+#!/bin/bash
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+KERNEL_DIR="$(dirname "$SCRIPT_DIR")"
+cd "$KERNEL_DIR"
+
+export GO111MODULE=on
+export CGO_ENABLED=1
+
+build_local() {
+ echo "Building for local platform..."
+ go build -tags fts5 -ldflags "-s -w" -o siyuan ./cli
+ echo "Done: siyuan"
+}
+
+build_windows() {
+ echo "Building Windows amd64..."
+ GOOS=windows GOARCH=amd64 go build -tags fts5 -ldflags "-s -w" -o siyuan-win-amd64.exe ./cli
+ echo "Done: siyuan-win-amd64.exe"
+}
+
+build_linux() {
+ echo "Building Linux amd64..."
+ GOOS=linux GOARCH=amd64 go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-amd64 ./cli
+ echo "Done: siyuan-linux-amd64"
+
+ echo "Building Linux arm64..."
+ GOOS=linux GOARCH=arm64 go build -tags fts5 -ldflags "-s -w" -o siyuan-linux-arm64 ./cli
+ echo "Done: siyuan-linux-arm64"
+}
+
+build_darwin() {
+ echo "Building macOS amd64..."
+ GOOS=darwin GOARCH=amd64 go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-amd64 ./cli
+ echo "Done: siyuan-darwin-amd64"
+
+ echo "Building macOS arm64..."
+ GOOS=darwin GOARCH=arm64 go build -tags fts5 -ldflags "-s -w" -o siyuan-darwin-arm64 ./cli
+ echo "Done: siyuan-darwin-arm64"
+}
+
+TARGET="${1:-local}"
+
+case "$TARGET" in
+ local) build_local ;;
+ windows) build_windows ;;
+ linux) build_linux ;;
+ darwin) build_darwin ;;
+ all)
+ build_windows
+ build_linux
+ build_darwin
+ ;;
+ *)
+ echo "Usage: $0 [local|windows|linux|darwin|all]"
+ echo " local Build for current platform (default)"
+ echo " windows Build Windows amd64"
+ echo " linux Build Linux amd64 + arm64"
+ echo " darwin Build macOS amd64 + arm64"
+ echo " all Build all platforms"
+ exit 1
+ ;;
+esac
+
+echo ""
+echo "Build complete."
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.go
new file mode 100644
index 0000000000..897dbb8711
--- /dev/null
+++ b/kernel/cli/cmd/document.go
@@ -0,0 +1,221 @@
+// 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 cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "math/rand"
+ "os"
+ "path"
+ "text/tabwriter"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+
+ "github.com/spf13/cobra"
+)
+
+var documentCmd = &cobra.Command{
+ Use: "document",
+ Short: "Manage documents",
+}
+
+var documentListCmd = &cobra.Command{
+ Use: "list --notebook <id>",
+ Short: "List documents in a notebook",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ notebook, _ := cmd.Flags().GetString("notebook")
+ docPath, _ := cmd.Flags().GetString("path")
+ if notebook == "" {
+ return fmt.Errorf("--notebook is required")
+ }
+ if docPath == "" {
+ docPath = "/"
+ }
+ files, _, err := model.ListDocTree(notebook, docPath, 0, false, false, 128)
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(files, "", " ")
+ fmt.Println(string(data))
+ default:
+ printDocumentTable(files)
+ }
+ return nil
+ },
+}
+
+var documentCreateCmd = &cobra.Command{
+ Use: "create --notebook <id> --title <title>",
+ Short: "Create a document",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ notebook, _ := cmd.Flags().GetString("notebook")
+ title, _ := cmd.Flags().GetString("title")
+ dir, _ := cmd.Flags().GetString("path")
+ markdown, _ := cmd.Flags().GetString("markdown")
+ if notebook == "" {
+ return fmt.Errorf("--notebook is required")
+ }
+ if title == "" {
+ return fmt.Errorf("--title is required")
+ }
+ if dir == "" {
+ dir = "/"
+ }
+
+ id := generateDocID()
+ docPath := path.Join(dir, id+".sy")
+ _, err := model.CreateDocByMd(notebook, docPath, title, markdown, nil, nil)
+ if err != nil {
+ return err
+ }
+ fmt.Println(id)
+ return nil
+ },
+}
+
+var documentGetCmd = &cobra.Command{
+ Use: "get --id <id>",
+ Short: "Get document info",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ bt := treenode.GetBlockTree(id)
+ if bt == nil {
+ return fmt.Errorf("document not found: %s", id)
+ }
+
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return err
+ }
+ block, err := model.GetBlock(id, tree)
+ if err != nil {
+ return err
+ }
+
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(block, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Printf("ID: %s\n", block.ID)
+ fmt.Printf("Title: %s\n", block.Name)
+ fmt.Printf("Type: %s\n", block.Type)
+ fmt.Printf("Box: %s\n", block.Box)
+ fmt.Printf("HPath: %s\n", block.HPath)
+ fmt.Printf("Created: %s\n", block.Created)
+ fmt.Printf("Updated: %s\n", block.Updated)
+ if block.Content != "" {
+ preview := block.Content
+ if len(preview) > 200 {
+ preview = preview[:200] + "..."
+ }
+ fmt.Printf("Content: %s\n", preview)
+ }
+ }
+ return nil
+ },
+}
+
+var documentRemoveCmd = &cobra.Command{
+ Use: "remove --id <id>",
+ Short: "Remove a document",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return err
+ }
+ model.RemoveDoc(tree.Box, tree.Path)
+ fmt.Println(id)
+ return nil
+ },
+}
+
+var documentRenameCmd = &cobra.Command{
+ Use: "rename --id <id> --title <title>",
+ Short: "Rename a document",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ title, _ := cmd.Flags().GetString("title")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ if title == "" {
+ return fmt.Errorf("--title is required")
+ }
+ tree, err := model.LoadTreeByBlockID(id)
+ if err != nil {
+ return err
+ }
+ if err := model.RenameDoc(tree.Box, tree.Path, title); err != nil {
+ return err
+ }
+ return nil
+ },
+}
+
+func printDocumentTable(files []*model.File) {
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "ID\tNAME\tSIZE\tCOUNT\tMTIME")
+ for _, f := range files {
+ fmt.Fprintf(w, "%s\t%s\t%s\t%d\t%s\n", f.ID, f.Name, f.HSize, f.Count, f.HMtime)
+ }
+ w.Flush()
+}
+
+func init() {
+ documentListCmd.Flags().String("notebook", "", "notebook ID")
+ documentListCmd.Flags().String("path", "", "subdirectory path (default /)")
+
+ documentCreateCmd.Flags().String("notebook", "", "notebook ID")
+ documentCreateCmd.Flags().String("title", "", "document title")
+ documentCreateCmd.Flags().String("path", "", "parent document path (default /)")
+ documentCreateCmd.Flags().String("markdown", "", "initial markdown content")
+
+ documentGetCmd.Flags().String("id", "", "document block ID")
+ documentRemoveCmd.Flags().String("id", "", "document block ID")
+ documentRenameCmd.Flags().String("id", "", "document block ID")
+ documentRenameCmd.Flags().String("title", "", "new document title")
+
+ rootCmd.AddCommand(documentCmd)
+ documentCmd.AddCommand(documentListCmd)
+ documentCmd.AddCommand(documentCreateCmd)
+ documentCmd.AddCommand(documentGetCmd)
+ documentCmd.AddCommand(documentRemoveCmd)
+ documentCmd.AddCommand(documentRenameCmd)
+}
+
+func generateDocID() string {
+ ts := time.Now().Format("20060102150405")
+ r := make([]byte, 7)
+ chars := "abcdefghijklmnopqrstuvwxyz0123456789"
+ for i := range r {
+ r[i] = chars[rand.Intn(len(chars))]
+ }
+ return ts + "-" + string(r)
+}
diff --git a/kernel/cli/cmd/notebook.go b/kernel/cli/cmd/notebook.go
new file mode 100644
index 0000000000..c019835c2d
--- /dev/null
+++ b/kernel/cli/cmd/notebook.go
@@ -0,0 +1,126 @@
+// 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 cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "text/tabwriter"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+
+ "github.com/spf13/cobra"
+)
+
+var notebookCmd = &cobra.Command{
+ Use: "notebook",
+ Short: "Manage notebooks",
+}
+
+var notebookListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List all notebooks",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ boxes, err := model.ListNotebooks()
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(boxes, "", " ")
+ fmt.Println(string(data))
+ default:
+ printNotebookTable(boxes)
+ }
+ return nil
+ },
+}
+
+var notebookCreateCmd = &cobra.Command{
+ Use: "create --name <name>",
+ Short: "Create a notebook",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ id, err := model.CreateBox(name)
+ if err != nil {
+ return err
+ }
+ fmt.Println(id)
+ return nil
+ },
+}
+
+var notebookRemoveCmd = &cobra.Command{
+ Use: "remove --id <id>",
+ Short: "Remove a notebook",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ if err := model.RemoveBox(id); err != nil {
+ return err
+ }
+ fmt.Println(id)
+ return nil
+ },
+}
+
+var notebookRenameCmd = &cobra.Command{
+ Use: "rename --id <id> --name <name>",
+ Short: "Rename a notebook",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ name, _ := cmd.Flags().GetString("name")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if err := model.RenameBox(id, name); err != nil {
+ return err
+ }
+ return nil
+ },
+}
+
+func printNotebookTable(boxes []*model.Box) {
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "ID\tNAME\tCLOSED\tSORT")
+ for _, b := range boxes {
+ fmt.Fprintf(w, "%s\t%s\t%v\t%d\n", b.ID, b.Name, b.Closed, b.Sort)
+ }
+ w.Flush()
+}
+
+func init() {
+ notebookCreateCmd.Flags().String("name", "", "notebook name")
+ notebookRemoveCmd.Flags().String("id", "", "notebook ID")
+ notebookRenameCmd.Flags().String("id", "", "notebook ID")
+ notebookRenameCmd.Flags().String("name", "", "new notebook name")
+
+ rootCmd.AddCommand(notebookCmd)
+ notebookCmd.AddCommand(notebookListCmd)
+ notebookCmd.AddCommand(notebookCreateCmd)
+ notebookCmd.AddCommand(notebookRemoveCmd)
+ notebookCmd.AddCommand(notebookRenameCmd)
+}
diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.go
new file mode 100644
index 0000000000..5216119330
--- /dev/null
+++ b/kernel/cli/cmd/root.go
@@ -0,0 +1,115 @@
+// 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 cmd
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+
+ "github.com/spf13/cobra"
+)
+
+var (
+ workspacePath string
+ outputFormat string
+)
+
+var rootCmd = &cobra.Command{
+ Use: "siyuan",
+ Short: "SiYuan Note CLI",
+ Long: `A command-line interface for SiYuan.`,
+ PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
+ // 确定工作目录
+ if exePath, err := os.Executable(); err == nil {
+ util.WorkingDir = filepath.Dir(exePath)
+ }
+
+ // 尝试在常见位置查找 appearance 目录
+ appDir := findAppDir()
+ if appDir != "" {
+ util.WorkingDir = appDir
+ }
+
+ // 设置工作空间路径
+ if workspacePath == "" {
+ workspacePath = os.Getenv("SIYUAN_WORKSPACE_PATH")
+ }
+ if workspacePath == "" {
+ workspacePath = filepath.Join(util.HomeDir, "SiYuan")
+ }
+
+ if _, err := os.Stat(workspacePath); os.IsNotExist(err) {
+ return fmt.Errorf("workspace not found: %s", workspacePath)
+ }
+
+ util.WorkspaceDir = workspacePath
+ util.ConfDir = filepath.Join(workspacePath, "conf")
+ util.DataDir = filepath.Join(workspacePath, "data")
+ util.TempDir = filepath.Join(workspacePath, "temp")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+
+ os.MkdirAll(util.TempDir, 0755)
+ logging.SetLogPath(filepath.Join(util.TempDir, "siyuan-cli.log"))
+ logging.SetLogToStdout(false)
+
+ model.InitConf()
+ sql.InitDatabase(false)
+
+ return nil
+ },
+}
+
+func findAppDir() string {
+ if exePath, err := os.Executable(); err == nil {
+ exeDir := filepath.Dir(exePath)
+ candidates := []string{
+ filepath.Join(exeDir, "..", "app"), // kernel/cli/ → kernel/ → app/
+ filepath.Join(exeDir, "app"), // kernel/ → app/
+ filepath.Join(exeDir, "..", "..", "app"), // kernel/cli/cmd/... → .../app/
+ }
+ // 添加 macOS app bundle 路径
+ if runtime.GOOS == "darwin" {
+ candidates = append(candidates,
+ filepath.Join(exeDir, "..", "..", "..", "..", "Resources"),
+ )
+ }
+ for _, d := range candidates {
+ langsDir := filepath.Join(d, "appearance", "langs")
+ if fi, err := os.Stat(langsDir); err == nil && fi.IsDir() {
+ return d
+ }
+ }
+ }
+ return ""
+}
+
+func init() {
+ rootCmd.PersistentFlags().StringVarP(&workspacePath, "workspace", "w", "", "workspace path")
+ rootCmd.PersistentFlags().StringVarP(&outputFormat, "format", "f", "table", "output format: table | json")
+}
+
+func Execute() error {
+ return rootCmd.Execute()
+}
diff --git a/kernel/cli/main.go b/kernel/cli/main.go
new file mode 100644
index 0000000000..2169bab603
--- /dev/null
+++ b/kernel/cli/main.go
@@ -0,0 +1,29 @@
+// 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 main
+
+import (
+ "os"
+
+ "github.com/siyuan-note/siyuan/kernel/cli/cmd"
+)
+
+func main() {
+ if err := cmd.Execute(); err != nil {
+ os.Exit(1)
+ }
+}
diff --git a/kernel/go.mod b/kernel/go.mod
index e976711cfe..31a4a28672 100644
--- a/kernel/go.mod
+++ b/kernel/go.mod
@@ -72,11 +72,12 @@ require (
github.com/siyuan-note/eventbus v0.0.0-20240627125516-396fdb0f0f97
github.com/siyuan-note/filelock v0.0.0-20260411141728-bf44452627c0
github.com/siyuan-note/httpclient v0.0.0-20260408083825-43e4476ad2b3
- github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1
+ github.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754
github.com/smallnest/chanx v1.2.0
github.com/soheilhy/cmux v0.1.5
github.com/spf13/cast v1.10.0
+ github.com/spf13/cobra v1.10.2
github.com/steambap/captcha v1.4.1
github.com/studio-b12/gowebdav v0.12.0
github.com/vanng822/css v1.0.1
@@ -93,8 +94,6 @@ require (
gopkg.in/yaml.v3 v3.0.1
)
-require gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
-
require (
dario.cat/mergo v1.0.2 // indirect
dmitri.shuralyov.com/font/woff2 v0.0.0-20180220214647-957792cbbdab // indirect
@@ -161,6 +160,7 @@ require (
github.com/hhrutter/tiff v1.0.2 // indirect
github.com/huandu/xstrings v1.5.0 // indirect
github.com/icholy/digest v1.1.0 // indirect
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jaypipes/pcidb v1.1.1 // indirect
github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 // indirect
github.com/jolestar/go-commons-pool/v2 v2.1.2 // indirect
@@ -189,6 +189,7 @@ require (
github.com/richardlehane/mscfb v1.0.6 // indirect
github.com/richardlehane/msoleps v1.0.6 // indirect
github.com/shopspring/decimal v1.4.0 // indirect
+ github.com/spf13/pflag v1.0.9 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
github.com/teambition/rrule-go v1.8.2 // indirect
github.com/tetratelabs/wazero v1.9.0 // indirect
@@ -207,6 +208,7 @@ require (
golang.org/x/image v0.38.0 // indirect
golang.org/x/tools v0.43.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
+ gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
howett.net/plist v1.0.2-0.20250314012144-ee69052608d9 // indirect
modernc.org/fileutil v1.4.0 // indirect
diff --git a/kernel/go.sum b/kernel/go.sum
index 9d5649ec07..140e282a20 100644
--- a/kernel/go.sum
+++ b/kernel/go.sum
@@ -109,6 +109,7 @@ github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be h1:J5BL2kskAlV9ckgEsNQXscjIaLiOYiZ75d4e94E6dcQ=
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be/go.mod h1:mk5IQ+Y0ZeO87b858TlA645sVcEcbiX6YqP98kt+7+w=
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -248,6 +249,8 @@ github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4=
github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
github.com/imroc/req/v3 v3.57.0 h1:LMTUjNRUybUkTPn8oJDq8Kg3JRBOBTcnDhKu7mzupKI=
github.com/imroc/req/v3 v3.57.0/go.mod h1:JL62ey1nvSLq81HORNcosvlf7SxZStONNqOprg0Pz00=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jaypipes/ghw v0.21.2 h1:woW0lqNMPbYk59sur6thOVM8YFP9Hxxr8PM+JtpUrNU=
github.com/jaypipes/ghw v0.21.2/go.mod h1:GPrvwbtPoxYUenr74+nAnWbardIZq600vJDD5HnPsPE=
github.com/jaypipes/pcidb v1.1.1 h1:QmPhpsbmmnCwZmHeYAATxEaoRuiMAJusKYkUncMC0ro=
@@ -365,6 +368,7 @@ github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjR
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/rqlite/sql v0.0.0-20251204023435-65660522892e h1:ccOm5zC6YqJtBrMmtiNcLPjFyWzB+TDY+fDIlQNsIFw=
github.com/rqlite/sql v0.0.0-20251204023435-65660522892e/go.mod h1:ib9zVtNgRKiGuoMyUqqL5aNpk+r+++YlyiVIkclVqPg=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjyw0ULyrTYWeN0UNCCkmCWfjPnIA2W6oviI=
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs=
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
@@ -391,8 +395,8 @@ github.com/siyuan-note/filelock v0.0.0-20260411141728-bf44452627c0 h1:9qiLwd2reW
github.com/siyuan-note/filelock v0.0.0-20260411141728-bf44452627c0/go.mod h1:ew8UsjZTqPTGmdR9Pd13Ep6hVVx+c69nHljuGDro/WU=
github.com/siyuan-note/httpclient v0.0.0-20260408083825-43e4476ad2b3 h1:zwfpFqYBhV7rPx6yC3AKjYW/5HOaBg2cuy4x4olWwQE=
github.com/siyuan-note/httpclient v0.0.0-20260408083825-43e4476ad2b3/go.mod h1:XxprEfaOoufvhLkI6rjfJrsNPFUAaCV6HI4M0e/Fr5w=
-github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1 h1:C2Y1XhBrrGegnHvWOeVVRFkMRzB6EqJSytHheq+T6mU=
-github.com/siyuan-note/logging v0.0.0-20260117134552-88b424dfe7f1/go.mod h1:t3Tmt3DgQx0zqJmrckszJ+JBZ7iJrD1Ktp8FDBQ249E=
+github.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490 h1:z8m0SaVN/9rQqQE+EHbqBoqEz7gSk8qtrNFhKyXHz9I=
+github.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490/go.mod h1:t3Tmt3DgQx0zqJmrckszJ+JBZ7iJrD1Ktp8FDBQ249E=
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754 h1:6QYpy7s5HlRSge09TyM/mT0vz1RDcWYZdkxEh7hmbH4=
github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754/go.mod h1:/N7+N2CsZ0nleNPpP3b+06Bzqvuhy6GUmLY7Kug/zT0=
github.com/smallnest/chanx v1.2.0 h1:RLyldZBbQZ4O0dSvdkTMHo4+mDw20Bc1jXXTHf+ymZo=
@@ -401,6 +405,10 @@ github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js=
github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
+github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM=
github.com/steambap/captcha v1.4.1 h1:OmMdxLCWCqJvsFaFYwRpvMckIuvI6s8s1LsBrBw97P0=
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 32994704ac..a8114f53b9 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1005,7 +1005,11 @@ func DuplicateDoc(tree *parse.Tree) {
if nil != box {
box.addSort(previousPath, tree.ID)
}
+
FlushTxQueue()
+ arg := map[string]any{}
+ arg["listDocTree"] = true
+ PushCreate(box, tree.Path, arg)
}
func createTreeTx(tree *parse.Tree) {
@@ -1015,7 +1019,7 @@ func createTreeTx(tree *parse.Tree) {
var createDocLock = sync.Mutex{}
-func CreateDocByMd(boxID, p, title, md string, sorts []string) (tree *parse.Tree, err error) {
+func CreateDocByMd(boxID, p, title, md string, sorts []string, arg map[string]any) (tree *parse.Tree, err error) {
createDocLock.Lock()
defer createDocLock.Unlock()
@@ -1038,10 +1042,13 @@ func CreateDocByMd(boxID, p, title, md string, sorts []string) (tree *parse.Tree
} else {
box.setSortByConf(path.Dir(tree.Path), tree.ID)
}
+
+ FlushTxQueue()
+ PushCreate(box, p, arg)
return
}
-func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bool, clippingHref string) (retID string, err error) {
+func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bool, clippingHref string, arg map[string]any) (retID string, err error) {
createDocLock.Lock()
defer createDocLock.Unlock()
@@ -1084,6 +1091,9 @@ func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bo
return
}
box.setSortByConf(path.Dir(bt.Path), retID)
+
+ FlushTxQueue()
+ PushCreate(box, bt.Path, arg)
return
}
diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.go
index 09eca81fdc..e7e54622be 100644
--- a/kernel/model/push_reload.go
+++ b/kernel/model/push_reload.go
@@ -419,3 +419,25 @@ func ReloadAttrView(avID string) {
func pushReloadAttrView(avID string) {
util.BroadcastByType("protyle", "refreshAttributeView", 0, "", map[string]any{"id": avID})
}
+
+func PushCreate(box *Box, p string, arg map[string]any) {
+ evt := util.NewCmdResult("create", 0, util.PushModeBroadcast)
+ listDocTree := false
+ if nil == arg {
+ arg = map[string]any{
+ "listDocTree": true,
+ }
+ }
+
+ listDocTreeArg := arg["listDocTree"]
+ if nil != listDocTreeArg {
+ listDocTree = listDocTreeArg.(bool)
+ }
+
+ evt.Data = map[string]any{
+ "box": box,
+ "path": p,
+ "listDocTree": listDocTree,
+ }
+ util.PushEvent(evt)
+}
diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.go
index fd5d8dd205..eda96be11d 100644
--- a/kernel/model/shortcuts.go
+++ b/kernel/model/shortcuts.go
@@ -115,7 +115,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
}
hPath = "/" + time.UnixMilli(i).Format("2006-01-02 15:04:05")
var retID string
- retID, err = CreateWithMarkdown("", boxID, hPath, content, "", "", false, "")
+ retID, err = CreateWithMarkdown("", boxID, hPath, content, "", "", false, "", nil)
if nil != err {
logging.LogErrorf("create doc failed: %s", err)
return
@@ -157,7 +157,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
bt := treenode.GetBlockTreeRootByHPath(boxID, hPath)
if nil == bt {
var retID string
- retID, err = CreateWithMarkdown("", boxID, hPath, buff.String(), "", "", false, "")
+ retID, err = CreateWithMarkdown("", boxID, hPath, buff.String(), "", "", false, "", nil)
if nil != err {
logging.LogErrorf("create doc failed: %s", err)
return
@@ -200,6 +200,12 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
logging.LogErrorf("remove file [%s] failed: %s", p, removeErr)
}
}
+
+ FlushTxQueue()
+ for _, id := range retIDs {
+ b, _ := GetBlock(id, nil)
+ PushCreate(box, b.Path, nil)
+ }
return
}