github.com/drone/runner-go@v1.12.0/shell/powershell/powershell.go (about)

     1  // Copyright 2019 Drone.IO Inc. All rights reserved.
     2  // Use of this source code is governed by the Polyform License
     3  // that can be found in the LICENSE file.
     4  
     5  // Package powershell provides functions for converting shell
     6  // commands to powershell scripts.
     7  package powershell
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"strings"
    13  )
    14  
    15  // Suffix provides the shell script suffix.
    16  const Suffix = ".ps1"
    17  
    18  // Command returns the Powershell command and arguments.
    19  func Command() (string, []string) {
    20  	return "powershell", []string{
    21  		"-noprofile",
    22  		"-noninteractive",
    23  		"-command",
    24  	}
    25  }
    26  
    27  func Script(commands []string) string {
    28  	return script(commands, true)
    29  }
    30  
    31  func SilentScript(commands []string) string {
    32  	return script(commands, false)
    33  }
    34  
    35  // Script converts a slice of individual shell commands to
    36  // a powershell script.
    37  func script(commands []string, trace bool) string {
    38  	buf := new(bytes.Buffer)
    39  	fmt.Fprintln(buf)
    40  	fmt.Fprintf(buf, optionScript)
    41  	fmt.Fprintln(buf)
    42  	for _, command := range commands {
    43  		escaped := fmt.Sprintf("%q", "+ "+command)
    44  		escaped = strings.Replace(escaped, "$", "`$", -1)
    45  		var stringToWrite string
    46  		if trace {
    47  			stringToWrite = fmt.Sprintf(
    48  				traceScript,
    49  				escaped,
    50  				command,
    51  			)
    52  		} else {
    53  			stringToWrite = "\n" + command + "\nif ($LastExitCode -gt 0) { exit $LastExitCode }\n"
    54  		}
    55  		buf.WriteString(stringToWrite)
    56  	}
    57  	return buf.String()
    58  }
    59  
    60  // optionScript is a helper script this is added to the build
    61  // to set shell options, in this case, to exit on error.
    62  const optionScript = `$erroractionpreference = "stop"`
    63  
    64  // traceScript is a helper script that is added to the build script to trace a command.
    65  const traceScript = `
    66  echo %s
    67  %s
    68  if ($LastExitCode -gt 0) { exit $LastExitCode }
    69  `