4a97151449751e5fc21c8d1369aaf28110ac679b
[oweals/busybox.git] / editors / patch.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  busybox patch applet to handle the unified diff format.
4  *  Copyright (C) 2003 Glenn McGrath
5  *
6  *  Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
7  *
8  *  This applet is written to work with patches generated by GNU diff,
9  *  where there is equivalent functionality busybox patch shall behave
10  *  as per GNU patch.
11  *
12  *  There is a SUSv3 specification for patch, however it looks to be
13  *  incomplete, it doesnt even mention unified diff format.
14  *  http://www.opengroup.org/onlinepubs/007904975/utilities/patch.html
15  *
16  *  Issues
17  *   - Non-interactive
18  *   - Patches must apply cleanly or patch (not just one hunk) will fail.
19  *   - Reject file isnt saved
20  */
21
22 #include "libbb.h"
23
24 static unsigned copy_lines(FILE *src_stream, FILE *dst_stream, unsigned lines_count)
25 {
26         while (src_stream && lines_count) {
27                 char *line;
28                 line = xmalloc_fgets(src_stream);
29                 if (line == NULL) {
30                         break;
31                 }
32                 if (fputs(line, dst_stream) == EOF) {
33                         bb_perror_msg_and_die("error writing to new file");
34                 }
35                 free(line);
36                 lines_count--;
37         }
38         return lines_count;
39 }
40
41 /* If patch_level is -1 it will remove all directory names
42  * char *line must be greater than 4 chars
43  * returns NULL if the file doesnt exist or error
44  * returns malloc'ed filename
45  * NB: frees 1st argument!
46  */
47 static char *extract_filename(char *line, int patch_level, const char *pat)
48 {
49         char *temp = NULL, *filename_start_ptr = line + 4;
50
51         if (strncmp(line, pat, 4) == 0) {
52                 /* Terminate string at end of source filename */
53                 line[strcspn(line, "\t\n\r")] = '\0';
54
55                 /* Skip over (patch_level) number of leading directories */
56                 while (patch_level--) {
57                         temp = strchr(filename_start_ptr, '/');
58                         if (!temp)
59                                 break;
60                         filename_start_ptr = temp + 1;
61                 }
62                 temp = xstrdup(filename_start_ptr);
63         }
64         free(line);
65         return temp;
66 }
67
68 int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
69 int patch_main(int argc UNUSED_PARAM, char **argv)
70 {
71         struct stat saved_stat;
72         char *patch_line;
73         FILE *patch_file;
74         int patch_level;
75         int ret = 0;
76         char plus = '+';
77         unsigned opt;
78         enum {
79                 OPT_R = (1 << 2),
80                 OPT_N = (1 << 3),
81         };
82
83         xfunc_error_retval = 2;
84         {
85                 const char *p = "-1";
86                 const char *i = "-"; /* compat */
87                 opt = getopt32(argv, "p:i:RN", &p, &i);
88                 if (opt & OPT_R)
89                         plus = '-';
90                 patch_level = xatoi(p); /* can be negative! */
91                 patch_file = xfopen_stdin(i);
92         }
93
94         patch_line = xmalloc_fgetline(patch_file);
95         while (patch_line) {
96                 FILE *src_stream;
97                 FILE *dst_stream;
98                 //char *old_filename;
99                 char *new_filename;
100                 char *backup_filename;
101                 unsigned src_cur_line = 1;
102                 unsigned dst_cur_line = 0;
103                 unsigned dst_beg_line;
104                 unsigned bad_hunk_count = 0;
105                 unsigned hunk_count = 0;
106                 smallint copy_trailing_lines_flag = 0;
107
108                 /* Skip everything upto the "---" marker
109                  * No need to parse the lines "Only in <dir>", and "diff <args>"
110                  */
111                 do {
112                         /* Extract the filename used before the patch was generated */
113                         new_filename = extract_filename(patch_line, patch_level, "--- ");
114                         // was old_filename above
115                         patch_line = xmalloc_fgetline(patch_file);
116                         if (!patch_line) goto quit;
117                 } while (!new_filename);
118                 free(new_filename); // "source" filename is irrelevant
119
120                 new_filename = extract_filename(patch_line, patch_level, "+++ ");
121                 if (!new_filename) {
122                         bb_error_msg_and_die("invalid patch");
123                 }
124
125                 /* Get access rights from the file to be patched */
126                 if (stat(new_filename, &saved_stat) != 0) {
127                         char *slash = strrchr(new_filename, '/');
128                         if (slash) {
129                                 /* Create leading directories */
130                                 *slash = '\0';
131                                 bb_make_directory(new_filename, -1, FILEUTILS_RECUR);
132                                 *slash = '/';
133                         }
134                         backup_filename = NULL;
135                         src_stream = NULL;
136                         saved_stat.st_mode = 0644;
137                 } else {
138                         backup_filename = xasprintf("%s.orig", new_filename);
139                         xrename(new_filename, backup_filename);
140                         src_stream = xfopen_for_read(backup_filename);
141                 }
142                 dst_stream = xfopen_for_write(new_filename);
143                 fchmod(fileno(dst_stream), saved_stat.st_mode);
144
145                 printf("patching file %s\n", new_filename);
146
147                 /* Handle all hunks for this file */
148                 patch_line = xmalloc_fgets(patch_file);
149                 while (patch_line) {
150                         unsigned count;
151                         unsigned src_beg_line;
152                         unsigned hunk_offset_start;
153                         unsigned src_last_line = 1;
154                         unsigned dst_last_line = 1;
155
156                         if ((sscanf(patch_line, "@@ -%d,%d +%d,%d", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3)
157                          && (sscanf(patch_line, "@@ -%d +%d,%d", &src_beg_line, &dst_beg_line, &dst_last_line) < 2)
158                         ) {
159                                 /* No more hunks for this file */
160                                 break;
161                         }
162                         if (plus != '+') {
163                                 /* reverse patch */
164                                 unsigned tmp = src_last_line;
165                                 src_last_line = dst_last_line;
166                                 dst_last_line = tmp;
167                                 tmp = src_beg_line;
168                                 src_beg_line = dst_beg_line;
169                                 dst_beg_line = tmp;
170                         }
171                         hunk_count++;
172
173                         if (src_beg_line && dst_beg_line) {
174                                 /* Copy unmodified lines upto start of hunk */
175                                 /* src_beg_line will be 0 if it's a new file */
176                                 count = src_beg_line - src_cur_line;
177                                 if (copy_lines(src_stream, dst_stream, count)) {
178                                         bb_error_msg_and_die("bad src file");
179                                 }
180                                 src_cur_line += count;
181                                 dst_cur_line += count;
182                                 copy_trailing_lines_flag = 1;
183                         }
184                         src_last_line += hunk_offset_start = src_cur_line;
185                         dst_last_line += dst_cur_line;
186
187                         while (1) {
188                                 free(patch_line);
189                                 patch_line = xmalloc_fgets(patch_file);
190                                 if (patch_line == NULL)
191                                         break; /* EOF */
192                                 if ((*patch_line != '-') && (*patch_line != '+')
193                                  && (*patch_line != ' ')
194                                 ) {
195                                         break; /* End of hunk */
196                                 }
197                                 if (*patch_line != plus) { /* '-' or ' ' */
198                                         char *src_line = NULL;
199                                         if (src_cur_line == src_last_line)
200                                                 break;
201                                         if (src_stream) {
202                                                 src_line = xmalloc_fgets(src_stream);
203                                                 if (src_line) {
204                                                         int diff = strcmp(src_line, patch_line + 1);
205                                                         src_cur_line++;
206                                                         free(src_line);
207                                                         if (diff)
208                                                                 src_line = NULL;
209                                                 }
210                                         }
211                                         /* Do not patch an already patched hunk with -N */
212                                         if (src_line == 0 && (opt & OPT_N)) {
213                                                 continue;
214                                         }
215                                         if (!src_line) {
216                                                 bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start);
217                                                 bad_hunk_count++;
218                                                 break;
219                                         }
220                                         if (*patch_line != ' ') { /* '-' */
221                                                 continue;
222                                         }
223                                 }
224                                 if (dst_cur_line == dst_last_line)
225                                         break;
226                                 fputs(patch_line + 1, dst_stream);
227                                 dst_cur_line++;
228                         } /* end of while loop handling one hunk */
229                 } /* end of while loop handling one file */
230
231                 /* Cleanup last patched file */
232                 if (copy_trailing_lines_flag) {
233                         copy_lines(src_stream, dst_stream, (unsigned)(-1));
234                 }
235                 if (src_stream) {
236                         fclose(src_stream);
237                 }
238                 fclose(dst_stream);
239                 if (bad_hunk_count) {
240                         ret = 1;
241                         bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count);
242                 } else {
243                         /* It worked, we can remove the backup */
244                         if (backup_filename) {
245                                 unlink(backup_filename);
246                         }
247                         if ((dst_cur_line == 0) || (dst_beg_line == 0)) {
248                                 /* The new patched file is empty, remove it */
249                                 xunlink(new_filename);
250                                 // /* old_filename and new_filename may be the same file */
251                                 // unlink(old_filename);
252                         }
253                 }
254                 free(backup_filename);
255                 //free(old_filename);
256                 free(new_filename);
257         } /* end of "while there are patch lines" */
258  quit:
259         /* 0 = SUCCESS
260          * 1 = Some hunks failed
261          * 2 = More serious problems (exited earlier)
262          */
263         return ret;
264 }