github.com/oweisse/u-root@v0.0.0-20181109060735-d005ad25fef1/pkg/gzip/options.go (about)

     1  // Copyright 2017-2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gzip
     6  
     7  import (
     8  	"errors"
     9  	"flag"
    10  	"fmt"
    11  	"os"
    12  	"path/filepath"
    13  	"runtime"
    14  
    15  	"github.com/klauspost/pgzip"
    16  )
    17  
    18  // Options represents the CLI options possible, controlling how
    19  // gzip operates on the given input data.
    20  type Options struct {
    21  	Blocksize  int
    22  	Level      int
    23  	Processes  int
    24  	Decompress bool
    25  	Force      bool
    26  	Help       bool
    27  	Keep       bool
    28  	Quiet      bool
    29  	Stdin      bool
    30  	Stdout     bool
    31  	Test       bool
    32  	Verbose    bool
    33  	Suffix     string
    34  }
    35  
    36  // ParseArgs takes CLI args and parses them via a Flagset into fields in
    37  // the Options struct. Returns any errors from parsing and validating options.
    38  func (o *Options) ParseArgs(args []string, cmdLine *flag.FlagSet) error {
    39  	var levels [10]bool
    40  
    41  	cmdLine.IntVar(&o.Blocksize, "b", 128, "Set compression block size in KiB")
    42  	cmdLine.BoolVar(&o.Decompress, "d", false, "Decompress the compressed input")
    43  	cmdLine.BoolVar(&o.Force, "f", false, "Force overwrite of output file and compress links")
    44  	cmdLine.BoolVar(&o.Help, "h", false, "Display a help screen and quit")
    45  	cmdLine.BoolVar(&o.Keep, "k", false, "Do not delete original file after processing")
    46  	// TODO: implement list option here
    47  	cmdLine.IntVar(&o.Processes, "p", runtime.NumCPU(), "Allow up to n compression threads")
    48  	cmdLine.BoolVar(&o.Quiet, "q", false, "Print no messages, even on error")
    49  	// TODO: implement recursive option here
    50  	cmdLine.BoolVar(&o.Stdout, "c", false, "Write all processed output to stdout (won't delete)")
    51  	cmdLine.StringVar(&o.Suffix, "S", ".gz", "Specify suffix for compression")
    52  	cmdLine.BoolVar(&o.Test, "t", false, "Test the integrity of the compressed input")
    53  	cmdLine.BoolVar(&o.Verbose, "v", false, "Produce more verbose output")
    54  	cmdLine.BoolVar(&levels[1], "1", false, "Compression Level 1")
    55  	cmdLine.BoolVar(&levels[2], "2", false, "Compression Level 2")
    56  	cmdLine.BoolVar(&levels[3], "3", false, "Compression Level 3")
    57  	cmdLine.BoolVar(&levels[4], "4", false, "Compression Level 4")
    58  	cmdLine.BoolVar(&levels[5], "5", false, "Compression Level 5")
    59  	cmdLine.BoolVar(&levels[6], "6", false, "Compression Level 6")
    60  	cmdLine.BoolVar(&levels[7], "7", false, "Compression Level 7")
    61  	cmdLine.BoolVar(&levels[8], "8", false, "Compression Level 8")
    62  	cmdLine.BoolVar(&levels[9], "9", false, "Compression Level 9")
    63  
    64  	if err := cmdLine.Parse(args[1:]); err != nil {
    65  		return err
    66  	}
    67  
    68  	var err error
    69  	o.Level, err = parseLevels(levels)
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	return o.validate(len(cmdLine.Args()) > 0)
    75  }
    76  
    77  // Validate checks options.
    78  // Forces decompression to be enabled when test mode is enabled.
    79  // It further modifies options if the running binary is named
    80  // gunzip or gzcat to allow for expected behavor. Checks if there is piped stdin data.
    81  func (o *Options) validate(moreArgs bool) error {
    82  	if o.Help {
    83  		// Return an empty errorString so the CLI app does not continue
    84  		return errors.New("")
    85  	}
    86  
    87  	if o.Test {
    88  		o.Decompress = true
    89  	}
    90  
    91  	// Support gunzip and gzcat symlinks
    92  	if filepath.Base(os.Args[0]) == "gunzip" {
    93  		o.Decompress = true
    94  	} else if filepath.Base(os.Args[0]) == "gzcat" {
    95  		o.Decompress = true
    96  		o.Stdout = true
    97  	}
    98  
    99  	// Stat os.Stdin and ignore errors. stat will be a nil FileInfo if there is an
   100  	// error.
   101  	stat, _ := os.Stdin.Stat()
   102  
   103  	// No files passed and arguments and Stdin piped data found.
   104  	// Stdin piped data is ignored if arguments are found.
   105  	if !moreArgs && (stat.Mode()&os.ModeNamedPipe) != 0 {
   106  		o.Stdin = true
   107  		// Enable force to ignore suffix checks
   108  		o.Force = true
   109  		// Since there's no filename to derive the output path from, only support
   110  		// outputting to stdout when data is piped from stdin
   111  		o.Stdout = true
   112  	} else if !moreArgs {
   113  		// No stdin piped data found and no files passed as arguments
   114  		return fmt.Errorf("error: no input files specified or piped data")
   115  	}
   116  
   117  	return nil
   118  }
   119  
   120  // parseLevels loops through a [10]bool and returns the index of the element
   121  // that's true. If more than one element is true it returns an error. If no
   122  // element is true, it returns the constant pgzip.DefaultCompression (-1).
   123  func parseLevels(levels [10]bool) (int, error) {
   124  	var level int
   125  
   126  	for i, l := range levels {
   127  		if l && level != 0 {
   128  			return 0, fmt.Errorf("error: multiple compression levels specified")
   129  		} else if l {
   130  			level = i
   131  		}
   132  	}
   133  
   134  	if level == 0 {
   135  		return pgzip.DefaultCompression, nil
   136  	}
   137  
   138  	return level, nil
   139  }