xref: /dragonfly/contrib/nvi2/ex/ex_mkexrc.c (revision 9348a738)
1 /*-
2  * Copyright (c) 1992, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1992, 1993, 1994, 1995, 1996
5  *	Keith Bostic.  All rights reserved.
6  *
7  * See the LICENSE file for redistribution information.
8  */
9 
10 #include "config.h"
11 
12 #ifndef lint
13 static const char sccsid[] = "$Id: ex_mkexrc.c,v 10.13 2001/06/25 15:19:17 skimo Exp $";
14 #endif /* not lint */
15 
16 #include <sys/types.h>
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 
20 #include <bitstring.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 
29 #include "../common/common.h"
30 #include "pathnames.h"
31 
32 /*
33  * ex_mkexrc -- :mkexrc[!] [file]
34  *
35  * Create (or overwrite) a .exrc file with the current info.
36  *
37  * PUBLIC: int ex_mkexrc(SCR *, EXCMD *);
38  */
39 int
40 ex_mkexrc(SCR *sp, EXCMD *cmdp)
41 {
42 	struct stat sb;
43 	FILE *fp;
44 	int fd, sverrno;
45 	char *fname;
46 	size_t flen;
47 
48 	switch (cmdp->argc) {
49 	case 0:
50 		fname = _PATH_EXRC;
51 		break;
52 	case 1:
53 		INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1,
54 			    fname, flen);
55 		set_alt_name(sp, fname);
56 		break;
57 	default:
58 		abort();
59 	}
60 
61 	if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
62 		msgq_str(sp, M_ERR, fname,
63 		    "137|%s exists, not written; use ! to override");
64 		return (1);
65 	}
66 
67 	/* Create with max permissions of rw-r--r--. */
68 	if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
69 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
70 		msgq_str(sp, M_SYSERR, fname, "%s");
71 		return (1);
72 	}
73 
74 	if ((fp = fdopen(fd, "w")) == NULL) {
75 		sverrno = errno;
76 		(void)close(fd);
77 		goto e2;
78 	}
79 
80 	if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
81 		goto e1;
82 	if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
83 		goto e1;
84 	if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
85 		goto e1;
86 	if (opts_save(sp, fp) || ferror(fp))
87 		goto e1;
88 	if (fclose(fp)) {
89 		sverrno = errno;
90 		goto e2;
91 	}
92 
93 	msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
94 	return (0);
95 
96 e1:	sverrno = errno;
97 	(void)fclose(fp);
98 e2:	errno = sverrno;
99 	msgq_str(sp, M_SYSERR, fname, "%s");
100 	return (1);
101 }
102