xref: /openbsd-src/usr.sbin/config/misc.c (revision 99fd087599a8791921855f21bd7e36130f39aadc)
1 /*	$OpenBSD: misc.c,v 1.10 2019/05/14 13:44:25 tedu Exp $	*/
2 
3 /*
4  * Copyright (c) 1997 Tobias Weingartner
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/types.h>
29 
30 #include <ctype.h>
31 #include <err.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 
36 #include "misc.h"
37 
38 extern int verbose;
39 
40 int
41 parse_cmd(cmd_t *cmd, char *lbuf)
42 {
43 	char *cp, *buf;
44 
45 	lbuf[strcspn(lbuf, "\n")] = '\0';
46 	if (verbose)
47 		printf("%s\n", lbuf);
48 
49 	/* Parse input */
50 	buf = lbuf;
51 	buf = &buf[strspn(buf, " \t")];
52 	cp = &buf[strcspn(buf, " \t")];
53 	*cp++ = '\0';
54 	strlcpy(cmd->cmd, buf, sizeof cmd->cmd);
55 	buf = &cp[strspn(cp, " \t")];
56 	strlcpy(cmd->args, buf, sizeof cmd->args);
57 
58 	return (0);
59 }
60 
61 int
62 ask_cmd(cmd_t *cmd)
63 {
64 	char lbuf[100];
65 
66 	/* Get input */
67 	if (fgets(lbuf, sizeof lbuf, stdin) == NULL)
68 		errx(1, "eof");
69 	return parse_cmd(cmd, lbuf);
70 }
71 
72 int
73 ask_yn(const char *str)
74 {
75 	int ch, first;
76 
77 	printf("%s [n] ", str);
78 	fflush(stdout);
79 
80 	first = ch = getchar();
81 	if (verbose) {
82 		printf("%c", ch);
83 		fflush(stdout);
84 	}
85 	while (ch != '\n' && ch != EOF) {
86 		ch = getchar();
87 		if (verbose) {
88 			printf("%c\n", ch);
89 			fflush(stdout);
90 		}
91 	}
92 	if (ch == EOF || first == EOF)
93 		errx(1, "eof");
94 
95 	return (first == 'y' || first == 'Y');
96 }
97