2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 2013 Johann 'Myrkraverk' Oskarsson.
5 * Copyright (c) 1992 Diomidis Spinellis.
6 * Copyright (c) 1992, 1993
7 * The Regents of the University of California. All rights reserved.
9 * This code is derived from software contributed to Berkeley by
10 * Diomidis Spinellis of Imperial College, University of London.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 static const char copyright[] =
42 "@(#) Copyright (c) 1992, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
47 static const char sccsid[] = "@(#)main.c 8.2 (Berkeley) 1/3/94";
50 #include <sys/types.h>
52 #include <sys/param.h>
72 * Linked list of units (strings and files) to be compiled
75 struct s_compunit *next;
76 enum e_cut {CU_FILE, CU_STRING} type;
77 char *s; /* Pointer to string or fname */
81 * Linked list pointer to compilation units and pointer to current
84 static struct s_compunit *script, **cu_nextp = &script;
87 * Linked list of files to be processed
95 * Linked list pointer to files and pointer to current
98 static struct s_flist *files, **fl_nextp = &files;
100 FILE *infile; /* Current input file */
101 FILE *outfile; /* Current output file */
103 int aflag, eflag, nflag;
105 static int rval; /* Exit status */
107 static int ispan; /* Whether inplace editing spans across files */
110 * Current file and line number; line numbers restart across compilation
111 * units, but span across input files. The latter is optional if editing
114 const char *fname; /* File name. */
115 const char *outfname; /* Output file name */
116 static char oldfname[PATH_MAX]; /* Old file name (for in-place editing) */
117 static char tmpfname[PATH_MAX]; /* Temporary file name (for in-place editing) */
118 static const char *inplace; /* Inplace edit file extension. */
121 static void add_compunit(enum e_cut, char *);
122 static void add_file(char *);
123 static void usage(void);
126 main(int argc, char *argv[])
131 (void) setlocale(LC_ALL, "");
136 while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
138 case 'r': /* Gnu sed compat */
140 rflags = REG_EXTENDED;
144 ispan = 1; /* span across input files */
151 if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
153 strcpy(temp_arg, optarg);
154 strcat(temp_arg, "\n");
155 add_compunit(CU_STRING, temp_arg);
159 add_compunit(CU_FILE, optarg);
163 ispan = 0; /* don't span across input files */
166 if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
167 warnx("setting line buffered output failed");
173 if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
174 warnx("setting unbuffered output failed");
183 /* First usage case; script is the first arg */
184 if (!eflag && !fflag && *argv) {
185 add_compunit(CU_STRING, *argv);
191 /* Continue with first and start second usage */
193 for (; *argv; argv++)
207 (void)fprintf(stderr,
208 "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
209 "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
210 " ... [file ...]\n", getprogname(), getprogname());
215 * Like fgets, but go through the chain of compilation units chaining them
216 * together. Empty strings and files are ignored.
219 cu_fgets(char *buf, int n, int *more)
221 static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
222 static FILE *f; /* Current open file */
223 static char *s; /* Current pointer inside string */
224 static char string_ident[30];
230 if (script == NULL) {
236 switch (script->type) {
238 if ((f = fopen(script->s, "r")) == NULL)
239 err(1, "%s", script->s);
244 if (((size_t)snprintf(string_ident,
245 sizeof(string_ident), "\"%s\"", script->s)) >=
246 sizeof(string_ident) - 1)
247 (void)strcpy(string_ident +
248 sizeof(string_ident) - 6, " ...\"");
249 fname = string_ident;
255 if ((p = fgets(buf, n, f)) != NULL) {
257 if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
263 script = script->next;
268 if (linenum == 0 && s[0] == '#' && s[1] == 'n')
282 if (s == script->s) {
283 script = script->next;
286 script = script->next;
311 * Like fgets, but go through the list of files chaining them together.
312 * Set len to the length of the line.
315 mf_fgets(SPACE *sp, enum e_spflag spflag)
319 char *dirbuf, *basebuf;
320 static char *p = NULL;
321 static size_t plen = 0;
323 static int firstfile;
325 if (infile == NULL) {
327 if (files->fname == NULL) {
329 errx(1, "-I or -i may not be used with stdin");
339 if (infile != NULL && (c = getc(infile)) != EOF) {
340 (void)ungetc(c, infile);
343 /* If we are here then either eof or no files are open yet */
344 if (infile == stdin) {
348 if (infile != NULL) {
350 if (*oldfname != '\0') {
351 /* if there was a backup file, remove it */
354 * Backup the original. Note that hard links
355 * are not supported on all filesystems.
357 if ((link(fname, oldfname) != 0) &&
358 (rename(fname, oldfname) != 0)) {
366 if (*tmpfname != '\0') {
367 if (outfile != NULL && outfile != stdout)
368 if (fclose(outfile) != 0) {
374 if (rename(tmpfname, fname) != 0) {
375 /* this should not happen really! */
392 fname = files->fname;
393 if (inplace != NULL) {
394 if (lstat(fname, &sb) != 0)
396 if (!S_ISREG(sb.st_mode))
397 errx(1, "%s: %s %s", fname,
398 "in-place editing only",
399 "works for regular files");
400 if (*inplace != '\0') {
401 strlcpy(oldfname, fname,
403 len = strlcat(oldfname, inplace,
405 if (len > (ssize_t)sizeof(oldfname))
406 errx(1, "%s: name too long", fname);
408 if ((dirbuf = strdup(fname)) == NULL ||
409 (basebuf = strdup(fname)) == NULL)
411 len = snprintf(tmpfname, sizeof(tmpfname),
412 "%s/.!%ld!%s", dirname(dirbuf), (long)getpid(),
416 if (len >= (ssize_t)sizeof(tmpfname))
417 errx(1, "%s: name too long", fname);
419 if (outfile != NULL && outfile != stdout)
421 if ((outfile = fopen(tmpfname, "w")) == NULL)
423 fchown(fileno(outfile), sb.st_uid, sb.st_gid);
424 fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
434 if ((infile = fopen(fname, "r")) == NULL) {
441 * We are here only when infile is open and we still have something
444 * Use getline() so that we can handle essentially infinite input
445 * data. The p and plen are static so each invocation gives
446 * getline() the same buffer which is expanded as needed.
448 len = getline(&p, &plen, infile);
451 if (len != 0 && p[len - 1] == '\n') {
452 sp->append_newline = 1;
454 } else if (!lastline()) {
455 sp->append_newline = 1;
457 sp->append_newline = 0;
459 cspace(sp, p, len, spflag);
467 * Add a compilation unit to the linked list
470 add_compunit(enum e_cut type, char *s)
472 struct s_compunit *cu;
474 if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
480 cu_nextp = &cu->next;
484 * Add a file to the linked list
491 if ((fp = malloc(sizeof(struct s_flist))) == NULL)
496 fl_nextp = &fp->next;
500 next_files_have_lines(void)
502 struct s_flist *file;
507 while ((file = file->next) != NULL) {
508 if ((file_fd = fopen(file->fname, "r")) == NULL)
511 if ((ch = getc(file_fd)) != EOF) {
513 * This next file has content, therefore current
514 * file doesn't contains the last line.
534 (inplace == NULL || ispan) &&
535 next_files_have_lines());
537 if ((ch = getc(infile)) == EOF) {
539 (inplace == NULL || ispan) &&
540 next_files_have_lines());