github.com/hashicorp/packer@v1.14.3/helper/wrappedreadline/wrappedreadline_unix.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  //go:build darwin || dragonfly || freebsd || (linux && !appengine) || netbsd || openbsd
     5  // +build darwin dragonfly freebsd linux,!appengine netbsd openbsd
     6  
     7  package wrappedreadline
     8  
     9  import (
    10  	"syscall"
    11  	"unsafe"
    12  
    13  	"github.com/hashicorp/packer/helper/wrappedstreams"
    14  )
    15  
    16  // getWidth impl for Unix
    17  func getWidth() int {
    18  	stdoutFd := int(wrappedstreams.Stdout().Fd())
    19  	stderrFd := int(wrappedstreams.Stderr().Fd())
    20  
    21  	w := getWidthFd(stdoutFd)
    22  	if w < 0 {
    23  		w = getWidthFd(stderrFd)
    24  	}
    25  
    26  	return w
    27  }
    28  
    29  type winsize struct {
    30  	Row    uint16
    31  	Col    uint16
    32  	Xpixel uint16
    33  	Ypixel uint16
    34  }
    35  
    36  // get width of the terminal
    37  func getWidthFd(stdoutFd int) int {
    38  	ws := &winsize{}
    39  	retCode, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
    40  		uintptr(stdoutFd),
    41  		uintptr(syscall.TIOCGWINSZ),
    42  		uintptr(unsafe.Pointer(ws)))
    43  
    44  	if int(retCode) == -1 {
    45  		_ = errno
    46  		return -1
    47  	}
    48  
    49  	return int(ws.Col)
    50  }