github.com/blend/go-sdk@v1.20220411.3/sh/output.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package sh
     9  
    10  import (
    11  	"bytes"
    12  	"context"
    13  	"os"
    14  	"os/exec"
    15  )
    16  
    17  // OutputParsed parses a command as binary and arguments.
    18  // It resolves the command name in your $PATH list for you.
    19  // It captures combined output and returns it as bytes.
    20  func OutputParsed(statement string) ([]byte, error) {
    21  	cmd, err := CmdParsed(statement)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	cmd.Env = os.Environ()
    26  	return OutputCmd(cmd)
    27  }
    28  
    29  // OutputParsedContext parses a command as binary and arguments with a given context.
    30  // It resolves the command name in your $PATH list for you.
    31  // It captures combined output and returns it as bytes.
    32  func OutputParsedContext(ctx context.Context, statement string) ([]byte, error) {
    33  	cmd, err := CmdParsedContext(ctx, statement)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	cmd.Env = os.Environ()
    38  	return OutputCmd(cmd)
    39  }
    40  
    41  // Output runs a command with a given list of arguments.
    42  // It resolves the command name in your $PATH list for you.
    43  // It captures combined output and returns it as bytes.
    44  func Output(command string, args ...string) ([]byte, error) {
    45  	cmd, err := Cmd(command, args...)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	cmd.Env = os.Environ()
    50  	return OutputCmd(cmd)
    51  }
    52  
    53  // OutputContext runs a command with a given list of arguments.
    54  // It resolves the command name in your $PATH list for you.
    55  // It captures combined output and returns it as bytes.
    56  func OutputContext(ctx context.Context, command string, args ...string) ([]byte, error) {
    57  	cmd, err := Cmd(command, args...)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	cmd.Env = os.Environ()
    62  	return OutputCmd(cmd)
    63  }
    64  
    65  // OutputCmd captures the output of a given command.
    66  func OutputCmd(cmd *exec.Cmd) ([]byte, error) {
    67  	output := new(bytes.Buffer)
    68  	cmd.Stdout = output
    69  	cmd.Stderr = output
    70  	if err := cmd.Run(); err != nil {
    71  		return output.Bytes(), err
    72  	}
    73  	return output.Bytes(), nil
    74  }