github.phpd.cn/thought-machine/please@v12.2.0+incompatible/src/update/clean.go (about)

     1  // +build !bootstrap
     2  
     3  package update
     4  
     5  import (
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"path"
    10  	"sort"
    11  
    12  	"github.com/Songmu/prompter"
    13  	"github.com/coreos/go-semver/semver"
    14  
    15  	"cli"
    16  	"core"
    17  )
    18  
    19  // clean checks for any stale versions in the download directory and wipes them out if OK.
    20  func clean(config *core.Configuration, manualUpdate bool) {
    21  	location := core.ExpandHomePath(config.Please.Location)
    22  	dir, _ := ioutil.ReadDir(location)
    23  	versions := make(semver.Versions, 0, len(dir))
    24  	// Convert these to semver
    25  	for _, entry := range dir {
    26  		if v, err := semver.NewVersion(entry.Name()); err == nil && !config.Please.Version.Equal(*v) {
    27  			versions = append(versions, v)
    28  		}
    29  	}
    30  	numToClean := len(versions) - config.Please.NumOldVersions
    31  	if numToClean <= 0 {
    32  		return
    33  	} else if config.Please.Autoclean {
    34  		log.Notice("Auto-cleaning old versions...")
    35  	} else if cli.StdErrIsATerminal && manualUpdate { // Only prompt on `plz update`, otherwise it is annoying
    36  		if !prompter.YN(fmt.Sprintf("Found %d old versions, will delete %d of them. OK?", len(versions), numToClean), true) {
    37  			return
    38  		}
    39  	} else {
    40  		// Not autoclean and no tty to prompt on.
    41  		log.Warning("Found %d old versions, not cleaning due to autoclean = false", len(versions))
    42  		return
    43  	}
    44  	// If we get here then we are a go for cleaning.
    45  	sort.Sort(versions)
    46  	for _, version := range versions[:numToClean] {
    47  		log.Notice("Cleaning old version %s...", version)
    48  		if err := os.RemoveAll(path.Join(location, version.String())); err != nil {
    49  			log.Error("Couldn't remove %s: %s", version, err)
    50  		}
    51  	}
    52  }