1
0

external.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package versioner
  7. import (
  8. "errors"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "github.com/syncthing/syncthing/lib/osutil"
  14. )
  15. func init() {
  16. // Register the constructor for this type of versioner with the name "external"
  17. Factories["external"] = NewExternal
  18. }
  19. type External struct {
  20. command string
  21. folderPath string
  22. }
  23. func NewExternal(folderID, folderPath string, params map[string]string) Versioner {
  24. command := params["command"]
  25. s := External{
  26. command: command,
  27. folderPath: folderPath,
  28. }
  29. l.Debugf("instantiated %#v", s)
  30. return s
  31. }
  32. // Archive moves the named file away to a version archive. If this function
  33. // returns nil, the named file does not exist any more (has been archived).
  34. func (v External) Archive(filePath string) error {
  35. _, err := osutil.Lstat(filePath)
  36. if os.IsNotExist(err) {
  37. l.Debugln("not archiving nonexistent file", filePath)
  38. return nil
  39. } else if err != nil {
  40. return err
  41. }
  42. l.Debugln("archiving", filePath)
  43. inFolderPath, err := filepath.Rel(v.folderPath, filePath)
  44. if err != nil {
  45. return err
  46. }
  47. if v.command == "" {
  48. return errors.New("Versioner: command is empty, please enter a valid command")
  49. }
  50. cmd := exec.Command(v.command, v.folderPath, inFolderPath)
  51. env := os.Environ()
  52. // filter STGUIAUTH and STGUIAPIKEY from environment variables
  53. filteredEnv := []string{}
  54. for _, x := range env {
  55. if !strings.HasPrefix(x, "STGUIAUTH=") && !strings.HasPrefix(x, "STGUIAPIKEY=") {
  56. filteredEnv = append(filteredEnv, x)
  57. }
  58. }
  59. cmd.Env = filteredEnv
  60. err = cmd.Run()
  61. if err != nil {
  62. return err
  63. }
  64. // return error if the file was not removed
  65. if _, err = osutil.Lstat(filePath); os.IsNotExist(err) {
  66. return nil
  67. }
  68. return errors.New("Versioner: file was not removed by external script")
  69. }