edit.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package shellutils
  15. import (
  16. "io/ioutil"
  17. "os"
  18. "os/exec"
  19. "strings"
  20. "yunion.io/x/pkg/errors"
  21. )
  22. var editors = []string{
  23. "vim",
  24. "vi",
  25. "nvim",
  26. "nano",
  27. }
  28. func findEditor() string {
  29. for _, prog := range editors {
  30. cmd := exec.Command(prog, "--version")
  31. if err := cmd.Run(); err == nil {
  32. return prog
  33. }
  34. }
  35. return ""
  36. }
  37. func Edit(yaml string) (string, error) {
  38. tmpfile, err := ioutil.TempFile("", "policy-blob")
  39. if err != nil {
  40. return "", errors.Wrap(err, "ioutil.TempFile")
  41. }
  42. defer os.Remove(tmpfile.Name()) // clean up
  43. if _, err := tmpfile.Write([]byte(yaml)); err != nil {
  44. return "", errors.Wrap(err, "tmpfile.Write")
  45. }
  46. if err := tmpfile.Close(); err != nil {
  47. return "", errors.Wrap(err, "tmpfile.Close")
  48. }
  49. editor := findEditor()
  50. if len(editor) == 0 {
  51. return "", errors.Wrapf(errors.ErrNotFound, "no editor found, supported editors are: %s", strings.Join(editors, ","))
  52. }
  53. cmd := exec.Command(editor, tmpfile.Name())
  54. cmd.Stdin = os.Stdin
  55. cmd.Stdout = os.Stdout
  56. err = cmd.Run()
  57. if err != nil {
  58. return "", errors.Wrap(err, "cmd.Run")
  59. }
  60. policyBytes, err := ioutil.ReadFile(tmpfile.Name())
  61. if err != nil {
  62. return "", errors.Wrap(err, "ioutil.ReadFile")
  63. }
  64. if yaml == string(policyBytes) {
  65. return "", errors.Error("no change")
  66. }
  67. return string(policyBytes), nil
  68. }