github.com/containerd/nerdctl@v1.7.7/pkg/consoleutil/detach.go (about)

     1  /*
     2     Copyright The containerd 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 consoleutil
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"io"
    23  
    24  	"github.com/containerd/log"
    25  	"github.com/moby/term"
    26  )
    27  
    28  const DefaultDetachKeys = "ctrl-p,ctrl-q"
    29  
    30  type detachableStdin struct {
    31  	stdin  io.Reader
    32  	closer func()
    33  }
    34  
    35  // NewDetachableStdin returns an io.Reader that
    36  // uses a TTY proxy reader to read from stdin and detect when the specified detach keys are read,
    37  // in which case closer will be called.
    38  func NewDetachableStdin(stdin io.Reader, keys string, closer func()) (io.Reader, error) {
    39  	if len(keys) == 0 {
    40  		keys = DefaultDetachKeys
    41  	}
    42  	b, err := term.ToBytes(keys)
    43  	if err != nil {
    44  		return nil, fmt.Errorf("failed to convert the detach keys to bytes: %w", err)
    45  	}
    46  	return &detachableStdin{
    47  		stdin:  term.NewEscapeProxy(stdin, b),
    48  		closer: closer,
    49  	}, nil
    50  }
    51  
    52  func (ds *detachableStdin) Read(p []byte) (int, error) {
    53  	n, err := ds.stdin.Read(p)
    54  	var eerr term.EscapeError
    55  	if errors.As(err, &eerr) {
    56  		log.L.Info("read detach keys")
    57  		if ds.closer != nil {
    58  			ds.closer()
    59  		}
    60  		return n, io.EOF
    61  	}
    62  	return n, err
    63  }