...

Source file src/github.com/google/go-containerregistry/internal/editor/editor.go

Documentation: github.com/google/go-containerregistry/internal/editor

     1  // Copyright 2020 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package editor implements a simple interface for interactive file editing.
    16  // It most likely does not work on windows.
    17  package editor
    18  
    19  import (
    20  	"fmt"
    21  	"io"
    22  	"os"
    23  	"os/exec"
    24  	"path/filepath"
    25  )
    26  
    27  // Edit opens a temporary file in the default editor (per $EDITOR, falling back
    28  // to "vi") with the contents of the given io.Reader and a filename ending in
    29  // the given extension (to give a hint to the editor for syntax highlighting).
    30  //
    31  // The contents of the edited file are returned, and the temporary file removed.
    32  func Edit(input io.Reader, extension string) ([]byte, error) {
    33  	f, err := os.CreateTemp("", fmt.Sprintf("%s-edit.*.%s", filepath.Base(os.Args[0]), extension))
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	defer os.Remove(f.Name())
    38  
    39  	if _, err := io.Copy(f, input); err != nil {
    40  		return nil, err
    41  	}
    42  	f.Close()
    43  
    44  	editor := "vi"
    45  	if env := os.Getenv("EDITOR"); env != "" {
    46  		editor = env
    47  	}
    48  
    49  	path, err := exec.LookPath(editor)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	cmd := exec.Command(path, f.Name())
    55  	cmd.Stdin = os.Stdin
    56  	cmd.Stdout = os.Stdout
    57  	cmd.Stderr = os.Stderr
    58  
    59  	if err := cmd.Run(); err != nil {
    60  		return nil, err
    61  	}
    62  
    63  	return os.ReadFile(f.Name())
    64  }
    65  

View as plain text