跳到主要内容

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

浏览文件

embed.go

682 行 · 24.5 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limatmpl
5
6import (
7 "bytes"
8 "context"
9 "encoding/base64"
10 "fmt"
11 "os"
12 "path/filepath"
13 "slices"
14 "strings"
15 "sync"
16 "unicode"
17
18 "github.com/coreos/go-semver/semver"
19 "github.com/sirupsen/logrus"
20
21 "github.com/lima-vm/lima/v2/pkg/limatype"
22 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
23 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
24 "github.com/lima-vm/lima/v2/pkg/limayaml"
25 "github.com/lima-vm/lima/v2/pkg/version/versionutil"
26 "github.com/lima-vm/lima/v2/pkg/yqutil"
27)
28
29// Embed will recursively resolve all "base" dependencies and update the
30// template with the merged result. It also inlines all external provisioning
31// and probe scripts.
32func (tmpl *Template) Embed(ctx context.Context, embedAll, defaultBase bool) error {
33 if err := tmpl.UseAbsLocators(ctx); err != nil {
34 return err
35 }
36 seen := make(map[string]bool)
37 err := tmpl.embedAllBases(ctx, embedAll, defaultBase, seen)
38 // additionalDisks, mounts, and networks may combine entries based on a shared key
39 // This must be done after **all** base templates have been merged, so that wildcard keys can match
40 // against all earlier list entries, and not just against the direct parent template.
41 if err == nil {
42 err = tmpl.combineListEntries(ctx)
43 }
44 return tmpl.ClearOnError(err)
45}
46
47func (tmpl *Template) embedAllBases(ctx context.Context, embedAll, defaultBase bool, seen map[string]bool) error {
48 logrus.Debugf("Embedding templates into %#q", tmpl.Locator)
49 if defaultBase {
50 configDir, err := dirnames.LimaConfigDir()
51 if err != nil {
52 return err
53 }
54 defaultBaseFilename := filepath.Join(configDir, filenames.Base)
55 if _, err := os.Stat(defaultBaseFilename); err == nil {
56 // turn string into single element list
57 // empty concatenation works around bug https://github.com/mikefarah/yq/issues/2269
58 tmpl.expr.WriteString("| ($a.base | select(type == \"!!str\")) |= [\"\" + .]\n")
59 tmpl.expr.WriteString("| ($a.base | select(type == \"!!map\")) |= [[] + .]\n")
60 // prepend base template at the beginning of the list
61 fmt.Fprintf(&tmpl.expr, "| $a.base = [%q, $a.base[]]\n", defaultBaseFilename)
62 if err := tmpl.evalExpr(ctx); err != nil {
63 return err
64 }
65 }
66 }
67 for {
68 if err := tmpl.Unmarshal(); err != nil {
69 return err
70 }
71 if len(tmpl.Config.Base) == 0 {
72 break
73 }
74 baseLocator := tmpl.Config.Base[0]
75 if baseLocator.Digest != nil {
76 return fmt.Errorf("base %#q in %#q has specified a digest; digest support is not yet implemented", baseLocator.URL, tmpl.Locator)
77 }
78 isTemplate, _ := SeemsTemplateURL(baseLocator.URL)
79 if isTemplate && !embedAll {
80 // Once we skip a template: URL we can no longer embed any other base template
81 for i := 1; i < len(tmpl.Config.Base); i++ {
82 isTemplate, _ = SeemsTemplateURL(tmpl.Config.Base[i].URL)
83 if !isTemplate {
84 return fmt.Errorf("cannot embed template %#q after not embedding %#q", tmpl.Config.Base[i].URL, baseLocator.URL)
85 }
86 }
87 break
88 // TODO should we track embedding of template: URLs so we can warn if we embed a non-template: URL afterwards?
89 }
90
91 if seen[baseLocator.URL] {
92 return fmt.Errorf("base template loop detected: template %#q already included", baseLocator.URL)
93 }
94 seen[baseLocator.URL] = true
95
96 // remove base[0] from template before merging
97 if err := tmpl.embedBase(ctx, baseLocator, embedAll, seen); err != nil {
98 return err
99 }
100 }
101 if err := tmpl.embedAllScripts(ctx, embedAll); err != nil {
102 return err
103 }
104 if len(tmpl.Bytes) > yBytesLimit {
105 return fmt.Errorf("template %#q embedding exceeded the size limit (%d bytes)", tmpl.Locator, yBytesLimit)
106 }
107 return nil
108}
109
110func (tmpl *Template) embedBase(ctx context.Context, baseLocator limatype.LocatorWithDigest, embedAll bool, seen map[string]bool) error {
111 logrus.Debugf("Embedding base %#q in template %#q", baseLocator.URL, tmpl.Locator)
112 if err := tmpl.Unmarshal(); err != nil {
113 return err
114 }
115 base, err := Read(ctx, "", baseLocator.URL)
116 if err != nil {
117 return err
118 }
119 if err := base.UseAbsLocators(ctx); err != nil {
120 return err
121 }
122 if err := base.embedAllBases(ctx, embedAll, false, seen); err != nil {
123 return err
124 }
125 if err := tmpl.merge(ctx, base); err != nil {
126 return err
127 }
128 if len(tmpl.Bytes) > yBytesLimit {
129 return fmt.Errorf("template %#q embedding exceeded the size limit (%d bytes)", tmpl.Locator, yBytesLimit)
130 }
131 return nil
132}
133
134// evalExprImpl evaluates tmpl.expr against one or more documents.
135// Called by evalExpr() and embedAllScripts() for single documents and merge() for 2 documents.
136func (tmpl *Template) evalExprImpl(ctx context.Context, prefix string, b []byte) error {
137 var err error
138 expr := prefix + tmpl.expr.String() + "| $a"
139 tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, expr, b)
140 // Make sure the YAML ends with just a single newline
141 tmpl.Bytes = append(bytes.TrimRight(tmpl.Bytes, "\n"), '\n')
142 tmpl.Config = nil
143 tmpl.expr.Reset()
144 return tmpl.ClearOnError(err)
145}
146
147// evalExpr evaluates tmpl.expr against the tmpl.Bytes document.
148func (tmpl *Template) evalExpr(ctx context.Context) error {
149 var err error
150 if tmpl.expr.Len() > 0 {
151 // There is just a single document; $a and $b are the same
152 singleDocument := "select(document_index == 0) as $a | $a as $b\n"
153 err = tmpl.evalExprImpl(ctx, singleDocument, tmpl.Bytes)
154 }
155 return err
156}
157
158// merge merges the base template into tmpl.
159func (tmpl *Template) merge(ctx context.Context, base *Template) error {
160 if err := tmpl.mergeBase(base); err != nil {
161 return tmpl.ClearOnError(err)
162 }
163 documents := fmt.Sprintf("%s\n---\n%s", string(tmpl.Bytes), string(base.Bytes))
164 return tmpl.evalExprImpl(ctx, mergeDocuments, []byte(documents))
165}
166
167// mergeBase generates a yq script to merge the template with a base.
168// Most of the merging is done generically by the mergeDocuments script below.
169// Only thing left is to compare minimum version numbers and keep the highest version.
170func (tmpl *Template) mergeBase(base *Template) error {
171 if err := tmpl.Unmarshal(); err != nil {
172 return err
173 }
174 if err := base.Unmarshal(); err != nil {
175 return err
176 }
177 if tmpl.Config.MinimumLimaVersion != nil && base.Config.MinimumLimaVersion != nil {
178 if versionutil.GreaterThan(*base.Config.MinimumLimaVersion, *tmpl.Config.MinimumLimaVersion) {
179 const minimumLimaVersion = "minimumLimaVersion"
180 tmpl.copyField(minimumLimaVersion, minimumLimaVersion)
181 }
182 }
183 var tmplOpts limatype.QEMUOpts
184 if err := limayaml.Convert(tmpl.Config.VMOpts[limatype.QEMU], &tmplOpts, "vmOpts.qemu"); err != nil {
185 return err
186 }
187 var baseOpts limatype.QEMUOpts
188 if err := limayaml.Convert(base.Config.VMOpts[limatype.QEMU], &baseOpts, "vmOpts.qemu"); err != nil {
189 return err
190 }
191 if tmplOpts.MinimumVersion != nil && baseOpts.MinimumVersion != nil {
192 tmplVersion := *semver.New(*tmplOpts.MinimumVersion)
193 baseVersion := *semver.New(*baseOpts.MinimumVersion)
194 if tmplVersion.LessThan(baseVersion) {
195 const minimumQEMUVersion = "vmOpts.qemu.minimumVersion"
196 tmpl.copyField(minimumQEMUVersion, minimumQEMUVersion)
197 }
198 }
199 return nil
200}
201
202// mergeDocuments copies over settings from the base that don't yet exist
203// in the template, and to append lists from the base to template lists.
204// Both head and line comments are copied over as well.
205//
206// It also handles these special cases:
207// * dns lists are not merged and only copied when the template doesn't have any dns entries at all.
208// * probes and provision scripts are appended in reverse order.
209// * mountTypesUnsupported have duplicate values removed.
210// * base is removed from the template.
211const mergeDocuments = `
212 select(document_index == 0) as $a
213| select(document_index == 1) as $b
214
215# $c will be mutilated to implement our own "merge only new fields" logic.
216| $b as $c
217
218# Delete the base that is being merged right now
219| $a | select(.base | tag == "!!seq") | del(.base[0])
220| $a | select(.base | (tag == "!!seq" and length == 0)) | del(.base)
221| $a | select(.base | tag == "!!str") | del(.base)
222
223# If $a.base is a list, then $b.base must be a list as well
224# (note $b, not $c, because we merge lists from $b)
225| $b | select((.base | tag == "!!str") and ($a.base | tag == "!!seq")) | .base = [ "" + .base ]
226
227# Delete base DNS entries if the template list is not empty.
228| $b | select($a.dns | length > 0) | del(.dns)
229| $c | select($a.dns | length > 0) | del(.dns)
230
231# Mark all new list fields with a custom tag. This is needed to avoid appending
232# newly copied lists to themselves again when we merge lists.
233| $c | .. | select(tag == "!!seq") tag = "!!tag"
234
235# Delete all nodes in $c that are in $a and not a map. This is necessary because
236# the yq "*n" operator (merge only new fields) does not copy all comments across.
237| $c | delpaths([$a | .. | select(tag != "!!map") | path])
238
239# Merging with null returns null; use an empty map if $c has only comments
240| $a * ($c // {}) as $a
241
242# Find all elements that are existing lists. This will not match newly
243# copied lists because they have a custom !!tag instead of !!seq.
244# Append the elements from the same path in $b.
245# Exception: base templates, provision scripts and probes are prepended instead.
246| $a | (.. | select(tag == "!!seq" and (path[0] | test("^(base|provision|probes)$") | not))) |=
247 (. + (path[] as $p ireduce ($b; .[$p])))
248| $a | (.. | select(tag == "!!seq" and (path[0] | test("^(base|provision|probes)$")))) |=
249 ((path[] as $p ireduce ($b; .[$p])) + .)
250
251# Copy head and line comments for existing lists that do not already have comments.
252# New lists and existing maps already have their comments updated by the $a * $c merge.
253| $a | (.. | select(tag == "!!seq" and (key | head_comment == "")) | key) head_comment |=
254 (((path[] as $p ireduce ($b; .[$p])) | key | head_comment) // "")
255| $a | (.. | select(tag == "!!seq" and (key | line_comment == "")) | key) line_comment |=
256 (((path[] as $p ireduce ($b; .[$p])) | key | line_comment) // "")
257
258# Make sure mountTypesUnsupported elements are unique.
259| $a | (select(.mountTypesUnsupported) | .mountTypesUnsupported) |= unique
260
261# Remove the custom tags again so they do not clutter up the YAML output.
262| $a | .. | select(tag == "!!tag") tag = ""
263`
264
265// listFields returns dst and src fields like "list[idx].field".
266func listFields(list string, dstIdx, srcIdx int, field string) (dst, src string) {
267 dst = fmt.Sprintf("%s[%d]", list, dstIdx)
268 src = fmt.Sprintf("%s[%d]", list, srcIdx)
269 if field != "" {
270 dst += "." + field
271 src += "." + field
272 }
273 return dst, src
274}
275
276// copyField copies value and comments from $b.src to $a.dst.
277func (tmpl *Template) copyField(dst, src string) {
278 fmt.Fprintf(&tmpl.expr, "| ($a.%s) = $b.%s\n", dst, src)
279 // The head_comment is on the key and not the value, so needs to be copied explicitly.
280 // Surprisingly the line_comment seems to be copied with the value already even though it is also on the key.
281 fmt.Fprintf(&tmpl.expr, "| ($a.%s | key) head_comment = ($b.%s | key | head_comment)\n", dst, src)
282}
283
284// copyListEntryField copies $b.list[srcIdx].field to $a.list[dstIdx].field (including comments).
285// Note: field must not be "" and must not be a list field itself either.
286func (tmpl *Template) copyListEntryField(list string, dstIdx, srcIdx int, field string) {
287 tmpl.copyField(listFields(list, dstIdx, srcIdx, field))
288}
289
290type commentType string
291
292const (
293 headComment commentType = "head"
294 lineComment commentType = "line"
295)
296
297// copyComment copies a non-empty head or line comment from $b.src to $a.dst, but only if $a.dst already exists.
298func (tmpl *Template) copyComment(dst, src string, commentType commentType, isMapElement bool) {
299 onKey := ""
300 if isMapElement {
301 onKey = " | key" // For map elements the comments are on the keys and not the values.
302 }
303 // The expression is careful not to create a null $a.dst entry if $b.src has no comments and $a.dst didn't already exist.
304 // e.g.: `| $a | (select(.foo) | .foo | key | select(head_comment == "" and ($b.bar | key | head_comment != ""))) head_comment |= ($b.bar | key | head_comment)`
305 fmt.Fprintf(&tmpl.expr, "| $a | (select(.%s) | .%s%s | select(%s_comment == \"\" and ($b.%s%s | %s_comment != \"\"))) %s_comment |= ($b.%s%s | %s_comment)\n",
306 dst, dst, onKey, commentType, src, onKey, commentType, commentType, src, onKey, commentType)
307}
308
309// copyComments copies all non-empty comments from $b.src to $a.dst.
310func (tmpl *Template) copyComments(dst, src string, isMapElement bool) {
311 for _, commentType := range []commentType{headComment, lineComment} {
312 tmpl.copyComment(dst, src, commentType, isMapElement)
313 }
314}
315
316// copyListEntryComments copies all non-empty comments from $b.list[srcIdx].field to $a.list[dstIdx].field.
317func (tmpl *Template) copyListEntryComments(list string, dstIdx, srcIdx int, field string) {
318 dst, src := listFields(list, dstIdx, srcIdx, field)
319 isMapElement := field != ""
320 tmpl.copyComments(dst, src, isMapElement)
321}
322
323func (tmpl *Template) deleteListEntry(list string, idx int) {
324 fmt.Fprintf(&tmpl.expr, "| del($a.%s[%d], $b.%s[%d])\n", list, idx, list, idx)
325}
326
327// upgradeListEntryStringToMapField turns list[idx] from a string to a {field: list[idx]} map.
328func (tmpl *Template) upgradeListEntryStringToMapField(list string, idx int, field string) {
329 // TODO the head_comment on the string becomes duplicated as a foot_comment on the new field; could be a yq bug?
330 fmt.Fprintf(&tmpl.expr, "| ($a.%s[%d] | select(type == \"!!str\")) |= {\"%s\": .}\n", list, idx, field)
331}
332
333// combineListEntries combines entries based on a shared unique key.
334// If two entries share the same key, then any missing fields in the earlier entry are
335// filled in from the latter one. The latter one is then deleted.
336//
337// Notes:
338// * The field order is not maintained when entries with a matching key are merged.
339// * The unique keys (and mount locations) are assumed to not be subject to Go templating.
340// * A wildcard key '*' matches all prior list entries.
341func (tmpl *Template) combineListEntries(ctx context.Context) error {
342 if err := tmpl.Unmarshal(); err != nil {
343 return err
344 }
345
346 tmpl.combineAdditionalDisks()
347 tmpl.combineMounts()
348 tmpl.combineNetworks()
349
350 return tmpl.evalExpr(ctx)
351}
352
353// TODO: Maybe instead of hard-coding all the yaml names of LimaYAML struct fields we should
354// TODO: retrieve them using reflection from the Go type tags to avoid possible typos.
355
356// combineAdditionalDisks combines additionalDisks entries. The shared key is the disk name.
357func (tmpl *Template) combineAdditionalDisks() {
358 const additionalDisks = "additionalDisks"
359
360 diskIdx := make(map[string]int, len(tmpl.Config.AdditionalDisks))
361 for src := 0; src < len(tmpl.Config.AdditionalDisks); {
362 disk := tmpl.Config.AdditionalDisks[src]
363 var from, to int
364 if disk.Name == "*" {
365 // copy to **all** previous entries
366 from = 0
367 to = src - 1
368 } else {
369 if i, ok := diskIdx[disk.Name]; ok {
370 // copy to previous disk with the same diskIdx
371 from = i
372 to = i
373 } else {
374 // record disk index and continue with the next entry
375 if disk.Name != "" {
376 diskIdx[disk.Name] = src
377 }
378 src++
379 continue
380 }
381 }
382 for dst := from; dst <= to; dst++ {
383 // upgrade additionalDisks[dst] from "disk" name string to {"name": "disk"} map so we can add fields
384 upgradeDiskToMap := sync.OnceFunc(func() {
385 tmpl.upgradeListEntryStringToMapField(additionalDisks, dst, "name")
386 })
387
388 dest := &tmpl.Config.AdditionalDisks[dst]
389 if dest.Format == nil && disk.Format != nil {
390 upgradeDiskToMap()
391 tmpl.copyListEntryField(additionalDisks, dst, src, "format")
392 dest.Format = disk.Format
393 }
394 // TODO: Does it make sense to merge "fsType" and "fsArgs" independently of each other?
395 if dest.FSType == nil && disk.FSType != nil {
396 upgradeDiskToMap()
397 tmpl.copyListEntryField(additionalDisks, dst, src, "fsType")
398 dest.FSType = disk.FSType
399 }
400 // "fsArgs" are inherited all-or-nothing; they are not appended
401 if len(dest.FSArgs) == 0 && len(disk.FSArgs) != 0 {
402 upgradeDiskToMap()
403 tmpl.copyListEntryField(additionalDisks, dst, src, "fsArgs")
404 dest.FSArgs = disk.FSArgs
405 }
406 // TODO: Is there a good reason not to copy comments from wildcard entries?
407 if disk.Name != "*" {
408 tmpl.copyListEntryComments(additionalDisks, dst, src, "")
409 }
410 }
411 tmpl.Config.AdditionalDisks = slices.Delete(tmpl.Config.AdditionalDisks, src, src+1)
412 tmpl.deleteListEntry(additionalDisks, src)
413 }
414}
415
416// combineMounts combines mounts entries. The shared key is the mount point.
417func (tmpl *Template) combineMounts() {
418 const mounts = "mounts"
419
420 mountPointIdx := make(map[string]int, len(tmpl.Config.Mounts))
421 for src := 0; src < len(tmpl.Config.Mounts); {
422 mount := tmpl.Config.Mounts[src]
423 // mountPoint (an optional field) defaults to location (a required field)
424 mountPoint := mount.Location
425 if mount.MountPoint != nil {
426 mountPoint = *mount.MountPoint
427 }
428 var from, to int
429 if mountPoint == "*" {
430 from = 0
431 to = src - 1
432 } else {
433 if i, ok := mountPointIdx[mountPoint]; ok {
434 from = i
435 to = i
436 } else {
437 if mountPoint != "" {
438 mountPointIdx[mountPoint] = src
439 }
440 src++
441 continue
442 }
443 }
444 for dst := from; dst <= to; dst++ {
445 dest := &tmpl.Config.Mounts[dst]
446 // MountPoint
447 if dest.MountPoint == nil && mount.MountPoint != nil {
448 tmpl.copyListEntryField(mounts, dst, src, "mountPoint")
449 dest.MountPoint = mount.MountPoint
450 }
451 // Writable
452 if dest.Writable == nil && mount.Writable != nil {
453 tmpl.copyListEntryField(mounts, dst, src, "writable")
454 dest.Writable = mount.Writable
455 }
456 // SSHFS
457 if dest.SSHFS.Cache == nil && mount.SSHFS.Cache != nil {
458 tmpl.copyListEntryField(mounts, dst, src, "sshfs.cache")
459 dest.SSHFS.Cache = mount.SSHFS.Cache
460 }
461 if dest.SSHFS.FollowSymlinks == nil && mount.SSHFS.FollowSymlinks != nil {
462 tmpl.copyListEntryField(mounts, dst, src, "sshfs.followSymlinks")
463 dest.SSHFS.FollowSymlinks = mount.SSHFS.FollowSymlinks
464 }
465 if dest.SSHFS.SFTPDriver == nil && mount.SSHFS.SFTPDriver != nil {
466 tmpl.copyListEntryField(mounts, dst, src, "sshfs.sftpDriver")
467 dest.SSHFS.SFTPDriver = mount.SSHFS.SFTPDriver
468 }
469 if dest.SSHFS.ReadonlyNames == nil && mount.SSHFS.ReadonlyNames != nil {
470 tmpl.copyListEntryField(mounts, dst, src, "sshfs.readonlyNames")
471 dest.SSHFS.ReadonlyNames = mount.SSHFS.ReadonlyNames
472 }
473 // NineP
474 if dest.NineP.SecurityModel == nil && mount.NineP.SecurityModel != nil {
475 tmpl.copyListEntryField(mounts, dst, src, "9p.securityModel")
476 dest.NineP.SecurityModel = mount.NineP.SecurityModel
477 }
478 if dest.NineP.ProtocolVersion == nil && mount.NineP.ProtocolVersion != nil {
479 tmpl.copyListEntryField(mounts, dst, src, "9p.protocolVersion")
480 dest.NineP.ProtocolVersion = mount.NineP.ProtocolVersion
481 }
482 if dest.NineP.Msize == nil && mount.NineP.Msize != nil {
483 tmpl.copyListEntryField(mounts, dst, src, "9p.msize")
484 dest.NineP.Msize = mount.NineP.Msize
485 }
486 if dest.NineP.Cache == nil && mount.NineP.Cache != nil {
487 tmpl.copyListEntryField(mounts, dst, src, "9p.cache")
488 dest.NineP.Cache = mount.NineP.Cache
489 }
490 // Virtiofs
491 if dest.Virtiofs.QueueSize == nil && mount.Virtiofs.QueueSize != nil {
492 tmpl.copyListEntryField(mounts, dst, src, "virtiofs.queueSize")
493 dest.Virtiofs.QueueSize = mount.Virtiofs.QueueSize
494 }
495 if mountPoint != "*" {
496 tmpl.copyListEntryComments(mounts, dst, src, "")
497 tmpl.copyListEntryComments(mounts, dst, src, "sshfs")
498 tmpl.copyListEntryComments(mounts, dst, src, "9p")
499 tmpl.copyListEntryComments(mounts, dst, src, "virtiofs")
500 }
501 }
502 tmpl.Config.Mounts = slices.Delete(tmpl.Config.Mounts, src, src+1)
503 tmpl.deleteListEntry(mounts, src)
504 }
505}
506
507// combineNetworks combines networks entries. The shared key is the interface name.
508func (tmpl *Template) combineNetworks() {
509 const networks = "networks"
510
511 interfaceIdx := make(map[string]int, len(tmpl.Config.Networks))
512 for src := 0; src < len(tmpl.Config.Networks); {
513 nw := tmpl.Config.Networks[src]
514 var from, to int
515 if nw.Interface == "*" {
516 from = 0
517 to = src - 1
518 } else {
519 if i, ok := interfaceIdx[nw.Interface]; ok {
520 from = i
521 to = i
522 } else {
523 if nw.Interface != "" {
524 interfaceIdx[nw.Interface] = src
525 }
526 src++
527 continue
528 }
529 }
530 for dst := from; dst <= to; dst++ {
531 dest := &tmpl.Config.Networks[dst]
532 // Lima and Socket are mutually exclusive. Only copy base values if both are still unset.
533 if dest.Lima == "" && dest.Socket == "" {
534 if nw.Lima != "" {
535 tmpl.copyListEntryField(networks, dst, src, "lima")
536 dest.Lima = nw.Lima
537 }
538 if nw.Socket != "" {
539 tmpl.copyListEntryField(networks, dst, src, "socket")
540 dest.Socket = nw.Socket
541 }
542 }
543 if dest.MACAddress == "" && nw.MACAddress != "" {
544 tmpl.copyListEntryField(networks, dst, src, "macAddress")
545 dest.MACAddress = nw.MACAddress
546 }
547 if dest.VZNAT == nil && nw.VZNAT != nil {
548 tmpl.copyListEntryField(networks, dst, src, "vzNAT")
549 dest.VZNAT = nw.VZNAT
550 }
551 if dest.Metric == nil && nw.Metric != nil {
552 tmpl.copyListEntryField(networks, dst, src, "metric")
553 dest.Metric = nw.Metric
554 }
555 if nw.Interface != "*" {
556 tmpl.copyListEntryComments(networks, dst, src, "")
557 }
558 }
559 tmpl.Config.Networks = slices.Delete(tmpl.Config.Networks, src, src+1)
560 tmpl.deleteListEntry(networks, src)
561 }
562}
563
564// yamlfmt will fail with a buffer overflow while trying to retain line breaks if the line
565// is longer than 64K. We will encode all text files that have a line that comes close.
566// maxLineLength is a constant; it is only a variable for the benefit of the unit tests.
567var maxLineLength = 65000
568
569// encodeScriptReason returns the reason why a script needs to be base64 encoded or the empty string if it doesn't.
570func encodeScriptReason(script string) string {
571 start := 0
572 line := 1
573 for i, r := range script {
574 if !(unicode.IsPrint(r) || r == '\n') {
575 return fmt.Sprintf("unprintable character %#q at offset %d", r, i)
576 }
577 // maxLineLength includes final newline
578 if i-start >= maxLineLength {
579 return fmt.Sprintf("line %d (offset %d) is longer than %d characters", line, start, maxLineLength)
580 }
581 if r == '\n' {
582 line++
583 start = i + 1
584 }
585 }
586 return ""
587}
588
589// Break base64 strings into shorter chunks. Technically we could use maxLineLength here,
590// but shorter lines look better.
591const base64ChunkLength = 76
592
593// binaryString returns a base64 encoded version of the binary string, broken into chunks
594// of at most base64ChunkLength characters per line.
595func binaryString(s string) string {
596 encoded := base64.StdEncoding.EncodeToString([]byte(s))
597 if len(encoded) <= base64ChunkLength {
598 return encoded
599 }
600
601 // Estimate capacity: encoded length + number of newlines
602 lineCount := (len(encoded) + base64ChunkLength - 1) / base64ChunkLength
603 builder := strings.Builder{}
604 builder.Grow(len(encoded) + lineCount)
605
606 for i := 0; i < len(encoded); i += base64ChunkLength {
607 end := min(i+base64ChunkLength, len(encoded))
608 builder.WriteString(encoded[i:end])
609 builder.WriteByte('\n')
610 }
611
612 return builder.String()
613}
614
615// updateScript replaces a "file" property with the actual script and then renames the field to newName ("script" or "content").
616func (tmpl *Template) updateScript(field string, idx int, newName, script, file string) {
617 tag := ""
618 if reason := encodeScriptReason(script); reason != "" {
619 logrus.Infof("File %#q is being base64 encoded: %s", file, reason)
620 script = binaryString(script)
621 tag = "!!binary"
622 }
623 entry := fmt.Sprintf("$a.%s[%d].file", field, idx)
624 // Assign script to the "file" field and then rename it to "script" or "content".
625 fmt.Fprintf(&tmpl.expr, "| (%s) = %q | (%s) tag = %q | (%s | key) = %q\n",
626 entry, script, entry, tag, entry, newName)
627}
628
629// embedAllScripts replaces all "provision" and "probes" file references with the actual script.
630func (tmpl *Template) embedAllScripts(ctx context.Context, embedAll bool) error {
631 if err := tmpl.Unmarshal(); err != nil {
632 return err
633 }
634 for i, p := range tmpl.Config.Probes {
635 if p.File == nil {
636 continue
637 }
638 // Don't overwrite existing script. This should throw an error during validation.
639 if p.Script == nil || *p.Script != "" {
640 continue
641 }
642 isTemplate, _ := SeemsTemplateURL(p.File.URL)
643 if embedAll || !isTemplate {
644 scriptTmpl, err := Read(ctx, "", p.File.URL)
645 if err != nil {
646 return err
647 }
648 tmpl.updateScript("probes", i, "script", string(scriptTmpl.Bytes), p.File.URL)
649 }
650 }
651 for i, p := range tmpl.Config.Provision {
652 if p.File == nil {
653 continue
654 }
655 newName := "script"
656 switch p.Mode {
657 case limatype.ProvisionModeData:
658 newName = "content"
659 if p.Content != nil {
660 continue
661 }
662 case limatype.ProvisionModeYQ:
663 newName = "expression"
664 if p.Expression != nil {
665 continue
666 }
667 default:
668 if p.Script != nil && *p.Script != "" {
669 continue
670 }
671 }
672 isTemplate, _ := SeemsTemplateURL(p.File.URL)
673 if embedAll || !isTemplate {
674 scriptTmpl, err := Read(ctx, "", p.File.URL)
675 if err != nil {
676 return err
677 }
678 tmpl.updateScript("provision", i, newName, string(scriptTmpl.Bytes), p.File.URL)
679 }
680 }
681 return tmpl.evalExpr(ctx)
682}