github.com/orteth01/up@v0.2.0/internal/cli/build/build.go (about)

     1  package open
     2  
     3  import (
     4  	"archive/zip"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"sort"
    10  
    11  	humanize "github.com/dustin/go-humanize"
    12  	"github.com/pkg/errors"
    13  	"github.com/tj/go/term"
    14  	"github.com/tj/kingpin"
    15  
    16  	"github.com/apex/up/internal/cli/root"
    17  	"github.com/apex/up/internal/colors"
    18  	"github.com/apex/up/internal/stats"
    19  	"github.com/apex/up/internal/util"
    20  )
    21  
    22  func init() {
    23  	cmd := root.Command("build", "Build zip file.")
    24  	size := cmd.Flag("size", "Show zip contents size information.").Bool()
    25  	cmd.Example(`up build`, "Build archive and save to ./out.zip")
    26  	cmd.Example(`up build > /tmp/out.zip`, "Build archive and output to file via stdout.")
    27  	cmd.Example(`up build --size`, "Build archive and list files by size.")
    28  
    29  	cmd.Action(func(_ *kingpin.ParseContext) error {
    30  		defer util.Pad()()
    31  
    32  		_, p, err := root.Init()
    33  		if err != nil {
    34  			return errors.Wrap(err, "initializing")
    35  		}
    36  
    37  		stats.Track("Build", nil)
    38  
    39  		if err := p.Build(); err != nil {
    40  			return errors.Wrap(err, "building")
    41  		}
    42  
    43  		r, err := p.Zip()
    44  		if err != nil {
    45  			return errors.Wrap(err, "zip")
    46  		}
    47  
    48  		var out io.Writer
    49  		var buf bytes.Buffer
    50  
    51  		switch {
    52  		default:
    53  			out = os.Stdout
    54  		case *size:
    55  			out = &buf
    56  		case term.IsTerminal():
    57  			f, err := os.Create("out.zip")
    58  			if err != nil {
    59  				return errors.Wrap(err, "creating zip")
    60  			}
    61  			defer f.Close()
    62  			out = f
    63  		}
    64  
    65  		if _, err := io.Copy(out, r); err != nil {
    66  			return errors.Wrap(err, "copying")
    67  		}
    68  
    69  		if *size {
    70  			var files []*zip.File
    71  
    72  			z, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
    73  			if err != nil {
    74  				return errors.Wrap(err, "opening zip")
    75  			}
    76  
    77  			for _, f := range z.File {
    78  				files = append(files, f)
    79  			}
    80  
    81  			sort.Slice(files, func(i int, j int) bool {
    82  				a := files[i]
    83  				b := files[j]
    84  				return a.UncompressedSize64 > b.UncompressedSize64
    85  			})
    86  
    87  			fmt.Printf("\n")
    88  			for _, f := range files {
    89  				size := humanize.Bytes(f.UncompressedSize64)
    90  				fmt.Printf("  %10s %s\n", size, colors.Purple(f.Name))
    91  			}
    92  		}
    93  
    94  		return err
    95  	})
    96  }