Skip to content

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

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

Daniel30a8ad7258c2
diff --git a/kernel/cli/cmd/asset.go b/kernel/cli/cmd/asset.go
index 06cb605376..5ea2dfeeb5 100644
--- a/kernel/cli/cmd/asset.go
+++ b/kernel/cli/cmd/asset.go
@@ -24,6 +24,7 @@ import (
"text/tabwriter"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
"github.com/spf13/cobra"
)
@@ -140,14 +141,48 @@ var assetCleanCmd = &cobra.Command{
},
}
+var assetStatCmd = &cobra.Command{
+ Use: "stat --path <path>",
+ Short: "Show asset file info",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, _ := cmd.Flags().GetString("path")
+ if p == "" {
+ return fmt.Errorf("--path is required")
+ }
+ abs := filepath.Join(util.DataDir, p)
+ info, err := os.Stat(abs)
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(map[string]any{
+ "path": p,
+ "size": info.Size(),
+ "isDir": info.IsDir(),
+ "modTime": info.ModTime().Format("2006-01-02 15:04:05"),
+ }, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Printf("Path: %s\n", p)
+ fmt.Printf("Size: %d\n", info.Size())
+ fmt.Printf("IsDir: %v\n", info.IsDir())
+ fmt.Printf("ModTime: %s\n", info.ModTime().Format("2006-01-02 15:04:05"))
+ }
+ return nil
+ },
+}
+
func init() {
assetUploadCmd.Flags().String("id", "", "target document block ID")
assetUploadCmd.Flags().StringArray("file", nil, "local file path (repeatable)")
assetCleanCmd.Flags().String("path", "", "single unused asset path to remove")
+ assetStatCmd.Flags().String("path", "", "asset path relative to data dir, e.g. assets/image/xxx.png")
rootCmd.AddCommand(assetCmd)
assetCmd.AddCommand(assetUploadCmd)
assetCmd.AddCommand(assetUnusedCmd)
assetCmd.AddCommand(assetCleanCmd)
+ assetCmd.AddCommand(assetStatCmd)
}
diff --git a/kernel/cli/cmd/block.go b/kernel/cli/cmd/block.go
index a87c545a78..155f135f3b 100644
--- a/kernel/cli/cmd/block.go
+++ b/kernel/cli/cmd/block.go
@@ -21,6 +21,7 @@ import (
"fmt"
"io"
"os"
+ "strings"
"text/tabwriter"
"github.com/siyuan-note/siyuan/kernel/filesys"
@@ -407,6 +408,91 @@ var blockMoveCmd = &cobra.Command{
},
}
+var blockBatchGetCmd = &cobra.Command{
+ Use: "batch-get --ids id1,id2,...",
+ Short: "Batch get block info",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ idsStr, _ := cmd.Flags().GetString("ids")
+ if idsStr == "" {
+ return fmt.Errorf("--ids is required")
+ }
+ ids := splitIDs(idsStr)
+ if len(ids) == 0 {
+ return fmt.Errorf("no valid IDs provided")
+ }
+ infos := model.GetDocsInfo(ids, false, false)
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(infos, "", " ")
+ fmt.Println(string(data))
+ default:
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "ID\tNAME\tROOTID\tREFCOUNT")
+ for _, info := range infos {
+ fmt.Fprintf(w, "%s\t%s\t%s\t%d\n", info.ID, info.Name, info.RootID, info.RefCount)
+ }
+ for _, id := range ids {
+ found := false
+ for _, info := range infos {
+ if info.ID == id {
+ found = true
+ break
+ }
+ }
+ if !found {
+ fmt.Fprintf(w, "%s\tnot found\t\t\n", id)
+ }
+ }
+ w.Flush()
+ }
+ return nil
+ },
+}
+
+var blockBatchKramdownCmd = &cobra.Command{
+ Use: "batch-kramdown --ids id1,id2,...",
+ Short: "Batch get block kramdown",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ idsStr, _ := cmd.Flags().GetString("ids")
+ if idsStr == "" {
+ return fmt.Errorf("--ids is required")
+ }
+ ids := splitIDs(idsStr)
+ if len(ids) == 0 {
+ return fmt.Errorf("no valid IDs provided")
+ }
+ kramdowns := model.GetBlockKramdowns(ids, "md")
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(kramdowns, "", " ")
+ fmt.Println(string(data))
+ default:
+ var sb strings.Builder
+ for _, id := range ids {
+ if kd, ok := kramdowns[id]; ok {
+ sb.WriteString(fmt.Sprintf("--- %s ---\n%s\n\n", id, kd))
+ } else {
+ sb.WriteString(fmt.Sprintf("--- %s ---\n(not found)\n\n", id))
+ }
+ }
+ fmt.Print(sb.String())
+ }
+ return nil
+ },
+}
+
+func splitIDs(s string) []string {
+ parts := strings.Split(s, ",")
+ var ids []string
+ for _, p := range parts {
+ p = strings.TrimSpace(p)
+ if p != "" {
+ ids = append(ids, p)
+ }
+ }
+ return ids
+}
+
func resolveData(cmd *cobra.Command) (string, error) {
data, _ := cmd.Flags().GetString("data")
if data != "" {
@@ -478,6 +564,9 @@ func init() {
blockMoveCmd.Flags().String("parent", "", "target parent block ID")
blockMoveCmd.Flags().String("previous", "", "target previous sibling block ID")
+ blockBatchGetCmd.Flags().String("ids", "", "comma-separated block IDs")
+ blockBatchKramdownCmd.Flags().String("ids", "", "comma-separated block IDs")
+
rootCmd.AddCommand(blockCmd)
blockCmd.AddCommand(blockGetCmd)
blockCmd.AddCommand(blockChildrenCmd)
@@ -491,4 +580,6 @@ func init() {
blockCmd.AddCommand(blockUpdateCmd)
blockCmd.AddCommand(blockDeleteCmd)
blockCmd.AddCommand(blockMoveCmd)
+ blockCmd.AddCommand(blockBatchGetCmd)
+ blockCmd.AddCommand(blockBatchKramdownCmd)
}
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.go
index 951ede64eb..13b892dc5f 100644
--- a/kernel/cli/cmd/document.go
+++ b/kernel/cli/cmd/document.go
@@ -296,6 +296,37 @@ func resolvePath(boxID, userPath, hpath string) string {
return "/"
}
+var documentSearchCmd = &cobra.Command{
+ Use: "search <keyword>",
+ Short: "Search documents by keyword",
+ Args: cobra.MinimumNArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ keyword := args[0]
+ if keyword == "" {
+ return fmt.Errorf("keyword is required")
+ }
+ docs := model.SearchDocs(keyword, false, nil)
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(docs, "", " ")
+ fmt.Println(string(data))
+ default:
+ if len(docs) == 0 {
+ fmt.Println("No documents found.")
+ return nil
+ }
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "NAME\tID\tHPATH")
+ for _, d := range docs {
+ fmt.Fprintf(w, "%s\t%s\t%s\n", d["name"], d["id"], d["hPath"])
+ }
+ w.Flush()
+ fmt.Printf("\n%d document(s)\n", len(docs))
+ }
+ return nil
+ },
+}
+
func printDocumentTable(files []*model.File) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "ID\tNAME\tPATH\tSIZE\tCOUNT\tMTIME")
@@ -337,6 +368,7 @@ func init() {
documentCmd.AddCommand(documentMoveCmd)
documentCmd.AddCommand(documentDuplicateCmd)
documentCmd.AddCommand(documentInfoCmd)
+ documentCmd.AddCommand(documentSearchCmd)
}
diff --git a/kernel/cli/cmd/file.go b/kernel/cli/cmd/file.go
index cfcd1ea837..58888a9bde 100644
--- a/kernel/cli/cmd/file.go
+++ b/kernel/cli/cmd/file.go
@@ -17,6 +17,7 @@
package cmd
import (
+ "encoding/json"
"fmt"
"io"
"os"
@@ -265,9 +266,194 @@ func copyFile(src, dst string) error {
return err
}
+var fileGrepCmd = &cobra.Command{
+ Use: "grep --pattern <regex> --path <path>",
+ Short: "Search file contents with regex",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ pattern, _ := cmd.Flags().GetString("pattern")
+ if pattern == "" {
+ return fmt.Errorf("--pattern is required")
+ }
+ relPath, _ := cmd.Flags().GetString("path")
+ if relPath == "" {
+ return fmt.Errorf("--path is required")
+ }
+ abs, err := absPath(relPath)
+ if err != nil {
+ return err
+ }
+ include, _ := cmd.Flags().GetString("include")
+ ctx, _ := cmd.Flags().GetInt("context")
+ max, _ := cmd.Flags().GetInt("limit")
+ if max <= 0 {
+ max = 200
+ }
+ results, err := gulu.File.Grep(abs, include, pattern, ctx, max)
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(results, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Printf("Found %d lines:\n\n", len(results))
+ for _, r := range results {
+ rel, relErr := filepath.Rel(util.WorkspaceDir, r.File)
+ if relErr != nil {
+ rel = r.File
+ }
+ sep := ":"
+ if r.Context {
+ sep = "-:"
+ }
+ fmt.Printf("%s:%d%s %s\n", rel, r.Line, sep, r.Text)
+ }
+ }
+ return nil
+ },
+}
+
+var fileFindCmd = &cobra.Command{
+ Use: "find <path>",
+ Short: "Find files under a path",
+ Args: cobra.MinimumNArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ abs, err := absPath(args[0])
+ if err != nil {
+ return err
+ }
+ include, _ := cmd.Flags().GetString("include")
+ max, _ := cmd.Flags().GetInt("limit")
+ if max <= 0 {
+ max = 200
+ }
+ var results []string
+ total := 0
+ err = filepath.WalkDir(abs, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ if d.IsDir() {
+ name := d.Name()
+ if name == ".git" || name == ".svn" || name == ".hg" || strings.HasPrefix(name, ".") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !d.Type().IsRegular() {
+ return nil
+ }
+ if include != "" && !matchGlob(d.Name(), include) {
+ return nil
+ }
+ total++
+ if len(results) < max {
+ rel, relErr := filepath.Rel(util.WorkspaceDir, path)
+ if relErr != nil {
+ rel = path
+ }
+ results = append(results, rel)
+ }
+ if total >= max {
+ return filepath.SkipAll
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(results, "", " ")
+ fmt.Println(string(data))
+ default:
+ if max < total {
+ fmt.Printf("Found %d files (showing first %d):\n\n", total, max)
+ } else {
+ fmt.Printf("Found %d files:\n\n", len(results))
+ }
+ for _, r := range results {
+ fmt.Println(r)
+ }
+ }
+ return nil
+ },
+}
+
+var fileStatCmd = &cobra.Command{
+ Use: "stat <path>",
+ Short: "Show file or directory info",
+ Args: cobra.MinimumNArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ abs, err := absPath(args[0])
+ if err != nil {
+ return err
+ }
+ info, err := os.Stat(abs)
+ if err != nil {
+ return err
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(map[string]any{
+ "path": args[0],
+ "size": info.Size(),
+ "isDir": info.IsDir(),
+ "modTime": info.ModTime().Format("2006-01-02 15:04:05"),
+ }, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Printf("Path: %s\n", args[0])
+ fmt.Printf("Size: %d\n", info.Size())
+ fmt.Printf("IsDir: %v\n", info.IsDir())
+ fmt.Printf("ModTime: %s\n", info.ModTime().Format("2006-01-02 15:04:05"))
+ }
+ return nil
+ },
+}
+
+func matchGlob(filename, pattern string) bool {
+ for _, p := range expandGlobBrace(pattern) {
+ if matched, _ := filepath.Match(p, filename); matched {
+ return true
+ }
+ }
+ return false
+}
+
+func expandGlobBrace(pattern string) []string {
+ i := strings.Index(pattern, "{")
+ if i < 0 {
+ return []string{pattern}
+ }
+ j := strings.Index(pattern[i:], "}")
+ if j < 0 {
+ return []string{pattern}
+ }
+ j += i
+ prefix := pattern[:i]
+ body := pattern[i+1 : j]
+ suffix := pattern[j+1:]
+ var result []string
+ for _, opt := range strings.Split(body, ",") {
+ result = append(result, expandGlobBrace(prefix+strings.TrimSpace(opt)+suffix)...)
+ }
+ return result
+}
+
func init() {
fileWriteCmd.Flags().String("file", "", "source file path (default: stdin)")
+ fileGrepCmd.Flags().String("pattern", "", "regex pattern")
+ fileGrepCmd.Flags().String("path", "", "relative path within workspace")
+ fileGrepCmd.Flags().String("include", "", "file glob filter, e.g. *.go or *.{ts,tsx}")
+ fileGrepCmd.Flags().Int("context", 0, "context lines before and after each match")
+ fileGrepCmd.Flags().Int("limit", 200, "maximum matches (0 or negative for unlimited)")
+
+ fileFindCmd.Flags().String("include", "", "file glob filter, e.g. *.go or *.{ts,tsx}")
+ fileFindCmd.Flags().Int("limit", 200, "maximum files (0 or negative for unlimited)")
+
rootCmd.AddCommand(fileCmd)
fileCmd.AddCommand(fileListCmd)
fileCmd.AddCommand(fileReadCmd)
@@ -275,4 +461,7 @@ func init() {
fileCmd.AddCommand(fileDeleteCmd)
fileCmd.AddCommand(fileRenameCmd)
fileCmd.AddCommand(fileCopyCmd)
+ fileCmd.AddCommand(fileGrepCmd)
+ fileCmd.AddCommand(fileFindCmd)
+ fileCmd.AddCommand(fileStatCmd)
}
diff --git a/kernel/cli/cmd/outline.go b/kernel/cli/cmd/outline.go
new file mode 100644
index 0000000000..dc5b061814
--- /dev/null
+++ b/kernel/cli/cmd/outline.go
@@ -0,0 +1,111 @@
+// 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"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+
+ "github.com/spf13/cobra"
+)
+
+var outlineCmd = &cobra.Command{
+ Use: "outline",
+ Short: "Document outline (heading tree)",
+}
+
+var outlineGetCmd = &cobra.Command{
+ Use: "get --id <id>",
+ Short: "Get document outline",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ id, _ := cmd.Flags().GetString("id")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ paths, err := model.Outline(id, false)
+ if err != nil {
+ return err
+ }
+ if len(paths) == 0 {
+ return fmt.Errorf("document not found or has no headings")
+ }
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(paths, "", " ")
+ fmt.Println(string(data))
+ default:
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("Document outline (%d headings):\n\n", countOutlineHeadings(paths)))
+ for _, p := range paths {
+ writeOutlinePath(&sb, p, 0)
+ }
+ fmt.Print(sb.String())
+ }
+ return nil
+ },
+}
+
+func countOutlineHeadings(paths []*model.Path) int {
+ n := 0
+ for _, p := range paths {
+ n++
+ for _, b := range p.Blocks {
+ n++
+ n += countOutlineBlockChildren(b)
+ }
+ n += countOutlineHeadings(p.Children)
+ }
+ return n
+}
+
+func countOutlineBlockChildren(b *model.Block) int {
+ n := 0
+ for _, c := range b.Children {
+ n++
+ n += countOutlineBlockChildren(c)
+ }
+ return n
+}
+
+func writeOutlinePath(sb *strings.Builder, p *model.Path, depth int) {
+ prefix := strings.Repeat(" ", depth)
+ sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, p.Name, p.ID, p.Depth))
+ for _, b := range p.Blocks {
+ writeOutlineBlock(sb, b, depth+1)
+ }
+ for _, c := range p.Children {
+ writeOutlinePath(sb, c, depth+1)
+ }
+}
+
+func writeOutlineBlock(sb *strings.Builder, b *model.Block, depth int) {
+ prefix := strings.Repeat(" ", depth)
+ sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, b.Content, b.ID, b.Depth))
+ for _, c := range b.Children {
+ writeOutlineBlock(sb, c, depth+1)
+ }
+}
+
+func init() {
+ outlineGetCmd.Flags().String("id", "", "document block ID")
+
+ rootCmd.AddCommand(outlineCmd)
+ outlineCmd.AddCommand(outlineGetCmd)
+}
diff --git a/kernel/cli/cmd/system.go b/kernel/cli/cmd/system.go
new file mode 100644
index 0000000000..9f4a5a7127
--- /dev/null
+++ b/kernel/cli/cmd/system.go
@@ -0,0 +1,53 @@
+// 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"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+
+ "github.com/spf13/cobra"
+)
+
+var systemCmd = &cobra.Command{
+ Use: "system",
+ Short: "System information",
+}
+
+var systemCurrentTimeCmd = &cobra.Command{
+ Use: "current-time",
+ Short: "Show current server time",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ t := time.UnixMilli(util.CurrentTimeMillis())
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(map[string]string{"time": t.Format(time.RFC3339)}, "", " ")
+ fmt.Println(string(data))
+ default:
+ fmt.Println(t.Format(time.RFC3339))
+ }
+ return nil
+ },
+}
+
+func init() {
+ rootCmd.AddCommand(systemCmd)
+ systemCmd.AddCommand(systemCurrentTimeCmd)
+}
diff --git a/kernel/cli/cmd/template.go b/kernel/cli/cmd/template.go
new file mode 100644
index 0000000000..864d6f18a7
--- /dev/null
+++ b/kernel/cli/cmd/template.go
@@ -0,0 +1,227 @@
+// 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"
+ "path/filepath"
+ "strings"
+ "text/tabwriter"
+
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+
+ "github.com/spf13/cobra"
+)
+
+var templateCmd = &cobra.Command{
+ Use: "template",
+ Short: "Manage templates",
+}
+
+var templateSearchCmd = &cobra.Command{
+ Use: "search [keyword]",
+ Short: "Search templates (empty keyword lists all)",
+ Args: cobra.MaximumNArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ keyword := ""
+ if len(args) > 0 {
+ keyword = args[0]
+ }
+ results := model.SearchTemplate(keyword)
+ switch outputFormat {
+ case "json":
+ data, _ := json.MarshalIndent(results, "", " ")
+ fmt.Println(string(data))
+ default:
+ if len(results) == 0 {
+ fmt.Println("No templates found.")
+ return nil
+ }
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "NAME\tPATH")
+ for _, r := range results {
+ fmt.Fprintf(w, "%s\t%s\n", r.Content, r.Path)
+ }
+ w.Flush()
+ fmt.Printf("\n%d template(s)\n", len(results))
+ }
+ return nil
+ },
+}
+
+var templateGetCmd = &cobra.Command{
+ Use: "get --path <path>",
+ Short: "Read template content",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, _ := cmd.Flags().GetString("path")
+ abs, err := resolveTemplateAbs(p)
+ if err != nil {
+ return err
+ }
+ data, err := os.ReadFile(abs)
+ if err != nil {
+ return err
+ }
+ fmt.Print(string(data))
+ return nil
+ },
+}
+
+var templateRemoveCmd = &cobra.Command{
+ Use: "remove --path <path>",
+ Short: "Remove a template",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, _ := cmd.Flags().GetString("path")
+ abs, err := resolveTemplateAbs(p)
+ if err != nil {
+ return err
+ }
+ if dryRun {
+ fmt.Printf("[dry-run] Would remove template: %s\n", p)
+ return nil
+ }
+ if err := model.RemoveTemplate(abs); err != nil {
+ return err
+ }
+ fmt.Println("ok")
+ return nil
+ },
+}
+
+var templateRenderCmd = &cobra.Command{
+ Use: "render --path <path> --id <id>",
+ Short: "Render a template against a block (preview)",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ p, _ := cmd.Flags().GetString("path")
+ id, _ := cmd.Flags().GetString("id")
+ if id == "" {
+ return fmt.Errorf("--id is required")
+ }
+ abs, err := resolveTemplateAbs(p)
+ if err != nil {
+ return err
+ }
+ _, dom, err := model.RenderTemplate(abs, id, true)
+ if err != nil {
+ return err
+ }
+ fmt.Print(dom)
+ return nil
+ },
+}
+
+var templateSaveAsCmd = &cobra.Command{
+ Use: "save-as --id <id> --name <name>",
+ Short: "Save a document as a template",
+ 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")
+ }
+ overwrite, _ := cmd.Flags().GetBool("overwrite")
+ if dryRun {
+ fmt.Printf("[dry-run] Would save document %s as template \"%s\"\n", id, name)
+ return nil
+ }
+ code, err := model.DocSaveAsTemplate(id, name, overwrite)
+ if err != nil {
+ return err
+ }
+ if code == 1 {
+ return fmt.Errorf("template already exists, use --overwrite to replace: %s", name)
+ }
+ fmt.Printf("%s.md\n", name)
+ return nil
+ },
+}
+
+var templateCreateCmd = &cobra.Command{
+ Use: "create --name <name> [--data <markdown> | --file <path>]",
+ Short: "Create a template from markdown content",
+ RunE: func(cmd *cobra.Command, args []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ content, err := resolveData(cmd)
+ if err != nil {
+ return err
+ }
+ overwrite, _ := cmd.Flags().GetBool("overwrite")
+ if dryRun {
+ fmt.Printf("[dry-run] Would create template \"%s\"\n", name)
+ return nil
+ }
+ code, err := model.CreateTemplate(name, content, overwrite)
+ if err != nil {
+ return err
+ }
+ if code == 1 {
+ return fmt.Errorf("template already exists, use --overwrite to replace: %s", name)
+ }
+ fmt.Printf("%s.md\n", name)
+ return nil
+ },
+}
+
+// resolveTemplateAbs 把模板路径解析为 data/templates 下的绝对路径,拒绝越界。
+// 接受绝对路径或相对 data/templates 的相对路径。
+func resolveTemplateAbs(p string) (string, error) {
+ if p == "" {
+ return "", fmt.Errorf("--path is required")
+ }
+ abs := p
+ if !filepath.IsAbs(abs) {
+ abs = filepath.Join(util.DataDir, "templates", p)
+ }
+ abs = filepath.Clean(abs)
+ templatesBase := filepath.Clean(filepath.Join(util.DataDir, "templates"))
+ rel, err := filepath.Rel(templatesBase, abs)
+ if err != nil || strings.HasPrefix(rel, "..") || rel == ".." {
+ return "", fmt.Errorf("path escapes templates dir: %s", p)
+ }
+ return abs, nil
+}
+
+func init() {
+ templateGetCmd.Flags().String("path", "", "template path (absolute or relative to data/templates)")
+ templateRemoveCmd.Flags().String("path", "", "template path (absolute or relative to data/templates)")
+ templateRenderCmd.Flags().String("path", "", "template path (absolute or relative to data/templates)")
+ templateRenderCmd.Flags().String("id", "", "block ID to render against")
+ templateSaveAsCmd.Flags().String("id", "", "source document block ID")
+ templateSaveAsCmd.Flags().String("name", "", "template name without extension")
+ templateSaveAsCmd.Flags().Bool("overwrite", false, "overwrite if exists")
+ templateCreateCmd.Flags().String("name", "", "template name without extension")
+ templateCreateCmd.Flags().String("data", "", "markdown content")
+ templateCreateCmd.Flags().String("file", "", "read content from file path (- for stdin)")
+ templateCreateCmd.Flags().Bool("overwrite", false, "overwrite if exists")
+
+ rootCmd.AddCommand(templateCmd)
+ templateCmd.AddCommand(templateSearchCmd)
+ templateCmd.AddCommand(templateGetCmd)
+ templateCmd.AddCommand(templateRemoveCmd)
+ templateCmd.AddCommand(templateRenderCmd)
+ templateCmd.AddCommand(templateSaveAsCmd)
+ templateCmd.AddCommand(templateCreateCmd)
+}