1 /* $OpenBSD: edit.c,v 1.19 2009/06/07 13:29:50 ray Exp $ */
4 * Written by Raymond Lai <ray@cyth.net>.
25 cleanup(const char *filename)
29 err(2, "could not delete: %s", filename);
34 * Execute an editor on the specified pathname, which is interpreted
35 * from the shell. This means flags may be included.
37 * Returns -1 on error, or the exit value on success.
40 editit(const char *pathname)
42 sig_t sighup, sigint, sigquit, sigchld;
44 int saved_errno, st, ret = -1;
47 ed = getenv("VISUAL");
49 ed = getenv("EDITOR");
53 sighup = signal(SIGHUP, SIG_IGN);
54 sigint = signal(SIGINT, SIG_IGN);
55 sigquit = signal(SIGQUIT, SIG_IGN);
56 sigchld = signal(SIGCHLD, SIG_DFL);
57 if ((pid = fork()) == -1)
60 execlp(ed, ed, pathname, (char *)NULL);
63 while (waitpid(pid, &st, 0) == -1)
69 ret = WEXITSTATUS(st);
73 (void)signal(SIGHUP, sighup);
74 (void)signal(SIGINT, sigint);
75 (void)signal(SIGQUIT, sigquit);
76 (void)signal(SIGCHLD, sigchld);
82 * Parse edit command. Returns 0 on success, -1 on error.
85 eparse(const char *cmd, const char *left, const char *right)
91 char buf[BUFSIZ], *text;
93 /* Skip whitespace. */
100 /* Edit empty file. */
110 /* Neither column is blank, so print both. */
111 if (asprintf(&text, "%s\n%s\n", left, right) == -1)
112 err(2, "could not allocate memory");
117 /* Skip if there is no left column. */
121 if (asprintf(&text, "%s\n", left) == -1)
122 err(2, "could not allocate memory");
128 /* Skip if there is no right column. */
132 if (asprintf(&text, "%s\n", right) == -1)
133 err(2, "could not allocate memory");
141 /* Create temp file. */
142 if (asprintf(&filename, "%s/sdiff.XXXXXXXXXX", tmpdir) == -1)
144 if ((fd = mkstemp(filename)) == -1)
151 if ((nwritten = write(fd, text, len)) == -1 ||
152 (size_t)nwritten != len) {
153 warn("error writing to temp file");
159 /* text is no longer used. */
162 /* Edit temp file. */
163 if (editit(filename) == -1) {
164 warn("error editing %s", filename);
168 /* Open temporary file. */
169 if (!(file = fopen(filename, "r"))) {
170 warn("could not open edited file: %s", filename);
174 /* Copy temporary file contents to output file. */
175 for (nread = sizeof(buf); nread == sizeof(buf);) {
178 nread = fread(buf, sizeof(*buf), sizeof(buf), file);
179 /* Test for error or end of file. */
180 if (nread != sizeof(buf) &&
181 (ferror(file) || !feof(file))) {
182 warnx("error reading edited file: %s", filename);
187 * If we have nothing to read, break out of loop
188 * instead of writing nothing.
193 /* Write data we just read. */
194 nwritten = fwrite(buf, sizeof(*buf), nread, outfp);
195 if (nwritten != nread) {
196 warnx("error writing to output file");
201 /* We've reached the end of the temporary file, so remove it. */
202 if (unlink(filename))
203 warn("could not delete: %s", filename);