MCPcopy
hub / github.com/kopia/kopia / EditLoop

Function EditLoop

internal/editor/editor.go:24–64  ·  view source on GitHub ↗

EditLoop launches OS-specific editor (VI, notepad.exe or another editor configured through environment variables) It creates a temporary file with 'initial' contents and repeatedly invokes the editor until the provided 'parse' function returns nil result indicating success. The 'parse' function is p

(ctx context.Context, fname, initial string, withComments bool, parse func(updated string) error)

Source from the content-addressed store, hash-verified

22// It creates a temporary file with 'initial' contents and repeatedly invokes the editor until the provided 'parse' function
23// returns nil result indicating success. The 'parse' function is passed the contents of edited files without # line comments.
24func EditLoop(ctx context.Context, fname, initial string, withComments bool, parse func(updated string) error) error {
25 tmpDir, err := os.MkdirTemp("", "kopia")
26 if err != nil {
27 return errors.Wrap(err, "unable to create temp directory")
28 }
29
30 tmpFile := filepath.Join(tmpDir, fname)
31 defer os.RemoveAll(tmpDir) //nolint:errcheck
32
33 //nolint:mnd
34 if err := os.WriteFile(tmpFile, []byte(initial), 0o600); err != nil {
35 return errors.Wrap(err, "unable to write file to edit")
36 }
37
38 for {
39 if err := EditFile(ctx, tmpFile); err != nil {
40 return errors.Wrap(err, "error launching editor")
41 }
42
43 txt, err := readAndStripComments(tmpFile, withComments)
44 if err != nil {
45 return errors.Wrap(err, "error parsing edited file")
46 }
47
48 err = parse(txt)
49 if err == nil {
50 return nil
51 }
52
53 log(ctx).Errorf("%v", err)
54 fmt.Print("Reopen editor to fix? (Y/n) ")
55
56 var shouldReopen string
57
58 _, _ = fmt.Scanf("%s", &shouldReopen)
59
60 if strings.HasPrefix(strings.ToLower(shouldReopen), "n") {
61 return errors.New("aborted")
62 }
63 }
64}
65
66func readAndStripComments(fname string, withComments bool) (string, error) {
67 if !withComments {

Callers 2

runMethod · 0.92
launchEditorMethod · 0.92

Calls 5

readAndStripCommentsFunction · 0.85
ErrorfMethod · 0.80
HasPrefixMethod · 0.80
WriteFileMethod · 0.65
RemoveAllMethod · 0.45

Tested by

no test coverage detected