projects/sievemgr

changeset 8:8caacf702c0d

Add edit subcommand for interactive editing of a script
author Guido Berhoerster <guido+sievemgr@berhoerster.name>
date Fri Nov 13 10:49:08 2020 +0100 (3 months ago)
parents 3abc8be485c0
children 7ce77ceeaccc
files cmd/sievemgr/edit.go cmd/sievemgr/main.go
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/cmd/sievemgr/edit.go	Fri Nov 13 10:49:08 2020 +0100
     1.3 @@ -0,0 +1,227 @@
     1.4 +// Copyright (C) 2020 Guido Berhoerster <guido+sievemgr@berhoerster.name>
     1.5 +//
     1.6 +// Permission is hereby granted, free of charge, to any person obtaining
     1.7 +// a copy of this software and associated documentation files (the
     1.8 +// "Software"), to deal in the Software without restriction, including
     1.9 +// without limitation the rights to use, copy, modify, merge, publish,
    1.10 +// distribute, sublicense, and/or sell copies of the Software, and to
    1.11 +// permit persons to whom the Software is furnished to do so, subject to
    1.12 +// the following conditions:
    1.13 +//
    1.14 +// The above copyright notice and this permission notice shall be included
    1.15 +// in all copies or substantial portions of the Software.
    1.16 +//
    1.17 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    1.18 +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    1.19 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    1.20 +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    1.21 +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    1.22 +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    1.23 +// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    1.24 +
    1.25 +package main
    1.26 +
    1.27 +import (
    1.28 +	"fmt"
    1.29 +	"io"
    1.30 +	"io/ioutil"
    1.31 +	"os"
    1.32 +	"os/exec"
    1.33 +	"path/filepath"
    1.34 +	"runtime"
    1.35 +	"strings"
    1.36 +
    1.37 +	"go.guido-berhoerster.org/managesieve"
    1.38 +	"go.guido-berhoerster.org/sievemgr/cmd/sievemgr/internal/config"
    1.39 +	"golang.org/x/crypto/ssh/terminal"
    1.40 +)
    1.41 +
    1.42 +func init() {
    1.43 +	cmdEdit.Flag.StringVar(&acctName, "a", "", "Select the account")
    1.44 +}
    1.45 +
    1.46 +var cmdEdit = &command{
    1.47 +	UsageLine: "edit [options] name",
    1.48 +	Run:       runEdit,
    1.49 +}
    1.50 +
    1.51 +func promptYesNo(prompt string) (yesNo bool, err error) {
    1.52 +	var tty *os.File
    1.53 +	var r io.Reader
    1.54 +	var w io.Writer
    1.55 +	if runtime.GOOS == "windows" {
    1.56 +		r = os.Stdin
    1.57 +		w = os.Stdout
    1.58 +	} else {
    1.59 +		tty, err = os.OpenFile("/dev/tty", os.O_RDWR, 0666)
    1.60 +		if err != nil {
    1.61 +			return
    1.62 +		}
    1.63 +		r = tty
    1.64 +		w = tty
    1.65 +		defer tty.Close()
    1.66 +	}
    1.67 +
    1.68 +	for {
    1.69 +		io.WriteString(w, prompt)
    1.70 +
    1.71 +		var response string
    1.72 +		_, err = fmt.Fscanln(r, &response)
    1.73 +		if err != nil {
    1.74 +			err = fmt.Errorf("failed to read response: %s", err)
    1.75 +			return
    1.76 +		}
    1.77 +
    1.78 +		switch strings.ToLower(response) {
    1.79 +		case "y", "yes":
    1.80 +			yesNo = true
    1.81 +			return
    1.82 +		case "n", "no":
    1.83 +			return
    1.84 +		}
    1.85 +	}
    1.86 +}
    1.87 +
    1.88 +func getScript(acct *config.Account, scriptName string) (string, error) {
    1.89 +	c, err := dialPlainAuth(acct)
    1.90 +	if err != nil {
    1.91 +		return "", err
    1.92 +	}
    1.93 +	defer c.Logout()
    1.94 +
    1.95 +	return c.GetScript(scriptName)
    1.96 +}
    1.97 +
    1.98 +func readScript(filename string) (string, error) {
    1.99 +	f, err := os.Open(filename)
   1.100 +	if err != nil {
   1.101 +		return "", err
   1.102 +	}
   1.103 +	defer f.Close()
   1.104 +
   1.105 +	return readLimitedString(f, managesieve.ReadLimit)
   1.106 +}
   1.107 +
   1.108 +func putScript(acct *config.Account, scriptName, script string) (string, error) {
   1.109 +	c, err := dialPlainAuth(acct)
   1.110 +	if err != nil {
   1.111 +		return "", err
   1.112 +	}
   1.113 +	defer c.Logout()
   1.114 +
   1.115 +	return c.PutScript(scriptName, script)
   1.116 +}
   1.117 +
   1.118 +func runEdit(cmd *command, args []string) error {
   1.119 +	if len(args) != 1 {
   1.120 +		return usageError("invalid number of arguments")
   1.121 +	}
   1.122 +
   1.123 +	scriptName := args[0]
   1.124 +
   1.125 +	if !terminal.IsTerminal(int(os.Stdin.Fd())) ||
   1.126 +		!terminal.IsTerminal(int(os.Stdout.Fd())) {
   1.127 +		return fmt.Errorf("the edit subcommand can only be used interactively\n")
   1.128 +	}
   1.129 +
   1.130 +	editor := os.Getenv("EDITOR")
   1.131 +	if editor == "" {
   1.132 +		return fmt.Errorf("EDITOR environment variable not set")
   1.133 +	}
   1.134 +
   1.135 +	acct, err := getAccount(&conf, acctName)
   1.136 +	if err != nil {
   1.137 +		return err
   1.138 +	}
   1.139 +
   1.140 +	if err := lookupHostPort(acct); err != nil {
   1.141 +		return err
   1.142 +	}
   1.143 +
   1.144 +	if err := readPassword(acct); err != nil {
   1.145 +		return err
   1.146 +	}
   1.147 +
   1.148 +	c, err := dialPlainAuth(acct)
   1.149 +	if err != nil {
   1.150 +		return err
   1.151 +	}
   1.152 +	defer c.Logout()
   1.153 +
   1.154 +	script, err := getScript(acct, scriptName)
   1.155 +	if err != nil {
   1.156 +		return err
   1.157 +	}
   1.158 +
   1.159 +	tmpDir, err := ioutil.TempDir(os.TempDir(), "sievemgr*")
   1.160 +	if err != nil {
   1.161 +		return fmt.Errorf("failed to create temporary directory: %s", err)
   1.162 +	}
   1.163 +
   1.164 +	tmpFile := filepath.Join(tmpDir, scriptName)
   1.165 +	if err = ioutil.WriteFile(tmpFile, []byte(script), 0640); err != nil {
   1.166 +		return fmt.Errorf("failed to create script file: %s", err)
   1.167 +	}
   1.168 +	defer func() {
   1.169 +		// show filename if an error has occured and the file is
   1.170 +		// preserved
   1.171 +		if tmpFile != "" {
   1.172 +			fmt.Fprintf(os.Stderr,
   1.173 +				"the script has been preserved as %s\n",
   1.174 +				tmpFile)
   1.175 +		}
   1.176 +	}()
   1.177 +
   1.178 +	// modification time is used to detect changes
   1.179 +	info, err := os.Stat(tmpFile)
   1.180 +	if err != nil {
   1.181 +		return fmt.Errorf("failed to stat file: %s", err)
   1.182 +	}
   1.183 +	origModTime := info.ModTime()
   1.184 +
   1.185 +	for {
   1.186 +		cmd := exec.Command(editor, tmpFile)
   1.187 +		cmd.Stdin = os.Stdin
   1.188 +		cmd.Stdout = os.Stdout
   1.189 +		cmd.Stderr = os.Stderr
   1.190 +		if err := cmd.Run(); err != nil {
   1.191 +			return fmt.Errorf("failed to run editor: %s", err)
   1.192 +		}
   1.193 +
   1.194 +		// quit if the script has not been changed
   1.195 +		if info, err := os.Stat(tmpFile); err != nil {
   1.196 +			return fmt.Errorf("failed to stat file: %s", err)
   1.197 +		} else if info.ModTime() == origModTime {
   1.198 +			fmt.Fprintln(os.Stderr, "aborting, script was not modified")
   1.199 +			break
   1.200 +		}
   1.201 +
   1.202 +		script, err = readScript(tmpFile)
   1.203 +		if err != nil {
   1.204 +			return fmt.Errorf("failed to read script: %s", err)
   1.205 +		}
   1.206 +
   1.207 +		warnings, err := putScript(acct, scriptName, script)
   1.208 +		if err != nil {
   1.209 +			// show error and try again if the script was rejected
   1.210 +			// by the server
   1.211 +			fmt.Fprintln(os.Stderr, err)
   1.212 +			yesNo, err := promptYesNo("edit again [y/n]? ")
   1.213 +			if err != nil {
   1.214 +				return err
   1.215 +			} else if !yesNo {
   1.216 +				return fmt.Errorf("script not saved")
   1.217 +			}
   1.218 +		} else if warnings != "" {
   1.219 +			fmt.Fprintln(os.Stderr, warnings)
   1.220 +			break
   1.221 +		} else {
   1.222 +			break
   1.223 +		}
   1.224 +	}
   1.225 +
   1.226 +	os.RemoveAll(tmpDir)
   1.227 +	tmpFile = ""
   1.228 +
   1.229 +	return nil
   1.230 +}
     2.1 --- a/cmd/sievemgr/main.go	Sat Nov 07 16:48:55 2020 +0100
     2.2 +++ b/cmd/sievemgr/main.go	Fri Nov 13 10:49:08 2020 +0100
     2.3 @@ -70,6 +70,7 @@
     2.4  	cmdCheck,
     2.5  	cmdCheckSpace,
     2.6  	cmdRename,
     2.7 +	cmdEdit,
     2.8  }
     2.9  
    2.10  func usage() {