github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/pkg/logger/env.go (about)

     1  package logger
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  // DefaultEnv returns a set of strings in the form of "key=value"
    10  // based on the current process' environment with additional entries
    11  // to improve subprocess log output.
    12  func DefaultEnv(ctx context.Context) []string {
    13  	return PrepareEnv(Get(ctx), os.Environ())
    14  }
    15  
    16  // PrepareEnv returns a set of strings in the form of "key=value"
    17  // based on a provided set of strings in the same format with additional
    18  // entries to improve subprocess log output.
    19  func PrepareEnv(l Logger, env []string) []string {
    20  	supportsColor := l.SupportsColor()
    21  	hasLines := false
    22  	hasColumns := false
    23  	hasForceColor := false
    24  	hasPythonUnbuffered := false
    25  
    26  	for _, e := range env {
    27  		// LINES and COLUMNS are posix standards.
    28  		// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
    29  		hasLines = hasLines || strings.HasPrefix(e, "LINES=")
    30  		hasColumns = hasColumns || strings.HasPrefix(e, "COLUMNS=")
    31  
    32  		// FORCE_COLOR is common in nodejs https://github.com/tilt-dev/tilt/issues/3038
    33  		hasForceColor = hasForceColor || strings.HasPrefix(e, "FORCE_COLOR=")
    34  
    35  		// PYTHONUNBUFFERED tells old Python versions not to buffer their output (< Python 3.7)
    36  		// AIUI, older versions of Python buffer output aggressively when not connected to a TTY,
    37  		// because they assume they're connected to a file and don't need realtime streaming.
    38  		hasPythonUnbuffered = hasPythonUnbuffered || strings.HasPrefix(e, "PYTHONUNBUFFERED=")
    39  	}
    40  
    41  	if !hasLines {
    42  		env = append(env, "LINES=24")
    43  	}
    44  	if !hasColumns {
    45  		env = append(env, "COLUMNS=80")
    46  	}
    47  	if !hasForceColor && supportsColor {
    48  		env = append(env, "FORCE_COLOR=1")
    49  	}
    50  	if !hasPythonUnbuffered {
    51  		env = append(env, "PYTHONUNBUFFERED=1")
    52  	}
    53  	return env
    54  }