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 #include <sys/types.h>
13 #include <sys/queue.h>
14 #include <sys/stat.h>
15
16 #include <bitstring.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 #include "../common/common.h"
26 #include "pathnames.h"
27
28 /*
29 * ex_mkexrc -- :mkexrc[!] [file]
30 *
31 * Create (or overwrite) a .exrc file with the current info.
32 *
33 * PUBLIC: int ex_mkexrc(SCR *, EXCMD *);
34 */
35 int
ex_mkexrc(SCR * sp,EXCMD * cmdp)36 ex_mkexrc(SCR *sp, EXCMD *cmdp)
37 {
38 struct stat sb;
39 FILE *fp;
40 int fd, sverrno;
41 char *fname;
42 size_t flen;
43
44 switch (cmdp->argc) {
45 case 0:
46 fname = _PATH_EXRC;
47 break;
48 case 1:
49 INT2CHAR(sp, cmdp->argv[0]->bp, cmdp->argv[0]->len + 1,
50 fname, flen);
51 set_alt_name(sp, fname);
52 break;
53 default:
54 abort();
55 }
56
57 if (!FL_ISSET(cmdp->iflags, E_C_FORCE) && !stat(fname, &sb)) {
58 msgq_str(sp, M_ERR, fname,
59 "137|%s exists, not written; use ! to override");
60 return (1);
61 }
62
63 /* Create with max permissions of rw-r--r--. */
64 if ((fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY,
65 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
66 msgq_str(sp, M_SYSERR, fname, "%s");
67 return (1);
68 }
69
70 if ((fp = fdopen(fd, "w")) == NULL) {
71 sverrno = errno;
72 (void)close(fd);
73 goto e2;
74 }
75
76 if (seq_save(sp, fp, "abbreviate ", SEQ_ABBREV) || ferror(fp))
77 goto e1;
78 if (seq_save(sp, fp, "map ", SEQ_COMMAND) || ferror(fp))
79 goto e1;
80 if (seq_save(sp, fp, "map! ", SEQ_INPUT) || ferror(fp))
81 goto e1;
82 if (opts_save(sp, fp) || ferror(fp))
83 goto e1;
84 if (fclose(fp)) {
85 sverrno = errno;
86 goto e2;
87 }
88
89 msgq_str(sp, M_INFO, fname, "138|New exrc file: %s");
90 return (0);
91
92 e1: sverrno = errno;
93 (void)fclose(fp);
94 e2: errno = sverrno;
95 msgq_str(sp, M_SYSERR, fname, "%s");
96 return (1);
97 }
98