github.com/supr/packer@v0.3.10-0.20131015195147-7b09e24ac3c1/provisioner/file/provisioner.go (about) 1 package file 2 3 import ( 4 "errors" 5 "fmt" 6 "github.com/mitchellh/packer/common" 7 "github.com/mitchellh/packer/packer" 8 "os" 9 ) 10 11 type config struct { 12 common.PackerConfig `mapstructure:",squash"` 13 14 // The local path of the file to upload. 15 Source string 16 17 // The remote path where the local file will be uploaded to. 18 Destination string 19 20 tpl *packer.ConfigTemplate 21 } 22 23 type Provisioner struct { 24 config config 25 } 26 27 func (p *Provisioner) Prepare(raws ...interface{}) error { 28 md, err := common.DecodeConfig(&p.config, raws...) 29 if err != nil { 30 return err 31 } 32 33 p.config.tpl, err = packer.NewConfigTemplate() 34 if err != nil { 35 return err 36 } 37 p.config.tpl.UserVars = p.config.PackerUserVars 38 39 // Accumulate any errors 40 errs := common.CheckUnusedConfig(md) 41 42 templates := map[string]*string{ 43 "source": &p.config.Source, 44 "destination": &p.config.Destination, 45 } 46 47 for n, ptr := range templates { 48 var err error 49 *ptr, err = p.config.tpl.Process(*ptr, nil) 50 if err != nil { 51 errs = packer.MultiErrorAppend( 52 errs, fmt.Errorf("Error processing %s: %s", n, err)) 53 } 54 } 55 56 if _, err := os.Stat(p.config.Source); err != nil { 57 errs = packer.MultiErrorAppend(errs, 58 fmt.Errorf("Bad source '%s': %s", p.config.Source, err)) 59 } 60 61 if p.config.Destination == "" { 62 errs = packer.MultiErrorAppend(errs, 63 errors.New("Destination must be specified.")) 64 } 65 66 if errs != nil && len(errs.Errors) > 0 { 67 return errs 68 } 69 70 return nil 71 } 72 73 func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error { 74 ui.Say(fmt.Sprintf("Uploading %s => %s", p.config.Source, p.config.Destination)) 75 info, err := os.Stat(p.config.Source) 76 if err != nil { 77 return err 78 } 79 80 // If we're uploading a directory, short circuit and do that 81 if info.IsDir() { 82 return comm.UploadDir(p.config.Destination, p.config.Source, nil) 83 } 84 85 // We're uploading a file... 86 f, err := os.Open(p.config.Source) 87 if err != nil { 88 return err 89 } 90 defer f.Close() 91 92 err = comm.Upload(p.config.Destination, f) 93 if err != nil { 94 ui.Error(fmt.Sprintf("Upload failed: %s", err)) 95 } 96 return err 97 } 98 99 func (p *Provisioner) Cancel() { 100 // Just hard quit. It isn't a big deal if what we're doing keeps 101 // running on the other side. 102 os.Exit(0) 103 }