[WIP] add encoding support for powershell

karthik/powershell_encoding
karthik P 1 year ago
parent fe6eba27f2
commit 8a1e1c13fe

@ -29,6 +29,10 @@ import (
"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
"github.com/hashicorp/packer-plugin-sdk/tmp"
"github.com/hashicorp/packer-plugin-sdk/uuid"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
)
var psEscape = strings.NewReplacer(
@ -95,6 +99,10 @@ type Config struct {
// Run pwsh.exe instead of powershell.exe - latest version of powershell.
UsePwsh bool `mapstructure:"use_pwsh"`
// The encoding of the script file. This is used to set the encoding of the powershell file that gets written by
//packer. The default is UTF-8.
FileEncoding string `mapstructure:"file_encoding"`
ctx interpolate.Context
}
@ -126,6 +134,21 @@ func (p *Provisioner) defaultExecuteCommand() string {
}
func (p *Provisioner) getEncoding() encoding.Encoding {
encName := p.config.FileEncoding
switch encName {
case "utf-16":
return unicode.UTF16(unicode.LittleEndian, unicode.UseBOM)
case "iso-8859-1":
return charmap.ISO8859_1
case "windows-1252":
return charmap.Windows1252
default:
return unicode.UTF8 // Fallback to UTF-8
}
}
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
func (p *Provisioner) Prepare(raws ...interface{}) error {
@ -255,7 +278,9 @@ func extractScript(p *Provisioner) (string, error) {
return "", err
}
defer temp.Close()
writer := bufio.NewWriter(temp)
enc := p.getEncoding()
log.Printf("Using encoding: %s", enc)
writer := bufio.NewWriter(transform.NewWriter(temp, enc.NewEncoder()))
for _, command := range p.config.Inline {
log.Printf("Found command: %s", command)
if _, err := writer.WriteString(command + "\n"); err != nil {

@ -39,6 +39,7 @@ type FlatConfig struct {
DebugMode *int `mapstructure:"debug_mode" cty:"debug_mode" hcl:"debug_mode"`
PauseAfter *string `mapstructure:"pause_after" cty:"pause_after" hcl:"pause_after"`
UsePwsh *bool `mapstructure:"use_pwsh" cty:"use_pwsh" hcl:"use_pwsh"`
FileEncoding *string `mapstructure:"file_encoding" cty:"file_encoding" hcl:"file_encoding"`
}
// FlatMapstructure returns a new FlatConfig.
@ -82,6 +83,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec {
"debug_mode": &hcldec.AttrSpec{Name: "debug_mode", Type: cty.Number, Required: false},
"pause_after": &hcldec.AttrSpec{Name: "pause_after", Type: cty.String, Required: false},
"use_pwsh": &hcldec.AttrSpec{Name: "use_pwsh", Type: cty.Bool, Required: false},
"file_encoding": &hcldec.AttrSpec{Name: "file_encoding", Type: cty.String, Required: false},
}
return s
}

Loading…
Cancel
Save