github.com/GGP1/kure@v0.8.4/commands/file/cat/cat.go (about)

     1  package cat
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  
     7  	"github.com/GGP1/kure/auth"
     8  	cmdutil "github.com/GGP1/kure/commands"
     9  	"github.com/GGP1/kure/db/file"
    10  
    11  	"github.com/atotto/clipboard"
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/cobra"
    14  	bolt "go.etcd.io/bbolt"
    15  )
    16  
    17  const example = `
    18  * Write one file
    19  kure cat Sample
    20  
    21  * Write one file and copy content to the clipboard
    22  kure cat Sample -c
    23  
    24  * Write multiple files
    25  kure cat sample1 sample2 sample3`
    26  
    27  type catOptions struct {
    28  	copy bool
    29  }
    30  
    31  // NewCmd returns a new command.
    32  func NewCmd(db *bolt.DB, w io.Writer) *cobra.Command {
    33  	opts := catOptions{}
    34  	cmd := &cobra.Command{
    35  		Use:     "cat <name>",
    36  		Short:   "Read file and write to standard output",
    37  		Example: example,
    38  		Args:    cmdutil.MustExist(db, cmdutil.File),
    39  		PreRunE: auth.Login(db),
    40  		RunE:    runCat(db, w, &opts),
    41  		PostRun: func(cmd *cobra.Command, args []string) {
    42  			// Reset variables (session)
    43  			opts = catOptions{}
    44  		},
    45  	}
    46  
    47  	cmd.Flags().BoolVarP(&opts.copy, "copy", "c", false, "copy file content to the clipboard")
    48  
    49  	return cmd
    50  }
    51  
    52  func runCat(db *bolt.DB, w io.Writer, opts *catOptions) cmdutil.RunEFunc {
    53  	return func(cmd *cobra.Command, args []string) error {
    54  		for i, name := range args {
    55  			if name == "" {
    56  				return errors.Errorf("name [%d] is invalid", i)
    57  			}
    58  
    59  			name = cmdutil.NormalizeName(name)
    60  			f, err := file.Get(db, name)
    61  			if err != nil {
    62  				return err
    63  			}
    64  
    65  			buf := bytes.NewBuffer(f.Content)
    66  			buf.WriteString("\n")
    67  
    68  			if opts.copy {
    69  				if err := clipboard.WriteAll(buf.String()); err != nil {
    70  					return errors.Wrap(err, "writing to clipboard")
    71  				}
    72  			}
    73  
    74  			if _, err := io.Copy(w, buf); err != nil {
    75  				return errors.Wrap(err, "copying content")
    76  			}
    77  		}
    78  
    79  		return nil
    80  	}
    81  }