github.com/tiagovtristao/plz@v13.4.0+incompatible/src/clean/clean.go (about)

     1  // Code for cleaning Please build artifacts.
     2  
     3  package clean
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  
     9  	"gopkg.in/op/go-logging.v1"
    10  
    11  	"github.com/thought-machine/please/src/build"
    12  	"github.com/thought-machine/please/src/core"
    13  	"github.com/thought-machine/please/src/test"
    14  )
    15  
    16  var log = logging.MustGetLogger("clean")
    17  
    18  // Clean cleans the entire output directory and optionally the cache as well.
    19  func Clean(config *core.Configuration, cache core.Cache, background bool) {
    20  	if cache != nil {
    21  		cache.CleanAll()
    22  	}
    23  	if background {
    24  		if err := core.AsyncDeleteDir(core.OutDir); err != nil {
    25  			log.Warning("Couldn't run clean in background; will do it synchronously: %s", err)
    26  		} else {
    27  			fmt.Println("Cleaning in background; you may continue to do pleasing things in this repo in the meantime.")
    28  			return
    29  		}
    30  	}
    31  	clean(core.OutDir)
    32  }
    33  
    34  // Targets cleans a given set of build targets.
    35  func Targets(state *core.BuildState, labels []core.BuildLabel, cleanCache bool) {
    36  	for _, label := range labels {
    37  		// Clean any and all sub-targets of this target.
    38  		// This is not super efficient; we potentially repeat this walk multiple times if
    39  		// we have several targets to clean in a package. It's unlikely to be a big concern though
    40  		// unless we have lots of targets to clean and their packages are very large.
    41  		for _, target := range state.Graph.PackageOrDie(label).AllChildren(state.Graph.TargetOrDie(label)) {
    42  			if state.ShouldInclude(target) {
    43  				cleanTarget(state, target, cleanCache)
    44  			}
    45  		}
    46  	}
    47  }
    48  
    49  func cleanTarget(state *core.BuildState, target *core.BuildTarget, cleanCache bool) {
    50  	if err := build.RemoveOutputs(target); err != nil {
    51  		log.Fatalf("Failed to remove output: %s", err)
    52  	}
    53  	if target.IsTest {
    54  		if err := test.RemoveTestOutputs(target); err != nil {
    55  			log.Fatalf("Failed to remove file: %s", err)
    56  		}
    57  	}
    58  	if cleanCache && state.Cache != nil {
    59  		state.Cache.Clean(target)
    60  	}
    61  }
    62  
    63  func clean(path string) {
    64  	if core.PathExists(path) {
    65  		log.Info("Cleaning path %s", path)
    66  		if err := os.RemoveAll(path); err != nil {
    67  			log.Fatalf("Failed to clean path %s: %s", path, err)
    68  		}
    69  	}
    70  }