golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/gomote/rm.go (about)

     1  // Copyright 2015 The Go 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 main
     6  
     7  import (
     8  	"context"
     9  	"flag"
    10  	"fmt"
    11  	"os"
    12  
    13  	"golang.org/x/build/internal/gomote/protos"
    14  	"golang.org/x/sync/errgroup"
    15  )
    16  
    17  func rm(args []string) error {
    18  	fs := flag.NewFlagSet("rm", flag.ContinueOnError)
    19  	fs.Usage = func() {
    20  		fmt.Fprintln(os.Stderr, "rm usage: gomote rm [instance] <file-or-dir>+")
    21  		fmt.Fprintln(os.Stderr, "          gomote rm [instance] .  (to delete everything)")
    22  		fmt.Fprintln(os.Stderr)
    23  		fmt.Fprintln(os.Stderr, "Instance name is optional if a group is specified.")
    24  		fs.PrintDefaults()
    25  		os.Exit(1)
    26  	}
    27  	fs.Parse(args)
    28  
    29  	ctx := context.Background()
    30  	var rmSet []string
    31  	var paths []string
    32  	if err := doPing(ctx, fs.Arg(0)); instanceDoesNotExist(err) {
    33  		// When there's no active group, this is just an error.
    34  		if activeGroup == nil {
    35  			return fmt.Errorf("instance %q: %w", fs.Arg(0), err)
    36  		}
    37  		// When there is an active group, this just means that we're going
    38  		// to use the group instead and assume the rest is a command.
    39  		for _, inst := range activeGroup.Instances {
    40  			rmSet = append(rmSet, inst)
    41  		}
    42  		if fs.NArg() == 0 {
    43  			fmt.Fprintln(os.Stderr, "error: not enough arguments")
    44  			fs.Usage()
    45  		}
    46  		paths = fs.Args()
    47  	} else if err == nil {
    48  		rmSet = append(rmSet, fs.Arg(0))
    49  		if fs.NArg() == 1 {
    50  			fmt.Fprintln(os.Stderr, "error: not enough arguments")
    51  			fs.Usage()
    52  		}
    53  		paths = fs.Args()[1:]
    54  	} else {
    55  		return fmt.Errorf("checking instance %q: %w", fs.Arg(0), err)
    56  	}
    57  
    58  	eg, ctx := errgroup.WithContext(context.Background())
    59  	for _, inst := range rmSet {
    60  		inst := inst
    61  		eg.Go(func() error {
    62  			return doRm(ctx, inst, paths)
    63  		})
    64  	}
    65  	return eg.Wait()
    66  }
    67  
    68  func doRm(ctx context.Context, inst string, paths []string) error {
    69  	client := gomoteServerClient(ctx)
    70  	if _, err := client.RemoveFiles(ctx, &protos.RemoveFilesRequest{
    71  		GomoteId: inst,
    72  		Paths:    paths,
    73  	}); err != nil {
    74  		return fmt.Errorf("unable to remove files: %w", err)
    75  	}
    76  	return nil
    77  }