2017-11-20 19:16:05 +08:00
package touch
import (
"bytes"
2019-06-17 16:34:30 +08:00
"context"
2017-11-20 19:16:05 +08:00
"time"
"github.com/pkg/errors"
2019-07-29 01:47:38 +08:00
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/fs"
2019-10-11 23:55:04 +08:00
"github.com/rclone/rclone/fs/config/flags"
2019-07-29 01:47:38 +08:00
"github.com/rclone/rclone/fs/object"
2017-11-20 19:16:05 +08:00
"github.com/spf13/cobra"
)
var (
notCreateNewFile bool
timeAsArgument string
)
const defaultLayout string = "060102"
const layoutDateWithTime = "2006-01-02T15:04:05"
func init ( ) {
2019-10-11 23:58:11 +08:00
cmd . Root . AddCommand ( commandDefinition )
2019-10-11 23:55:04 +08:00
cmdFlags := commandDefinition . Flags ( )
flags . BoolVarP ( cmdFlags , & notCreateNewFile , "no-create" , "C" , false , "Do not create the file if it does not exist." )
flags . StringVarP ( cmdFlags , & 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)" )
2017-11-20 19:16:05 +08:00
}
2019-10-11 23:58:11 +08:00
var commandDefinition = & cobra . Command {
2017-11-20 19:16:05 +08:00
Use : "touch remote:path" ,
Short : ` Create new file or change file modification time. ` ,
Run : func ( command * cobra . Command , args [ ] string ) {
cmd . CheckArgs ( 1 , 1 , command , args )
fsrc , srcFileName := cmd . NewFsDstFile ( args )
cmd . Run ( true , false , command , func ( ) error {
2019-06-17 16:34:30 +08:00
return Touch ( context . Background ( ) , fsrc , srcFileName )
2017-11-20 19:16:05 +08:00
} )
} ,
}
//Touch create new file or change file modification time.
2019-06-17 16:34:30 +08:00
func Touch ( ctx context . Context , fsrc fs . Fs , srcFileName string ) error {
2017-11-20 19:16:05 +08:00
timeAtr := time . Now ( )
if timeAsArgument != "" {
layout := defaultLayout
if len ( timeAsArgument ) == len ( layoutDateWithTime ) {
layout = layoutDateWithTime
}
timeAtrFromFlags , err := time . Parse ( layout , timeAsArgument )
if err != nil {
return errors . Wrap ( err , "failed to parse date/time argument" )
}
timeAtr = timeAtrFromFlags
}
2019-06-17 16:34:30 +08:00
file , err := fsrc . NewObject ( ctx , srcFileName )
2017-11-20 19:16:05 +08:00
if err != nil {
if ! notCreateNewFile {
var buffer [ ] byte
2018-01-13 00:30:54 +08:00
src := object . NewStaticObjectInfo ( srcFileName , timeAtr , int64 ( len ( buffer ) ) , true , nil , fsrc )
2019-06-17 16:34:30 +08:00
_ , err = fsrc . Put ( ctx , bytes . NewBuffer ( buffer ) , src )
2017-11-20 19:16:05 +08:00
if err != nil {
return err
}
}
return nil
}
2019-06-17 16:34:30 +08:00
err = file . SetModTime ( ctx , timeAtr )
2017-11-20 19:16:05 +08:00
if err != nil {
return errors . Wrap ( err , "touch: couldn't set mod time" )
}
return nil
}