Skip to content

Commit 3f34474

Browse files
lexfreiclaude
andauthored
fix: normalize template paths for Windows compatibility (#88)
* fix: normalize template paths for Windows compatibility Use filepath.ToSlash to convert OS-specific path separators to forward slash for consistency with helm engine and embed.FS which always use forward slash internally. This fixes issue #10 where Windows users get "template not found" errors when using backslash in template paths. Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> * fix(tests): remove broken lookup tests from helm engine Remove TestRenderWithClientProvider and TestRenderWithClientProvider_error tests that reference non-existent ClientProvider interface and RenderWithClientProvider function. These tests were inherited from upstream Helm but never adapted for talm's LookupFunc implementation. Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> * refactor: address QA review findings - Export NormalizeTemplatePath and use in template.go - Add comment explaining path.Join vs filepath.Join choice - Update function documentation - Add edge case tests - Remove unused generateModeline function - Fix linter issues (error wrapping, unhandled error) Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> * fix(template): normalize paths in error fallbacks When filepath.Abs() fails for either RootDir or individual template paths, the fallback code now properly normalizes paths using engine.NormalizeTemplatePath() instead of passing raw OS-specific paths to the helm engine. This fixes Windows path handling in edge cases where Abs() fails. Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> * fix(template): fix modeline path handling Fix two bugs in the modeline path resolution loop: 1. Normalize paths in error fallback when filepath.Abs(RootDir) fails 2. Use correct variable absRootDirModeline instead of absRootDir Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> * style: fix gofmt formatting Co-Authored-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]> --------- Signed-off-by: Aleksei Sviridkin <[email protected]> Co-authored-by: Claude <[email protected]>
1 parent b96223f commit 3f34474

5 files changed

Lines changed: 103 additions & 228 deletions

File tree

‎pkg/commands/template.go‎

Lines changed: 31 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ package commands
1616

1717
import (
1818
"context"
19-
"encoding/json"
2019
"errors"
2120
"fmt"
2221
"os"
@@ -142,7 +141,7 @@ func templateWithFiles(args []string) func(ctx context.Context, c *client.Client
142141
for _, configFile := range expandedFiles {
143142
modelineConfig, err := modeline.ReadAndParseModeline(configFile)
144143
if err != nil {
145-
return fmt.Errorf("modeline parsing failed: %v\n", err)
144+
return fmt.Errorf("modeline parsing failed: %w", err)
146145
}
147146
if !templateCmdFlags.templatesFromArgs {
148147
if len(modelineConfig.Templates) == 0 {
@@ -174,7 +173,9 @@ func templateWithFiles(args []string) func(ctx context.Context, c *client.Client
174173
}
175174

176175
if templateCmdFlags.inplace {
177-
err = os.WriteFile(configFile, []byte(output), 0o644)
176+
if err = os.WriteFile(configFile, []byte(output), 0o644); err != nil {
177+
return fmt.Errorf("failed to write file %s: %w", configFile, err)
178+
}
178179
fmt.Fprintf(os.Stderr, "Updated.\n")
179180
} else {
180181
if firstFileProcessed {
@@ -215,15 +216,17 @@ func templateWithFiles(args []string) func(ctx context.Context, c *client.Client
215216
}
216217

217218
func generateOutput(ctx context.Context, c *client.Client, args []string) (string, error) {
218-
// Resolve secrets.yaml path relative to project root if not absolute
219-
withSecretsPath := ResolveSecretsPath(templateCmdFlags.withSecrets)
219+
// Resolve secrets.yaml path relative to project root if not absolute
220+
withSecretsPath := ResolveSecretsPath(templateCmdFlags.withSecrets)
220221

221222
// Resolve template file paths relative to project root
222223
resolvedTemplateFiles := make([]string, len(templateCmdFlags.templateFiles))
223224
absRootDir, rootErr := filepath.Abs(Config.RootDir)
224225
if rootErr != nil {
225-
// If we can't get absolute root, use original paths
226-
resolvedTemplateFiles = templateCmdFlags.templateFiles
226+
// If we can't get absolute root, normalize original paths for helm engine
227+
for i, p := range templateCmdFlags.templateFiles {
228+
resolvedTemplateFiles[i] = engine.NormalizeTemplatePath(p)
229+
}
227230
} else {
228231
for i, templatePath := range templateCmdFlags.templateFiles {
229232
var absTemplatePath string
@@ -235,16 +238,16 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
235238
var absErr error
236239
absTemplatePath, absErr = filepath.Abs(templatePath)
237240
if absErr != nil {
238-
// If we can't get absolute path, use original
239-
resolvedTemplateFiles[i] = templatePath
241+
// If we can't get absolute path, normalize original for helm engine
242+
resolvedTemplateFiles[i] = engine.NormalizeTemplatePath(templatePath)
240243
continue
241244
}
242245
}
243246
// Convert to relative path from root
244247
relPath, relErr := filepath.Rel(absRootDir, absTemplatePath)
245248
if relErr != nil {
246-
// If we can't get relative path, use original
247-
resolvedTemplateFiles[i] = templatePath
249+
// If we can't get relative path, use original (normalized for helm engine)
250+
resolvedTemplateFiles[i] = engine.NormalizeTemplatePath(templatePath)
248251
continue
249252
}
250253
// Normalize the path (remove .. and .)
@@ -258,12 +261,13 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
258261
if _, statErr := os.Stat(fullPath); statErr == nil {
259262
relPath = possiblePath
260263
} else {
261-
// Can't resolve, use original
262-
resolvedTemplateFiles[i] = templatePath
264+
// Can't resolve, use original (normalized for helm engine)
265+
resolvedTemplateFiles[i] = engine.NormalizeTemplatePath(templatePath)
263266
continue
264267
}
265268
}
266-
resolvedTemplateFiles[i] = relPath
269+
// Normalize path separators for helm engine (always uses forward slash)
270+
resolvedTemplateFiles[i] = engine.NormalizeTemplatePath(relPath)
267271
}
268272
}
269273

@@ -294,8 +298,10 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
294298
templatePathsForModeline := make([]string, len(templateCmdFlags.templateFiles))
295299
absRootDirModeline, err := filepath.Abs(Config.RootDir)
296300
if err != nil {
297-
// If we can't get absolute root, use original paths
298-
templatePathsForModeline = templateCmdFlags.templateFiles
301+
// If we can't get absolute root, normalize original paths for modeline
302+
for i, p := range templateCmdFlags.templateFiles {
303+
templatePathsForModeline[i] = engine.NormalizeTemplatePath(p)
304+
}
299305
} else {
300306
for i, templatePath := range templateCmdFlags.templateFiles {
301307
var absTemplatePath string
@@ -306,16 +312,16 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
306312
// Resolve relative path from current working directory
307313
absTemplatePath, err = filepath.Abs(templatePath)
308314
if err != nil {
309-
// If we can't get absolute path, use original
310-
templatePathsForModeline[i] = templatePath
315+
// If we can't get absolute path, use original (normalized)
316+
templatePathsForModeline[i] = engine.NormalizeTemplatePath(templatePath)
311317
continue
312318
}
313319
}
314320
// Check if the resolved path is inside root project
315-
relPath, err := filepath.Rel(absRootDir, absTemplatePath)
321+
relPath, err := filepath.Rel(absRootDirModeline, absTemplatePath)
316322
if err != nil {
317-
// If we can't get relative path, use original
318-
templatePathsForModeline[i] = templatePath
323+
// If we can't get relative path, use original (normalized)
324+
templatePathsForModeline[i] = engine.NormalizeTemplatePath(templatePath)
319325
continue
320326
}
321327
// Normalize the path (remove .. and .)
@@ -340,8 +346,8 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
340346
}
341347
}
342348
if !found {
343-
// Can't resolve, use original
344-
templatePathsForModeline[i] = templatePath
349+
// Can't resolve, use original (normalized)
350+
templatePathsForModeline[i] = engine.NormalizeTemplatePath(templatePath)
345351
continue
346352
}
347353
} else {
@@ -372,7 +378,8 @@ func generateOutput(ctx context.Context, c *client.Client, args []string) (strin
372378
}
373379
}
374380
}
375-
templatePathsForModeline[i] = relPath
381+
// Normalize path separators for cross-platform compatibility
382+
templatePathsForModeline[i] = engine.NormalizeTemplatePath(relPath)
376383
}
377384
}
378385

@@ -406,28 +413,3 @@ func init() {
406413

407414
addCommand(templateCmd)
408415
}
409-
410-
// generateModeline creates a modeline string using JSON formatting for values
411-
func generateModeline(templates []string) (string, error) {
412-
// Convert Nodes to JSON
413-
nodesJSON, err := json.Marshal(GlobalArgs.Nodes)
414-
if err != nil {
415-
return "", fmt.Errorf("failed to marshal nodes: %v", err)
416-
}
417-
418-
// Convert Endpoints to JSON
419-
endpointsJSON, err := json.Marshal(GlobalArgs.Endpoints)
420-
if err != nil {
421-
return "", fmt.Errorf("failed to marshal endpoints: %v", err)
422-
}
423-
424-
// Convert Templates to JSON
425-
templatesJSON, err := json.Marshal(templates)
426-
if err != nil {
427-
return "", fmt.Errorf("failed to marshal templates: %v", err)
428-
}
429-
430-
// Form the final modeline string
431-
modeline := fmt.Sprintf(`# talm: nodes=%s, endpoints=%s, templates=%s`, string(nodesJSON), string(endpointsJSON), string(templatesJSON))
432-
return modeline, nil
433-
}

‎pkg/engine/engine.go‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"encoding/json"
77
"fmt"
88
"os"
9+
"path"
910
"path/filepath"
1011
"reflect"
1112
"regexp"
@@ -57,6 +58,13 @@ type Options struct {
5758
Endpoint string
5859
}
5960

61+
// NormalizeTemplatePath converts OS-specific path separators to forward slash.
62+
// Helm engine's Render() returns map keys with forward slashes regardless of OS,
63+
// so input paths must be normalized to match.
64+
func NormalizeTemplatePath(p string) string {
65+
return filepath.ToSlash(p)
66+
}
67+
6068
// debugPhase is a unified debug function that prints debug information based on the given stage and context,
6169
// then exits the program.
6270
func debugPhase(opts Options, patches []string, clusterName string, clusterEndpoint string, mType machine.Type) {
@@ -234,7 +242,8 @@ func Render(ctx context.Context, c *client.Client, opts Options) ([]byte, error)
234242

235243
configPatches := []string{}
236244
for _, templateFile := range opts.TemplateFiles {
237-
requestedTemplate := filepath.Join(chrt.Name(), templateFile)
245+
// Use path.Join (not filepath.Join) because helm engine keys always use forward slashes
246+
requestedTemplate := path.Join(chrt.Name(), NormalizeTemplatePath(templateFile))
238247
configPatch, ok := out[requestedTemplate]
239248
if !ok {
240249
return nil, fmt.Errorf("template %s not found", templateFile)

‎pkg/engine/engine_test.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,25 @@ func TestExtractExtraDocuments(t *testing.T) {
131131
})
132132
}
133133
}
134+
135+
func TestNormalizeTemplatePath(t *testing.T) {
136+
tests := []struct {
137+
name string
138+
input string
139+
want string
140+
}{
141+
{"unix path", "templates/file.yaml", "templates/file.yaml"},
142+
{"nested path", "templates/nested/file.yaml", "templates/nested/file.yaml"},
143+
{"simple file", "file.yaml", "file.yaml"},
144+
{"empty string", "", ""},
145+
{"trailing slash", "templates/", "templates/"},
146+
}
147+
148+
for _, tt := range tests {
149+
t.Run(tt.name, func(t *testing.T) {
150+
if got := NormalizeTemplatePath(tt.input); got != tt.want {
151+
t.Errorf("NormalizeTemplatePath(%q) = %q, want %q", tt.input, got, tt.want)
152+
}
153+
})
154+
}
155+
}

‎pkg/engine/engine_windows_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//go:build windows
2+
3+
// Copyright Cozystack Authors
4+
//
5+
// Licensed under the Apache License, Version 2.0 (the "License");
6+
// you may not use this file except in compliance with the License.
7+
// You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing, software
12+
// distributed under the License is distributed on an "AS IS" BASIS,
13+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
// See the License for the specific language governing permissions and
15+
// limitations under the License.
16+
17+
package engine
18+
19+
import "testing"
20+
21+
func TestNormalizeTemplatePathWindows(t *testing.T) {
22+
tests := []struct {
23+
name string
24+
input string
25+
want string
26+
}{
27+
{"backslash", "templates\\file.yaml", "templates/file.yaml"},
28+
{"nested backslash", "templates\\nested\\file.yaml", "templates/nested/file.yaml"},
29+
{"mixed slashes", "templates\\nested/file.yaml", "templates/nested/file.yaml"},
30+
{"trailing backslash", "templates\\", "templates/"},
31+
}
32+
33+
for _, tt := range tests {
34+
t.Run(tt.name, func(t *testing.T) {
35+
if got := NormalizeTemplatePath(tt.input); got != tt.want {
36+
t.Errorf("NormalizeTemplatePath(%q) = %q, want %q", tt.input, got, tt.want)
37+
}
38+
})
39+
}
40+
}

0 commit comments

Comments
 (0)