2a2b130b973cea81fbc77ffc806239ac1895ac46
[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 *dest_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, dest_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 ATTRIBUTE_UNUSED, 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
77         xfunc_error_retval = 2;
78         {
79                 const char *p = "-1";
80                 const char *i = "-"; /* compat */
81                 getopt32(argv, "p:i:", &p, &i);
82                 patch_level = xatoi(p); /* can be negative! */
83                 patch_file = xfopen_stdin(i);
84         }
85
86         patch_line = xmalloc_getline(patch_file);
87         while (patch_line) {
88                 FILE *src_stream;
89                 FILE *dst_stream;
90                 //char *old_filename;
91                 char *new_filename;
92                 char *backup_filename;
93                 unsigned src_cur_line = 1;
94                 unsigned dest_cur_line = 0;
95                 unsigned dest_beg_line;
96                 unsigned bad_hunk_count = 0;
97                 unsigned hunk_count = 0;
98                 smallint copy_trailing_lines_flag = 0;
99
100                 /* Skip everything upto the "---" marker
101                  * No need to parse the lines "Only in <dir>", and "diff <args>"
102                  */
103                 do {
104                         /* Extract the filename used before the patch was generated */
105                         new_filename = extract_filename(patch_line, patch_level, "--- ");
106                         // was old_filename above
107                         patch_line = xmalloc_getline(patch_file);
108                         if (!patch_line) goto quit;
109                 } while (!new_filename);
110                 free(new_filename); // "source" filename is irrelevant
111
112                 new_filename = extract_filename(patch_line, patch_level, "+++ ");
113                 if (!new_filename) {
114                         bb_error_msg_and_die("invalid patch");
115                 }
116
117                 /* Get access rights from the file to be patched */
118                 if (stat(new_filename, &saved_stat) != 0) {
119                         char *slash = strrchr(new_filename, '/');
120                         if (slash) {
121                                 /* Create leading directories */
122                                 *slash = '\0';
123                                 bb_make_directory(new_filename, -1, FILEUTILS_RECUR);
124                                 *slash = '/';
125                         }
126                         backup_filename = NULL;
127                         src_stream = NULL;
128                         saved_stat.st_mode = 0644;
129                 } else {
130                         backup_filename = xasprintf("%s.orig", new_filename);
131                         xrename(new_filename, backup_filename);
132                         src_stream = xfopen(backup_filename, "r");
133                 }
134                 dst_stream = xfopen(new_filename, "w");
135                 fchmod(fileno(dst_stream), saved_stat.st_mode);
136
137                 printf("patching file %s\n", new_filename);
138
139                 /* Handle all hunks for this file */
140                 patch_line = xmalloc_fgets(patch_file);
141                 while (patch_line) {
142                         unsigned count;
143                         unsigned src_beg_line;
144                         unsigned hunk_offset_start;
145                         unsigned src_last_line = 1;
146
147                         if ((sscanf(patch_line, "@@ -%d,%d +%d", &src_beg_line, &src_last_line, &dest_beg_line) != 3)
148                          && (sscanf(patch_line, "@@ -%d +%d", &src_beg_line, &dest_beg_line) != 2)
149                         ) { /* No more hunks for this file */
150                                 break;
151                         }
152                         hunk_count++;
153
154                         if (src_beg_line && dest_beg_line) {
155                                 /* Copy unmodified lines upto start of hunk */
156                                 /* src_beg_line will be 0 if it's a new file */
157                                 count = src_beg_line - src_cur_line;
158                                 if (copy_lines(src_stream, dst_stream, count)) {
159                                         bb_error_msg_and_die("bad src file");
160                                 }
161                                 src_cur_line += count;
162                                 dest_cur_line += count;
163                                 copy_trailing_lines_flag = 1;
164                         }
165                         src_last_line += hunk_offset_start = src_cur_line;
166
167                         while (1) {
168                                 free(patch_line);
169                                 patch_line = xmalloc_fgets(patch_file);
170                                 if (patch_line == NULL)
171                                         break; /* EOF */
172                                 if ((*patch_line != '-') && (*patch_line != '+')
173                                  && (*patch_line != ' ')
174                                 ) {
175                                         break; /* End of hunk */
176                                 }
177                                 if (*patch_line != '+') { /* '-', ' ' or '\n' */
178                                         char *src_line = NULL;
179                                         if (src_cur_line == src_last_line)
180                                                 break;
181                                         if (src_stream) {
182                                                 src_line = xmalloc_fgets(src_stream);
183                                                 if (src_line) {
184                                                         int diff = strcmp(src_line, patch_line + 1);
185                                                         src_cur_line++;
186                                                         free(src_line);
187                                                         if (diff) src_line = NULL;
188                                                 }
189                                         }
190                                         if (!src_line) {
191                                                 bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start);
192                                                 bad_hunk_count++;
193                                                 break;
194                                         }
195                                         if (*patch_line == '-') {
196                                                 continue;
197                                         }
198                                 }
199                                 fputs(patch_line + 1, dst_stream);
200                                 dest_cur_line++;
201                         } /* end of while loop handling one hunk */
202                 } /* end of while loop handling one file */
203
204                 /* Cleanup last patched file */
205                 if (copy_trailing_lines_flag) {
206                         copy_lines(src_stream, dst_stream, (unsigned)(-1));
207                 }
208                 if (src_stream) {
209                         fclose(src_stream);
210                 }
211                 fclose(dst_stream);
212                 if (bad_hunk_count) {
213                         ret = 1;
214                         bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count);
215                 } else {
216                         /* It worked, we can remove the backup */
217                         if (backup_filename) {
218                                 unlink(backup_filename);
219                         }
220                         if ((dest_cur_line == 0) || (dest_beg_line == 0)) {
221                                 /* The new patched file is empty, remove it */
222                                 xunlink(new_filename);
223                                 // /* old_filename and new_filename may be the same file */
224                                 // unlink(old_filename);
225                         }
226                 }
227                 free(backup_filename);
228                 //free(old_filename);
229                 free(new_filename);
230         } /* end of "while there are patch lines" */
231 quit:
232
233         /* 0 = SUCCESS
234          * 1 = Some hunks failed
235          * 2 = More serious problems (exited earlier)
236          */
237         return ret;
238 }