github.com/ncw/rclone@v1.48.1-0.20190724201158-a35aa1360e3e/cmd/touch/touch.go (about) 1 package touch 2 3 import ( 4 "bytes" 5 "context" 6 "time" 7 8 "github.com/ncw/rclone/cmd" 9 "github.com/ncw/rclone/fs" 10 "github.com/ncw/rclone/fs/object" 11 "github.com/pkg/errors" 12 "github.com/spf13/cobra" 13 ) 14 15 var ( 16 notCreateNewFile bool 17 timeAsArgument string 18 ) 19 20 const defaultLayout string = "060102" 21 const layoutDateWithTime = "2006-01-02T15:04:05" 22 23 func init() { 24 cmd.Root.AddCommand(commandDefintion) 25 flags := commandDefintion.Flags() 26 flags.BoolVarP(¬CreateNewFile, "no-create", "C", false, "Do not create the file if it does not exist.") 27 flags.StringVarP(&timeAsArgument, "timestamp", "t", "", "Change the modification times to the specified time instead of the current time of day. The argument is of the form 'YYMMDD' (ex. 17.10.30) or 'YYYY-MM-DDTHH:MM:SS' (ex. 2006-01-02T15:04:05)") 28 } 29 30 var commandDefintion = &cobra.Command{ 31 Use: "touch remote:path", 32 Short: `Create new file or change file modification time.`, 33 Run: func(command *cobra.Command, args []string) { 34 cmd.CheckArgs(1, 1, command, args) 35 fsrc, srcFileName := cmd.NewFsDstFile(args) 36 cmd.Run(true, false, command, func() error { 37 return Touch(context.Background(), fsrc, srcFileName) 38 }) 39 }, 40 } 41 42 //Touch create new file or change file modification time. 43 func Touch(ctx context.Context, fsrc fs.Fs, srcFileName string) error { 44 timeAtr := time.Now() 45 if timeAsArgument != "" { 46 layout := defaultLayout 47 if len(timeAsArgument) == len(layoutDateWithTime) { 48 layout = layoutDateWithTime 49 } 50 timeAtrFromFlags, err := time.Parse(layout, timeAsArgument) 51 if err != nil { 52 return errors.Wrap(err, "failed to parse date/time argument") 53 } 54 timeAtr = timeAtrFromFlags 55 } 56 file, err := fsrc.NewObject(ctx, srcFileName) 57 if err != nil { 58 if !notCreateNewFile { 59 var buffer []byte 60 src := object.NewStaticObjectInfo(srcFileName, timeAtr, int64(len(buffer)), true, nil, fsrc) 61 _, err = fsrc.Put(ctx, bytes.NewBuffer(buffer), src) 62 if err != nil { 63 return err 64 } 65 } 66 return nil 67 } 68 err = file.SetModTime(ctx, timeAtr) 69 if err != nil { 70 return errors.Wrap(err, "touch: couldn't set mod time") 71 } 72 return nil 73 }