changeset 503:3b9dea897dc0

Upgrade yesno() and make cp -i use it.
author Rob Landley <rob@landley.net>
date Mon, 27 Feb 2012 21:56:49 -0600
parents 763d581badae
children a497beb97eee
files lib/lib.c lib/lib.h toys/cp.c
diffstat 3 files changed, 12 insertions(+), 20 deletions(-) [+]
line wrap: on
line diff
--- a/lib/lib.c	Sun Feb 26 22:04:37 2012 -0600
+++ b/lib/lib.c	Mon Feb 27 21:56:49 2012 -0600
@@ -792,20 +792,19 @@
 }
 
 // This should use a raw tty, fixit later.
-int yesno(int def)
+int yesno(char *prompt, int def)
 {
-	char buf[16];
+	char buf;
 	int i;
 
 	for (i=0; i<3 && !isatty(i); i++);
 	if (i == 3) return 1;
 
-	sprintf(buf, "(%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
-	write(i, buf, 6);
-	while (read(i, buf, 1)) {
-		if (isspace(*buf)) break;
-		if (tolower(*buf) == 'y') return 1;
-		if (tolower(*buf) == 'n') return 0;
+	fdprintf(i, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
+	while (read(i, &buf, 1)) {
+		if (isspace(buf)) break;
+		if (tolower(buf) == 'y') return 1;
+		if (tolower(buf) == 'n') return 0;
 	}
 	return def;
 }
--- a/lib/lib.h	Sun Feb 26 22:04:37 2012 -0600
+++ b/lib/lib.h	Mon Feb 27 21:56:49 2012 -0600
@@ -109,7 +109,7 @@
 void replace_tempfile(int fdin, int fdout, char **tempname);
 void crc_init(unsigned int *crc_table, int little_endian);
 void terminal_size(unsigned *x, unsigned *y);
-int yesno(int def);
+int yesno(char *prompt, int def);
 void for_each_pid_with_name_in(char **names, void (*callback)(pid_t pid));
 
 
--- a/toys/cp.c	Sun Feb 26 22:04:37 2012 -0600
+++ b/toys/cp.c	Mon Feb 27 21:56:49 2012 -0600
@@ -58,18 +58,11 @@
 void cp_file(char *src, char *dst, struct stat *srcst)
 {
 	int fdout = -1;
-	char overwrite;
 
-	if ((toys.optflags & FLAG_i) && access(dst, R_OK) == 0) {
-		// -i flag is specified and dst file exists.
-		// If user does not confirm, don't copy the file
-		// Ideally I'd use perror here, but it always appends a newline
-		// to the string, resulting in the input prompt being displayed
-		// on the next line.
-		fprintf(stderr, "cp: overwrite '%s'? ", dst);
-		(void)scanf("%c", &overwrite);
-		if (!(overwrite == 'y' || overwrite == 'Y')) return;
-	}
+	// -i flag is specified and dst file exists.
+	if ((toys.optflags&FLAG_i) && !access(dst, R_OK)
+		&& !yesno("cp: overwrite", 1))
+			return;
 
 	if (toys.optflags & FLAG_v)
 		printf("'%s' -> '%s'\n", src, dst);