github.com/yourbase/yb@v0.7.1/cmd/yb/clean.go (about) 1 // Copyright 2020 YourBase Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // SPDX-License-Identifier: Apache-2.0 16 17 package main 18 19 import ( 20 "context" 21 "errors" 22 "os" 23 "path/filepath" 24 25 "github.com/spf13/cobra" 26 "github.com/yourbase/yb/internal/ybdata" 27 "zombiezen.com/go/log" 28 ) 29 30 type cleanCmd struct { 31 targets []string 32 } 33 34 func newCleanCmd() *cobra.Command { 35 cmd := new(cleanCmd) 36 c := &cobra.Command{ 37 Use: "clean [flags] [TARGET [...]]", 38 Short: "Delete build cache", 39 Long: "clean deletes the build cache available as $HOME in the build\n" + 40 "environment. If no arguments are given, all targets' caches\n" + 41 "for the current package will be deleted. Otherwise, only the\n" + 42 "caches for the given targets will be deleted.", 43 RunE: func(cc *cobra.Command, args []string) error { 44 cmd.targets = args 45 return cmd.run(cc.Context()) 46 }, 47 DisableFlagsInUseLine: true, 48 ValidArgsFunction: func(cc *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { 49 return autocompleteTargetName(toComplete) 50 }, 51 } 52 return c 53 } 54 55 func (cmd *cleanCmd) run(ctx context.Context) error { 56 dirs, err := ybdata.DirsFromEnv() 57 if err != nil { 58 return err 59 } 60 pkg, _, err := findPackage() 61 if err != nil { 62 return err 63 } 64 65 if len(cmd.targets) == 0 { 66 // Delete all caches for package. 67 dir := dirs.BuildHomeRoot(pkg.Path) 68 log.Debugf(ctx, "Deleting %s", dir) 69 return os.RemoveAll(dir) 70 } 71 72 ok := true 73 for _, tgt := range cmd.targets { 74 dir := filepath.Join(dirs.BuildHomeRoot(pkg.Path), tgt) 75 log.Debugf(ctx, "Deleting %s", dir) 76 if err := os.RemoveAll(dir); err != nil { 77 log.Errorf(ctx, "Failed to remove directory: %v", err) 78 ok = false 79 } 80 } 81 if !ok { 82 return errors.New("failed to clean directories") 83 } 84 return nil 85 }