github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/util/term/term.go (about)

     1  /*
     2  Copyright 2020 The Skaffold Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package term
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  	"os/exec"
    24  	"runtime"
    25  	"strconv"
    26  	"strings"
    27  
    28  	"golang.org/x/term"
    29  
    30  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants"
    31  	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
    32  )
    33  
    34  func IsTerminal(w io.Writer) (uintptr, bool) {
    35  	type descriptor interface {
    36  		Fd() uintptr
    37  	}
    38  
    39  	if f, ok := w.(descriptor); ok {
    40  		termFd := f.Fd()
    41  		isTerm := term.IsTerminal(int(termFd))
    42  		return termFd, isTerm
    43  	}
    44  
    45  	return 0, false
    46  }
    47  
    48  func SupportsColor(ctx context.Context) (bool, error) {
    49  	if runtime.GOOS == constants.Windows {
    50  		return true, nil
    51  	}
    52  
    53  	cmd := exec.Command("tput", "colors")
    54  	res, err := util.RunCmdOut(ctx, cmd)
    55  	if err != nil {
    56  		return false, fmt.Errorf("checking terminal colors: %w", err)
    57  	}
    58  
    59  	numColors, err := strconv.Atoi(strings.TrimSpace(string(res)))
    60  	if err != nil {
    61  		return false, err
    62  	}
    63  
    64  	return numColors > 0, nil
    65  }