Skip to content

"rsync for cloud storage" - Google Drive, S3, Dropbox, Backblaze B2, One Drive, Swift, Hubic, Wasabi, Google Cloud Storage, Azure Blob, Azure Files, Yandex Files

1.6 KB
Raw Blame
// Package deletefile provides the deletefile command.
package deletefile

import (
	"context"
	"fmt"
	"strings"

	"github.com/rclone/rclone/cmd"
	"github.com/rclone/rclone/fs"
	"github.com/rclone/rclone/fs/operations"
	"github.com/spf13/cobra"
)

func init() {
	cmd.Root.AddCommand(commandDefinition)
}

var commandDefinition = &cobra.Command{
	Use:   "deletefile remote:path",
	Short: `Remove a single file from remote.`,
	// Warning! "|" will be replaced by backticks below
	Long: strings.ReplaceAll(`Remove a single file from remote. Unlike |delete| it cannot be used to
remove a directory and it doesn't obey include/exclude filters - if the
specified file exists, it will always be removed from its original location.

The |--backup-dir| and |--suffix| flags are honored when set.`, "|", "`"),
	Annotations: map[string]string{
		"versionIntroduced": "v1.42",
		"groups":            "Important,Sync",
	},
	Run: func(command *cobra.Command, args []string) {
		cmd.CheckArgs(1, 1, command, args)
		f, fileName := cmd.NewFsFile(args[0])
		cmd.Run(true, false, command, func() error {
			ctx := context.Background()
			if fileName == "" {
				return fmt.Errorf("%s is a directory or doesn't exist: %w", args[0], fs.ErrorObjectNotFound)
			}
			fileObj, err := f.NewObject(ctx, fileName)
			if err != nil {
				return err
			}
			ci := fs.GetConfig(ctx)
			var backupDir fs.Fs
			if ci.BackupDir != "" || ci.Suffix != "" {
				backupDir, err = operations.BackupDir(ctx, f, f, fileName)
				if err != nil {
					return err
				}
			}
			return operations.DeleteFileWithBackupDir(ctx, fileObj, backupDir)
		})
	},
}