Initial import from FreeBSD RELENG_4:
[dragonfly.git] / gnu / usr.bin / patch / inp.c
1 /* $FreeBSD: src/gnu/usr.bin/patch/inp.c,v 1.10.2.1 2002/04/30 20:40:02 gad Exp $
2  *
3  * $Log: inp.c,v $
4  * Revision 2.0.1.1  88/06/03  15:06:13  lwall
5  * patch10: made a little smarter about sccs files
6  *
7  * Revision 2.0  86/09/17  15:37:02  lwall
8  * Baseline for netwide release.
9  *
10  */
11
12 #include "EXTERN.h"
13 #include "common.h"
14 #include "util.h"
15 #include "pch.h"
16 #include "INTERN.h"
17 #include "inp.h"
18
19 /* Input-file-with-indexable-lines abstract type */
20
21 static long i_size;                     /* size of the input file */
22 static char *i_womp;                    /* plan a buffer for entire file */
23 static char **i_ptr;                    /* pointers to lines in i_womp */
24
25 static int tifd = -1;                   /* plan b virtual string array */
26 static char *tibuf[2];                  /* plan b buffers */
27 static LINENUM tiline[2] = {-1, -1};    /* 1st line in each buffer */
28 static LINENUM lines_per_buf;           /* how many lines per buffer */
29 static int tireclen;                    /* length of records in tmp file */
30
31 /*
32  * New patch--prepare to edit another file.
33  */
34 void
35 re_input(void)
36 {
37     if (using_plan_a) {
38         i_size = 0;
39 #ifndef lint
40         if (i_ptr != Null(char**))
41             free((char *)i_ptr);
42 #endif
43         if (i_womp != Nullch)
44             free(i_womp);
45         i_womp = Nullch;
46         i_ptr = Null(char **);
47     }
48     else {
49         using_plan_a = TRUE;            /* maybe the next one is smaller */
50         Close(tifd);
51         tifd = -1;
52         free(tibuf[0]);
53         free(tibuf[1]);
54         tibuf[0] = tibuf[1] = Nullch;
55         tiline[0] = tiline[1] = -1;
56         tireclen = 0;
57     }
58 }
59
60 /*
61  * Constuct the line index, somehow or other.
62  */
63 void
64 scan_input(char *filename)
65 {
66     if (!plan_a(filename))
67         plan_b(filename);
68     if (verbose) {
69         say3("Patching file %s using Plan %s...\n", filename,
70           (using_plan_a ? "A" : "B") );
71     }
72 }
73
74 /*
75  * Try keeping everything in memory.
76  */
77 bool
78 plan_a(char *filename)
79 {
80     int ifd, statfailed;
81     Reg1 char *s;
82     Reg2 LINENUM iline;
83     char lbuf[MAXLINELEN];
84     int output_elsewhere = strcmp(filename, outname);
85     extern int check_patch;
86
87     statfailed = stat(filename, &filestat);
88     if (statfailed && ok_to_create_file) {
89         if (verbose)
90             say2("(Creating file %s...)\n",filename);
91         if (check_patch)
92           return TRUE;
93         makedirs(filename, TRUE);
94         close(creat(filename, 0666));
95         statfailed = stat(filename, &filestat);
96     }
97     if (statfailed && check_patch) {
98         fatal2("%s not found and in check_patch mode.", filename);
99     }
100     /* For nonexistent or read-only files, look for RCS or SCCS versions.  */
101     if (statfailed
102         || (! output_elsewhere
103             && (/* No one can write to it.  */
104                 (filestat.st_mode & 0222) == 0
105                 /* I can't write to it.  */
106                 || ((filestat.st_mode & 0022) == 0
107                     && filestat.st_uid != myuid)))) {
108         struct stat cstat;
109         char *cs = Nullch;
110         char *filebase;
111         int pathlen;
112
113         filebase = basename(filename);
114         pathlen = filebase - filename;
115
116         /* Put any leading path into `s'.
117            Leave room in lbuf for the diff command.  */
118         s = lbuf + 20;
119         strncpy(s, filename, pathlen);
120
121 #define try(f,a1,a2) (Sprintf(s + pathlen, f, a1, a2), stat(s, &cstat) == 0)
122         if ((   try("RCS/%s%s", filebase, RCSSUFFIX)
123              || try("RCS/%s%s", filebase,        "")
124              || try(    "%s%s", filebase, RCSSUFFIX))
125             &&
126             /* Check that RCS file is not working file.
127                Some hosts don't report file name length errors.  */
128             (statfailed
129              || (  (filestat.st_dev ^ cstat.st_dev)
130                  | (filestat.st_ino ^ cstat.st_ino)))) {
131             Sprintf(buf, output_elsewhere?CHECKOUT:CHECKOUT_LOCKED, filename);
132             Sprintf(lbuf, RCSDIFF, filename);
133             cs = "RCS";
134         } else if (   try("SCCS/%s%s", SCCSPREFIX, filebase)
135                    || try(     "%s%s", SCCSPREFIX, filebase)) {
136             Sprintf(buf, output_elsewhere?GET:GET_LOCKED, s);
137             Sprintf(lbuf, SCCSDIFF, s, filename);
138             cs = "SCCS";
139         } else if (statfailed)
140             fatal2("can't find %s\n", filename);
141         /* else we can't write to it but it's not under a version
142            control system, so just proceed.  */
143         if (cs) {
144             if (!statfailed) {
145                 if ((filestat.st_mode & 0222) != 0)
146                     /* The owner can write to it.  */
147                     fatal3("file %s seems to be locked by somebody else under %s\n",
148                            filename, cs);
149                 /* It might be checked out unlocked.  See if it's safe to
150                    check out the default version locked.  */
151                 if (verbose)
152                     say3("Comparing file %s to default %s version...\n",
153                          filename, cs);
154                 if (system(lbuf))
155                     fatal3("can't check out file %s: differs from default %s version\n",
156                            filename, cs);
157             }
158             if (verbose)
159                 say3("Checking out file %s from %s...\n", filename, cs);
160             if (system(buf) || stat(filename, &filestat))
161                 fatal3("can't check out file %s from %s\n", filename, cs);
162         }
163     }
164     filemode = filestat.st_mode;
165     if (!S_ISREG(filemode))
166         fatal2("%s is not a normal file--can't patch\n", filename);
167     i_size = filestat.st_size;
168     if (out_of_mem) {
169         set_hunkmax();          /* make sure dynamic arrays are allocated */
170         out_of_mem = FALSE;
171         return FALSE;                   /* force plan b because plan a bombed */
172     }
173 #ifdef lint
174     i_womp = Nullch;
175 #else
176     i_womp = malloc((MEM)(i_size+2));   /* lint says this may alloc less than */
177                                         /* i_size, but that's okay, I think. */
178 #endif
179     if (i_womp == Nullch)
180         return FALSE;
181     if ((ifd = open(filename, 0)) < 0)
182         pfatal2("can't open file %s", filename);
183 #ifndef lint
184     if (read(ifd, i_womp, (int)i_size) != i_size) {
185         Close(ifd);     /* probably means i_size > 15 or 16 bits worth */
186         free(i_womp);   /* at this point it doesn't matter if i_womp was */
187         return FALSE;   /*   undersized. */
188     }
189 #endif
190     Close(ifd);
191     if (i_size && i_womp[i_size-1] != '\n')
192         i_womp[i_size++] = '\n';
193     i_womp[i_size] = '\0';
194
195     /* count the lines in the buffer so we know how many pointers we need */
196
197     iline = 0;
198     for (s=i_womp; *s; s++) {
199         if (*s == '\n')
200             iline++;
201     }
202 #ifdef lint
203     i_ptr = Null(char**);
204 #else
205     i_ptr = (char **)malloc((MEM)((iline + 2) * sizeof(char *)));
206 #endif
207     if (i_ptr == Null(char **)) {       /* shucks, it was a near thing */
208         free((char *)i_womp);
209         return FALSE;
210     }
211
212     /* now scan the buffer and build pointer array */
213
214     iline = 1;
215     i_ptr[iline] = i_womp;
216     for (s=i_womp; *s; s++) {
217         if (*s == '\n')
218             i_ptr[++iline] = s+1;       /* these are NOT null terminated */
219     }
220     input_lines = iline - 1;
221
222     /* now check for revision, if any */
223
224     if (revision != Nullch) {
225         if (!rev_in_string(i_womp)) {
226             if (force) {
227                 if (verbose)
228                     say2(
229 "Warning: this file doesn't appear to be the %s version--patching anyway.\n",
230                         revision);
231             }
232             else if (batch) {
233                 fatal2(
234 "this file doesn't appear to be the %s version--aborting.\n", revision);
235             }
236             else {
237                 (void) ask2(
238 "This file doesn't appear to be the %s version--patch anyway? [n] ",
239                     revision);
240             if (*buf != 'y')
241                 fatal1("aborted\n");
242             }
243         }
244         else if (verbose)
245             say2("Good.  This file appears to be the %s version.\n",
246                 revision);
247     }
248     return TRUE;                        /* plan a will work */
249 }
250
251 /*
252  * Keep (virtually) nothing in memory.
253  */
254 void
255 plan_b(char *filename)
256 {
257     Reg3 FILE *ifp;
258     Reg1 int i = 0;
259     Reg2 int maxlen = 1;
260     Reg4 bool found_revision = (revision == Nullch);
261
262     using_plan_a = FALSE;
263     if ((ifp = fopen(filename, "r")) == Nullfp)
264         pfatal2("can't open file %s", filename);
265     if ((tifd = creat(TMPINNAME, 0666)) < 0)
266         pfatal2("can't open file %s", TMPINNAME);
267     while (fgets(buf, sizeof buf, ifp) != Nullch) {
268         if (revision != Nullch && !found_revision && rev_in_string(buf))
269             found_revision = TRUE;
270         if ((i = strlen(buf)) > maxlen)
271             maxlen = i;                 /* find longest line */
272     }
273     if (revision != Nullch) {
274         if (!found_revision) {
275             if (force) {
276                 if (verbose)
277                     say2(
278 "Warning: this file doesn't appear to be the %s version--patching anyway.\n",
279                         revision);
280             }
281             else if (batch) {
282                 fatal2(
283 "this file doesn't appear to be the %s version--aborting.\n", revision);
284             }
285             else {
286                 (void) ask2(
287 "This file doesn't appear to be the %s version--patch anyway? [n] ",
288                     revision);
289                 if (*buf != 'y')
290                     fatal1("aborted\n");
291             }
292         }
293         else if (verbose)
294             say2("Good.  This file appears to be the %s version.\n",
295                 revision);
296     }
297     Fseek(ifp, 0L, 0);          /* rewind file */
298     lines_per_buf = BUFFERSIZE / maxlen;
299     tireclen = maxlen;
300     tibuf[0] = malloc((MEM)(BUFFERSIZE + 1));
301     tibuf[1] = malloc((MEM)(BUFFERSIZE + 1));
302     if (tibuf[1] == Nullch)
303         fatal1("out of memory\n");
304     for (i=1; ; i++) {
305         if (! (i % lines_per_buf))      /* new block */
306             if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
307                 pfatal1("can't write temp file");
308         if (fgets(tibuf[0] + maxlen * (i%lines_per_buf), maxlen + 1, ifp)
309           == Nullch) {
310             input_lines = i - 1;
311             if (i % lines_per_buf)
312                 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
313                     pfatal1("can't write temp file");
314             break;
315         }
316     }
317     Fclose(ifp);
318     Close(tifd);
319     if ((tifd = open(TMPINNAME, 0)) < 0) {
320         pfatal2("can't reopen file %s", TMPINNAME);
321     }
322 }
323
324 /*
325  * Fetch a line from the input file, \n terminated, not necessarily \0.
326  */
327 char *
328 ifetch(line,whichbuf)
329 Reg1 LINENUM line;
330 int whichbuf;                           /* ignored when file in memory */
331 {
332     if (line < 1 || line > input_lines)
333         return "";
334     if (using_plan_a)
335         return i_ptr[line];
336     else {
337         LINENUM offline = line % lines_per_buf;
338         LINENUM baseline = line - offline;
339
340         if (tiline[0] == baseline)
341             whichbuf = 0;
342         else if (tiline[1] == baseline)
343             whichbuf = 1;
344         else {
345             tiline[whichbuf] = baseline;
346 #ifndef lint            /* complains of long accuracy */
347             Lseek(tifd, (long)baseline / lines_per_buf * BUFFERSIZE, 0);
348 #endif
349             if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
350                 pfatal2("error reading tmp file %s", TMPINNAME);
351         }
352         return tibuf[whichbuf] + (tireclen*offline);
353     }
354 }
355
356 /*
357  * True if the string argument contains the revision number we want.
358  */
359 bool
360 rev_in_string(char *string)
361 {
362     Reg1 char *s;
363     Reg2 int patlen;
364
365     if (revision == Nullch)
366         return TRUE;
367     patlen = strlen(revision);
368     if (strnEQ(string,revision,patlen) && isspace((unsigned char)string[patlen]))
369         return TRUE;
370     for (s = string; *s; s++) {
371         if (isspace((unsigned char)*s) && strnEQ(s+1, revision, patlen) &&
372                 isspace((unsigned char)s[patlen+1] )) {
373             return TRUE;
374         }
375     }
376     return FALSE;
377 }