跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

yqutil.go

158 行 · 4.7 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package yqutil
5
6import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io"
12 "strings"
13 "sync"
14
15 "github.com/google/yamlfmt"
16 "github.com/google/yamlfmt/formatters/basic"
17 "github.com/mikefarah/yq/v4/pkg/yqlib"
18 "github.com/sirupsen/logrus"
19 logging "gopkg.in/op/go-logging.v1"
20)
21
22// yqlib shares its parser, security preferences and logging backend.
23// Keep validation and evaluation in the same critical section so each call
24// owns both its parser state and the diagnostics captured for that call.
25var operationMu sync.Mutex
26
27// ValidateContent decodes the content yaml, to check it for syntax errors.
28func ValidateContent(content []byte) error {
29 operationMu.Lock()
30 defer operationMu.Unlock()
31
32 memory := logging.NewMemoryBackend(0)
33 backend := logging.AddModuleLevel(memory)
34 logging.SetBackend(backend)
35 yqlib.InitExpressionParser()
36
37 decoder := yqlib.NewYamlDecoder(yqlib.ConfiguredYamlPreferences)
38
39 reader := bytes.NewReader(content)
40 err := decoder.Init(reader)
41 if err != nil {
42 return err
43 }
44 _, err = decoder.Decode()
45 if errors.Is(err, io.EOF) {
46 return nil
47 }
48 return err
49}
50
51// EvaluateExpressionWithEncoder evaluates the yq expression and returns the yq result using a custom encoder.
52func EvaluateExpressionWithEncoder(expression, content string, encoder yqlib.Encoder) (string, error) {
53 if expression == "" {
54 return content, nil
55 }
56 operationMu.Lock()
57 defer operationMu.Unlock()
58
59 logrus.Debugf("Evaluating yq expression: %#q", expression)
60 memory := logging.NewMemoryBackend(0)
61 backend := logging.AddModuleLevel(memory)
62 logging.SetBackend(backend)
63 yqlib.InitExpressionParser()
64
65 // Disable access to environment variables and file loading functions
66 yqlib.ConfiguredSecurityPreferences.DisableEnvOps = true
67 yqlib.ConfiguredSecurityPreferences.DisableFileOps = true
68
69 decoder := yqlib.NewYamlDecoder(yqlib.ConfiguredYamlPreferences)
70 out, err := yqlib.NewStringEvaluator().EvaluateAll(expression, content, encoder, decoder)
71 if err != nil {
72 logger := logrus.StandardLogger()
73 for node := memory.Head(); node != nil; node = node.Next() {
74 entry := logrus.NewEntry(logger).WithTime(node.Record.Time)
75 prefix := fmt.Sprintf("[%s] ", node.Record.Module)
76 message := prefix + node.Record.Message()
77 switch node.Record.Level {
78 case logging.CRITICAL:
79 entry.Fatal(message)
80 case logging.ERROR:
81 entry.Error(message)
82 case logging.WARNING:
83 entry.Warn(message)
84 case logging.NOTICE:
85 entry.Info(message)
86 case logging.INFO:
87 entry.Info(message)
88 case logging.DEBUG:
89 entry.Debug(message)
90 }
91 }
92 return "", err
93 }
94 return out, nil
95}
96
97// EvaluateExpressionPlain evaluates the yq expression and returns the yq result.
98func EvaluateExpressionPlain(expression, content string, colorsEnabled bool) (string, error) {
99 encoderPrefs := yqlib.ConfiguredYamlPreferences.Copy()
100 encoderPrefs.Indent = 2
101 encoderPrefs.ColorsEnabled = colorsEnabled
102 encoder := yqlib.NewYamlEncoder(encoderPrefs)
103 return EvaluateExpressionWithEncoder(expression, content, encoder)
104}
105
106// EvaluateExpression evaluates the yq expression and returns the output formatted with yamlfmt.
107func EvaluateExpression(ctx context.Context, expression string, content []byte) ([]byte, error) {
108 if err := ctx.Err(); err != nil {
109 return nil, err
110 }
111 if expression == "" {
112 return content, nil
113 }
114 formatter, err := yamlfmtBasicFormatter()
115 if err != nil {
116 return nil, err
117 }
118 // `ApplyFeatures()` is being called directly before passing content to `yqlib`.
119 // This results in `ApplyFeatures()` being called twice with `FeatureApplyBefore`:
120 // once here and once inside `formatter.Format`.
121 // Currently, calling `ApplyFeatures()` with `FeatureApplyBefore` twice is not an issue,
122 // but future changes to `yamlfmt` might cause problems if it is called twice.
123 _, contentModified, err := formatter.Features.ApplyFeatures(ctx, content, yamlfmt.FeatureApplyBefore)
124 if err != nil {
125 return nil, err
126 }
127
128 out, err := EvaluateExpressionPlain(expression, string(contentModified), false)
129 if err != nil {
130 return nil, err
131 }
132 return formatter.Format([]byte(out))
133}
134
135func Join(yqExprs []string) string {
136 return strings.Join(yqExprs, " | ")
137}
138
139func yamlfmtBasicFormatter() (*basic.BasicFormatter, error) {
140 factory := basic.BasicFormatterFactory{}
141 config := map[string]any{
142 "indentless_arrays": true,
143 "line_ending": "lf", // prefer LF even on Windows
144 "pad_line_comments": 2,
145 "retain_line_breaks": true,
146 "retain_line_breaks_single": false,
147 }
148
149 formatter, err := factory.NewFormatter(config)
150 if err != nil {
151 return nil, err
152 }
153 basicFormatter, ok := formatter.(*basic.BasicFormatter)
154 if !ok {
155 return nil, fmt.Errorf("unexpected formatter type: %T", formatter)
156 }
157 return basicFormatter, nil
158}