Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: skip rewriting history if exiting due to signal



On Fri, Oct 01, 2004 at 12:36:58PM -0700, Wayne Davison wrote:
> [non-appending history-file writing] will have to be improved in some
> other manner, possibly by switching over to using a *.new file to
> write out the new history lines

Here's a patch that makes the savehistfile() function use a temporary
file whenever it writes out the whole file from the start (rather than
overwriting the existing file).  This could be controversial if someone
out there has a symlink for their history file (since it would get
replaced by the temp file, and thus would no longer remain a symlink).

The naming scheme I chose to use was to write out the history data using
the name $HISTFILE.$$ since this naming idiom is already used for a
temporary file name when acquiring the $HISTFILE.LOCK lock file (there's
also no conflict with that use).  If folks think that $HISTFILE.new is a
better choice, it would be easy to change.

Thoughts?  Is this a desired change?

..wayne..
--- Src/hist.c	1 Oct 2004 19:48:53 -0000	1.54
+++ Src/hist.c	17 Oct 2004 19:44:20 -0000
@@ -2005,7 +2005,7 @@ readhistfile(char *fn, int err, int read
 void
 savehistfile(char *fn, int err, int writeflags)
 {
-    char *t, *start = NULL;
+    char *t, *tmpfile, *start = NULL;
     FILE *out;
     Histent he;
     zlong xcurhist = curhist - !!(histactive & HA_ACTIVE);
@@ -2042,11 +2042,17 @@ savehistfile(char *fn, int err, int writ
 	    extended_history = 1;
     }
     if (writeflags & HFILE_APPEND) {
+	tmpfile = NULL;
 	out = fdopen(open(unmeta(fn),
 			O_CREAT | O_WRONLY | O_APPEND | O_NOCTTY, 0600), "a");
     }
     else {
-	out = fdopen(open(unmeta(fn),
+	char *fnu = unmeta(fn);
+	int len = strlen(fnu);
+	tmpfile = zalloc(len + 10 + 1);
+	sprintf(tmpfile, "%s.%ld", fnu, (long)mypid);
+	unlink(tmpfile);
+	out = fdopen(open(tmpfile,
 			 O_CREAT | O_WRONLY | O_TRUNC | O_NOCTTY, 0600), "w");
     }
     if (out) {
@@ -2092,6 +2098,10 @@ savehistfile(char *fn, int err, int writ
 	    lasthist.text = ztrdup(start);
 	}
 	fclose(out);
+	if (tmpfile) {
+	    rename(tmpfile, unmeta(fn));
+	    free(tmpfile);
+	}
 
 	if (writeflags & HFILE_SKIPOLD
 	 && !(writeflags & (HFILE_FAST | HFILE_NO_REWRITE))) {


Messages sorted by: Reverse Date, Date, Thread, Author