input.go

  1// Inspired by the git-appraise project
  2
  3// Package input contains helpers to use a text editor as an input for
  4// various field of a bug
  5package input
  6
  7import (
  8	"bufio"
  9	"bytes"
 10	"fmt"
 11	"io/ioutil"
 12	"os"
 13	"os/exec"
 14	"strings"
 15
 16	"github.com/MichaelMure/git-bug/repository"
 17	"github.com/pkg/errors"
 18)
 19
 20const messageFilename = "BUG_MESSAGE_EDITMSG"
 21
 22// ErrEmptyMessage is returned when the required message has not been entered
 23var ErrEmptyMessage = errors.New("empty message")
 24
 25// ErrEmptyMessage is returned when the required title has not been entered
 26var ErrEmptyTitle = errors.New("empty title")
 27
 28const bugTitleCommentTemplate = `%s%s
 29
 30# Please enter the title and comment message. The first non-empty line will be
 31# used as the title. Lines starting with '#' will be ignored.
 32# An empty title aborts the operation.
 33`
 34
 35// BugCreateEditorInput will open the default editor in the terminal with a
 36// template for the user to fill. The file is then processed to extract title
 37// and message.
 38func BugCreateEditorInput(repo repository.RepoCommon, preTitle string, preMessage string) (string, string, error) {
 39	if preMessage != "" {
 40		preMessage = "\n\n" + preMessage
 41	}
 42
 43	template := fmt.Sprintf(bugTitleCommentTemplate, preTitle, preMessage)
 44
 45	raw, err := launchEditorWithTemplate(repo, messageFilename, template)
 46
 47	if err != nil {
 48		return "", "", err
 49	}
 50
 51	lines := strings.Split(raw, "\n")
 52
 53	var title string
 54	var buffer bytes.Buffer
 55	for _, line := range lines {
 56		if strings.HasPrefix(line, "#") {
 57			continue
 58		}
 59
 60		if title == "" {
 61			trimmed := strings.TrimSpace(line)
 62			if trimmed != "" {
 63				title = trimmed
 64			}
 65			continue
 66		}
 67
 68		buffer.WriteString(line)
 69		buffer.WriteString("\n")
 70	}
 71
 72	if title == "" {
 73		return "", "", ErrEmptyTitle
 74	}
 75
 76	message := strings.TrimSpace(buffer.String())
 77
 78	return title, message, nil
 79}
 80
 81const bugCommentTemplate = `
 82
 83# Please enter the comment message. Lines starting with '#' will be ignored,
 84# and an empty message aborts the operation.
 85`
 86
 87// BugCommentEditorInput will open the default editor in the terminal with a
 88// template for the user to fill. The file is then processed to extract a comment.
 89func BugCommentEditorInput(repo repository.RepoCommon) (string, error) {
 90	raw, err := launchEditorWithTemplate(repo, messageFilename, bugCommentTemplate)
 91
 92	if err != nil {
 93		return "", err
 94	}
 95
 96	lines := strings.Split(raw, "\n")
 97
 98	var buffer bytes.Buffer
 99	for _, line := range lines {
100		if strings.HasPrefix(line, "#") {
101			continue
102		}
103		buffer.WriteString(line)
104		buffer.WriteString("\n")
105	}
106
107	message := strings.TrimSpace(buffer.String())
108
109	if message == "" {
110		return "", ErrEmptyMessage
111	}
112
113	return message, nil
114}
115
116const bugTitleTemplate = `%s
117
118# Please enter the new title. Only one line will used.
119# Lines starting with '#' will be ignored, and an empty title aborts the operation.
120`
121
122// BugTitleEditorInput will open the default editor in the terminal with a
123// template for the user to fill. The file is then processed to extract a title.
124func BugTitleEditorInput(repo repository.RepoCommon, preTitle string) (string, error) {
125	template := fmt.Sprintf(bugTitleTemplate, preTitle)
126	raw, err := launchEditorWithTemplate(repo, messageFilename, template)
127
128	if err != nil {
129		return "", err
130	}
131
132	lines := strings.Split(raw, "\n")
133
134	var title string
135	for _, line := range lines {
136		if strings.HasPrefix(line, "#") {
137			continue
138		}
139		trimmed := strings.TrimSpace(line)
140		if trimmed == "" {
141			continue
142		}
143		title = trimmed
144		break
145	}
146
147	if title == "" {
148		return "", ErrEmptyTitle
149	}
150
151	return title, nil
152}
153
154const queryTemplate = `%s
155
156# Please edit the bug query.
157# Lines starting with '#' will be ignored, and an empty query aborts the operation.
158#
159# Example: status:open author:"rené descartes" sort:edit
160#
161# Valid filters are:
162#
163# - status:open, status:closed
164# - author:<query>
165# - label:<label>
166# - no:label
167#
168# Sorting
169#
170# - sort:id, sort:id-desc, sort:id-asc
171# - sort:creation, sort:creation-desc, sort:creation-asc
172# - sort:edit, sort:edit-desc, sort:edit-asc
173#
174# Notes
175# 
176# - queries are case insensitive.
177# - you can combine as many qualifiers as you want.
178# - you can use double quotes for multi-word search terms (ex: author:"René Descartes")
179`
180
181// QueryEditorInput will open the default editor in the terminal with a
182// template for the user to fill. The file is then processed to extract a query.
183func QueryEditorInput(repo repository.RepoCommon, preQuery string) (string, error) {
184	template := fmt.Sprintf(queryTemplate, preQuery)
185	raw, err := launchEditorWithTemplate(repo, messageFilename, template)
186
187	if err != nil {
188		return "", err
189	}
190
191	lines := strings.Split(raw, "\n")
192
193	for _, line := range lines {
194		if strings.HasPrefix(line, "#") {
195			continue
196		}
197		trimmed := strings.TrimSpace(line)
198		if trimmed == "" {
199			continue
200		}
201		return trimmed, nil
202	}
203
204	return "", nil
205}
206
207// launchEditorWithTemplate will launch an editor as launchEditor do, but with a
208// provided template.
209func launchEditorWithTemplate(repo repository.RepoCommon, fileName string, template string) (string, error) {
210	path := fmt.Sprintf("%s/.git/%s", repo.GetPath(), fileName)
211
212	err := ioutil.WriteFile(path, []byte(template), 0644)
213
214	if err != nil {
215		return "", err
216	}
217
218	return launchEditor(repo, fileName)
219}
220
221// launchEditor launches the default editor configured for the given repo. This
222// method blocks until the editor command has returned.
223//
224// The specified filename should be a temporary file and provided as a relative path
225// from the repo (e.g. "FILENAME" will be converted to ".git/FILENAME"). This file
226// will be deleted after the editor is closed and its contents have been read.
227//
228// This method returns the text that was read from the temporary file, or
229// an error if any step in the process failed.
230func launchEditor(repo repository.RepoCommon, fileName string) (string, error) {
231	path := fmt.Sprintf("%s/.git/%s", repo.GetPath(), fileName)
232	defer os.Remove(path)
233
234	editor, err := repo.GetCoreEditor()
235	if err != nil {
236		return "", fmt.Errorf("Unable to detect default git editor: %v\n", err)
237	}
238
239	cmd, err := startInlineCommand(editor, path)
240	if err != nil {
241		// Running the editor directly did not work. This might mean that
242		// the editor string is not a path to an executable, but rather
243		// a shell command (e.g. "emacsclient --tty"). As such, we'll try
244		// to run the command through bash, and if that fails, try with sh
245		args := []string{"-c", fmt.Sprintf("%s %q", editor, path)}
246		cmd, err = startInlineCommand("bash", args...)
247		if err != nil {
248			cmd, err = startInlineCommand("sh", args...)
249		}
250	}
251	if err != nil {
252		return "", fmt.Errorf("Unable to start editor: %v\n", err)
253	}
254
255	if err := cmd.Wait(); err != nil {
256		return "", fmt.Errorf("Editing finished with error: %v\n", err)
257	}
258
259	output, err := ioutil.ReadFile(path)
260
261	if err != nil {
262		return "", fmt.Errorf("Error reading edited file: %v\n", err)
263	}
264
265	return string(output), err
266}
267
268// FromFile loads and returns the contents of a given file. If - is passed
269// through, much like git, it will read from stdin. This can be piped data,
270// unless there is a tty in which case the user will be prompted to enter a
271// message.
272func FromFile(fileName string) (string, error) {
273	if fileName == "-" {
274		stat, err := os.Stdin.Stat()
275		if err != nil {
276			return "", fmt.Errorf("Error reading from stdin: %v\n", err)
277		}
278		if (stat.Mode() & os.ModeCharDevice) == 0 {
279			// There is no tty. This will allow us to read piped data instead.
280			output, err := ioutil.ReadAll(os.Stdin)
281			if err != nil {
282				return "", fmt.Errorf("Error reading from stdin: %v\n", err)
283			}
284			return string(output), err
285		}
286
287		fmt.Printf("(reading comment from standard input)\n")
288		var output bytes.Buffer
289		s := bufio.NewScanner(os.Stdin)
290		for s.Scan() {
291			output.Write(s.Bytes())
292			output.WriteRune('\n')
293		}
294		return output.String(), nil
295	}
296
297	output, err := ioutil.ReadFile(fileName)
298	if err != nil {
299		return "", fmt.Errorf("Error reading file: %v\n", err)
300	}
301	return string(output), err
302}
303
304func startInlineCommand(command string, args ...string) (*exec.Cmd, error) {
305	cmd := exec.Command(command, args...)
306	cmd.Stdin = os.Stdin
307	cmd.Stdout = os.Stdout
308	cmd.Stderr = os.Stderr
309	err := cmd.Start()
310	return cmd, err
311}