Extract usage information into a separate file.
[oweals/busybox.git] / sed.c
diff --git a/sed.c b/sed.c
index 2fb243fb94ae4e09861b02aef6d868ed010a292e..4d4886e19ef73b1110fe7e19fc946c30448562f8 100644 (file)
--- a/sed.c
+++ b/sed.c
@@ -24,8 +24,9 @@
        Supported features and commands in this version of sed:
 
         - comments ('#')
-        - Address matching: num|/matchstr/[,num|/matchstr/|$]command
-        - Commands: p, d, s/match/replace/[g]
+        - address matching: num|/matchstr/[,num|/matchstr/|$]command
+        - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
+        - edit commands: (a)ppend, (i)nsert, (c)hange
         
         (Note: Specifying an address (range) to match is *optional*; commands
         default to the whole pattern space if no specific address match was
@@ -73,6 +74,9 @@ struct sed_cmd {
        regex_t *sub_match; /* sed -e 's/sub_match/replace/' */
        char *replace; /* sed -e 's/sub_match/replace/' XXX: who will hold the \1 \2 \3s? */
        unsigned int sub_g:1; /* sed -e 's/foo/bar/g' (global) */
+
+       /* edit command (a,i,c) speicific field */
+       char *editline;
 };
 
 /* globals */
@@ -81,22 +85,7 @@ static int ncmds = 0; /* number of sed commands */
 
 /*static char *cur_file = NULL;*/ /* file currently being processed XXX: do I need this? */
 
-static const char sed_usage[] =
-       "sed [-Vhnef] pattern [files...]\n"
-#ifndef BB_FEATURE_TRIVIAL_HELP
-       "\n"
-       "-n\tsuppress automatic printing of pattern space\n"
-       "-e script\tadd the script to the commands to be executed\n"
-       "-f scriptfile\tadd the contents of script-file to the commands to be executed\n"
-       "-h\tdisplay this help message\n"
-       "-V\toutput version information and exit\n"
-       "\n"
-       "If no -e or -f is given, the first non-option argument is taken as the\n"
-       "sed script to interpret. All remaining arguments are names of input\n"
-       "files; if no input files are specified, then the standard input is read.\n"
-#endif
-       ;
-
+#if 0
 static void destroy_cmd_strs()
 {
        if (sed_cmds == NULL)
@@ -125,20 +114,15 @@ static void destroy_cmd_strs()
        free(sed_cmds);
        sed_cmds = NULL;
 }
+#endif
 
-static void exit_sed(int retcode, const char *message)
-{
-       destroy_cmd_strs();
-       if (message)
-               fputs(message, stderr);
-       exit(retcode);
-}
-
+#if 0
 /*
  * trim_str - trims leading and trailing space from a string
  * 
  * Note: This returns a malloc'ed string so you must store and free it
  * XXX: This should be in the utility.c file.
+ * XXX: This is now obsolete. Maybe it belongs nowhere.
  */
 static char *trim_str(const char *str)
 {
@@ -158,17 +142,34 @@ static char *trim_str(const char *str)
         *
         * you know, a strrspn() would really be nice cuz then we could say:
         * 
-        * retstr[strlen(retstr) - strrspn(retstr, " \n\t\v") + 1] = 0;
+        * retstr[strrspn(retstr, " \n\t\v") + 1] = 0;
         */
        
        return retstr;
 }
+#endif
+
+#if 0
+/*
+ * strrspn - works just like strspn() but goes from right to left instead of
+ * left to right
+ */
+static size_t strrspn(const char *s, const char *accept)
+{
+       size_t i = strlen(s);
+
+       while (strchr(accept, s[--i]))
+               ;
+
+       return i;
+}
+#endif
 
 /*
  * index_of_unescaped_slash - walks left to right through a string beginning
  * at a specified index and returns the index of the next unescaped slash.
  */
-static int index_of_next_unescaped_slash(int idx, const char *str)
+static int index_of_next_unescaped_slash(const char *str, int idx)
 {
        do {
                idx++;
@@ -194,27 +195,23 @@ static int get_address(const char *str, int *line, regex_t **regex)
                } while (isdigit(my_str[idx]));
                my_str[idx] = 0;
                *line = atoi(my_str);
-               *regex = NULL;
        }
        else if (my_str[idx] == '$') {
                *line = -1;
-               *regex = NULL;
                idx++;
        }
        else if (my_str[idx] == '/') {
-               idx = index_of_next_unescaped_slash(idx, my_str);
+               idx = index_of_next_unescaped_slash(my_str, idx);
                if (idx == -1)
-                       exit_sed(1, "sed: unterminated match expression\n");
+                       fatalError("unterminated match expression\n");
                my_str[idx] = '\0';
                *regex = (regex_t *)xmalloc(sizeof(regex_t));
-               if (bb_regcomp(*regex, my_str+1, REG_NEWLINE) != 0) {
-                       free(my_str);
-                       exit_sed(1, NULL);
-               }
+               xregcomp(*regex, my_str+1, REG_NEWLINE);
+               idx++; /* so it points to the next character after the last '/' */
        }
        else {
-               fprintf(stderr, "sed.c:get_address: no address found in string\n");
-               fprintf(stderr, "\t(you probably didn't check the string you passed me)\n");
+               errorMsg("get_address: no address found in string\n"
+                               "\t(you probably didn't check the string you passed me)\n");
                idx = -1;
        }
 
@@ -231,7 +228,139 @@ static char *strdup_substr(const char *str, int start, int end)
        return newstr;
 }
 
-static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
+static int parse_subst_cmd(struct sed_cmd *sed_cmd, const char *substr)
+{
+       int oldidx, cflags = REG_NEWLINE;
+       char *match;
+       int idx = 0;
+
+       /*
+        * the string that gets passed to this function should look like this:
+        *    s/match/replace/gI
+        *    ||     |        ||
+        *    mandatory       optional
+        *
+        *    (all three of the '/' slashes are mandatory)
+        */
+
+       /* verify that the 's' is followed by a 'slash' */
+       if (substr[++idx] != '/')
+               fatalError("bad format in substitution expression\n");
+
+       /* save the match string */
+       oldidx = idx+1;
+       idx = index_of_next_unescaped_slash(substr, idx);
+       if (idx == -1)
+               fatalError("bad format in substitution expression\n");
+       match = strdup_substr(substr, oldidx, idx);
+
+       /* save the replacement string */
+       oldidx = idx+1;
+       idx = index_of_next_unescaped_slash(substr, idx);
+       if (idx == -1)
+               fatalError("bad format in substitution expression\n");
+       sed_cmd->replace = strdup_substr(substr, oldidx, idx);
+
+       /* process the flags */
+       while (substr[++idx]) {
+               switch (substr[idx]) {
+                       case 'g':
+                               sed_cmd->sub_g = 1;
+                               break;
+                       case 'I':
+                               cflags |= REG_ICASE;
+                               break;
+                       default:
+                               /* any whitespace or semicolon trailing after a s/// is ok */
+                               if (strchr("; \t\v\n\r", substr[idx]))
+                                       goto out;
+                               /* else */
+                               fatalError("bad option in substitution expression\n");
+               }
+       }
+
+out:   
+       /* compile the regex */
+       sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
+       xregcomp(sed_cmd->sub_match, match, cflags);
+       free(match);
+
+       return idx;
+}
+
+static int parse_edit_cmd(struct sed_cmd *sed_cmd, const char *editstr)
+{
+       int idx = 0;
+       int slashes_eaten = 0;
+       char *ptr; /* shorthand */
+
+       /*
+        * the string that gets passed to this function should look like this:
+        *
+        *    need one of these 
+        *    |
+        *    |    this backslash (immediately following the edit command) is mandatory
+        *    |    |
+        *    [aic]\
+        *    TEXT1\
+        *    TEXT2\
+        *    TEXTN
+        *
+        * as soon as we hit a TEXT line that has no trailing '\', we're done.
+        * this means a command like:
+        *
+        * i\
+        * INSERTME
+        *
+        * is a-ok.
+        *
+        */
+
+       if (editstr[1] != '\\' && (editstr[2] != '\n' || editstr[2] != '\r'))
+               fatalError("bad format in edit expression\n");
+
+       /* store the edit line text */
+       /* make editline big enough to accomodate the extra '\n' we will tack on
+        * to the end */
+       sed_cmd->editline = xmalloc(strlen(&editstr[3]) + 2);
+       strcpy(sed_cmd->editline, &editstr[3]);
+       ptr = sed_cmd->editline;
+
+       /* now we need to go through * and: s/\\[\r\n]$/\n/g on the edit line */
+       while (ptr[idx]) {
+               while (ptr[idx] != '\\' && (ptr[idx+1] != '\n' || ptr[idx+1] != '\r')) {
+                       idx++;
+                       if (!ptr[idx]) {
+                               goto out;
+                       }
+               }
+               /* move the newline over the '\' before it (effectively eats the '\') */
+               memmove(&ptr[idx], &ptr[idx+1], strlen(&ptr[idx+1]));
+               ptr[strlen(ptr)-1] = 0;
+               slashes_eaten++;
+               /* substitue \r for \n if needed */
+               if (ptr[idx] == '\r')
+                       ptr[idx] = '\n';
+       }
+
+out:
+       ptr[idx] = '\n';
+       ptr[idx+1] = 0;
+
+       /* this accounts for discrepancies between the modified string and the
+        * original string passed in to this function */
+       idx += slashes_eaten;
+
+       /* this accounts for the fact that A) we started at index 3, not at index
+        * 0  and B) that we added an extra '\n' at the end (if you think the next
+        * line should read 'idx += 4' remember, arrays are zero-based) */
+
+       idx += 3;
+
+       return idx;
+}
+
+static char *parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
 {
        int idx = 0;
 
@@ -241,6 +370,7 @@ static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
         *            part1 part2  part3
         */
 
+
        /* first part (if present) is an address: either a number or a /regex/ */
        if (isdigit(cmdstr[idx]) || cmdstr[idx] == '/')
                idx = get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
@@ -251,78 +381,55 @@ static void parse_cmd_str(struct sed_cmd *sed_cmd, const char *cmdstr)
 
        /* last part (mandatory) will be a command */
        if (cmdstr[idx] == '\0')
-               exit_sed(1, "sed: missing command\n");
-       if (!strchr("pds", cmdstr[idx])) /* <-- XXX add new commands here */
-               exit_sed(1, "sed: invalid command\n");
+               fatalError("missing command\n");
+       if (!strchr("pdsaic", cmdstr[idx])) /* <-- XXX add new commands here */
+               fatalError("invalid command\n");
        sed_cmd->cmd = cmdstr[idx];
-       /* special-case handling for 's' */
-       if (sed_cmd->cmd == 's') {
-               int oldidx, cflags = REG_NEWLINE;
-               char *match;
-               /* format for substitution is:
-                *    s/match/replace/gI
-                *    |               ||
-                *    mandatory       optional
-                */
-
-               /* verify that we have an 's' followed by a 'slash' */
-               if (cmdstr[++idx] != '/')
-                       exit_sed(1, "sed: bad format in substitution expression\n");
-
-               /* save the match string */
-               oldidx = idx+1;
-               idx = index_of_next_unescaped_slash(idx, cmdstr);
-               if (idx == -1)
-                       exit_sed(1, "sed: bad format in substitution expression\n");
-               match = strdup_substr(cmdstr, oldidx, idx);
-
-               /* save the replacement string */
-               oldidx = idx+1;
-               idx = index_of_next_unescaped_slash(idx, cmdstr);
-               if (idx == -1)
-                       exit_sed(1, "sed: bad format in substitution expression\n");
-               sed_cmd->replace = strdup_substr(cmdstr, oldidx, idx);
 
-               /* process the flags */
-               while (cmdstr[++idx]) {
-                       switch (cmdstr[idx]) {
-                       case 'g':
-                               sed_cmd->sub_g = 1;
-                               break;
-                       case 'I':
-                               cflags |= REG_ICASE;
-                               break;
-                       default:
-                               exit_sed(1, "sed: bad option in substitution expression\n");
-                       }
-               }
-                       
-               /* compile the regex */
-               sed_cmd->sub_match = (regex_t *)xmalloc(sizeof(regex_t));
-               if (bb_regcomp(sed_cmd->sub_match, match, cflags) != 0) {
-                       free(match);
-                       exit_sed(1, NULL);
-               }
-               free(match);
+       /* special-case handling for (s)ubstitution */
+       if (sed_cmd->cmd == 's') {
+               idx += parse_subst_cmd(sed_cmd, &cmdstr[idx]);
+       }
+       /* special-case handling for (a)ppend, (i)nsert, and (c)hange */
+       else if (strchr("aic", cmdstr[idx])) {
+               if (sed_cmd->end_line || sed_cmd->end_match)
+                       fatalError("only a beginning address can be specified for edit commands\n");
+               idx += parse_edit_cmd(sed_cmd, &cmdstr[idx]);
        }
+       /* if it was a single-letter command (such as 'p' or 'd') we need to
+        * increment the index past that command */
+       else
+               idx++;
+
+       /* give back whatever's left over */
+       return (char *)&cmdstr[idx];
 }
 
 static void add_cmd_str(const char *cmdstr)
 {
-       char *my_cmdstr = trim_str(cmdstr);
+       char *mystr = (char *)cmdstr;
 
-       /* if this is a comment, don't even bother */
-       if (my_cmdstr[0] == '#') {
-               free(my_cmdstr);
-               return;
-       }
+       do {
 
-       /* grow the array */
-       sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
-       /* zero new element */
-       memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
-       /* load command string into new array element */
-       parse_cmd_str(&sed_cmds[ncmds-1], my_cmdstr);
+               /* trim leading whitespace and semicolons */
+               memmove(mystr, &mystr[strspn(mystr, "; \n\r\t\v")], strlen(mystr));
+               /* if we ate the whole thing, that means there was just trailing
+                * whitespace or a final / no-op semicolon. either way, get out */
+               if (strlen(mystr) == 0)
+                       return;
+               /* if this is a comment, jump past it and keep going */
+               if (mystr[0] == '#') {
+                       mystr = strpbrk(mystr, ";\n\r");
+                       continue;
+               }
+               /* grow the array */
+               sed_cmds = realloc(sed_cmds, sizeof(struct sed_cmd) * (++ncmds));
+               /* zero new element */
+               memset(&sed_cmds[ncmds-1], 0, sizeof(struct sed_cmd));
+               /* load command string into new array element, get remainder */
+               mystr = parse_cmd_str(&sed_cmds[ncmds-1], mystr);
+
+       } while (mystr && strlen(mystr));
 }
 
 
@@ -330,18 +437,69 @@ static void load_cmd_file(char *filename)
 {
        FILE *cmdfile;
        char *line;
+       char *nextline;
 
        cmdfile = fopen(filename, "r");
        if (cmdfile == NULL)
-               exit_sed(1, strerror(errno));
+               fatalError(strerror(errno));
 
        while ((line = get_line_from_file(cmdfile)) != NULL) {
-               line[strlen(line)-1] = 0; /* eat newline */
+               /* if a line ends with '\' it needs the next line appended to it */
+               while (line[strlen(line)-2] == '\\' &&
+                               (nextline = get_line_from_file(cmdfile)) != NULL) {
+                       line = realloc(line, strlen(line) + strlen(nextline) + 1);
+                       strcat(line, nextline);
+                       free(nextline);
+               }
+               /* eat trailing newline (if any) --if I don't do this, edit commands
+                * (aic) will print an extra newline */
+               if (line[strlen(line)-1] == '\n')
+                       line[strlen(line)-1] = 0;
                add_cmd_str(line);
                free(line);
        }
 }
 
+static int do_subst_command(const struct sed_cmd *sed_cmd, const char *line)
+{
+       int altered = 0;
+
+       /* we only substitute if the substitution 'search' expression matches */
+       if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
+               regmatch_t regmatch;
+               int i;
+               char *ptr = (char *)line;
+
+               while (*ptr) {
+                       /* if we can match the search string... */
+                       if (regexec(sed_cmd->sub_match, ptr, 1, &regmatch, 0) == 0) {
+                               /* print everything before the match, */
+                               for (i = 0; i < regmatch.rm_so; i++)
+                                       fputc(ptr[i], stdout);
+                               /* then print the substitution in its place */
+                               fputs(sed_cmd->replace, stdout);
+                               /* then advance past the match */
+                               ptr += regmatch.rm_eo;
+                               /* and flag that something has changed */
+                               altered++;
+
+                               /* if we're not doing this globally... */
+                               if (!sed_cmd->sub_g)
+                                       break;
+                       }
+                       /* if we COULD NOT match the search string (meaning we've gone past
+                        * all previous instances), get out */
+                       else
+                               break;
+               }
+
+               /* is there anything left to print? */
+               if (*ptr) 
+                       fputs(ptr, stdout);
+       }
+
+       return altered;
+}
 
 static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line) 
 {
@@ -357,43 +515,23 @@ static int do_sed_command(const struct sed_cmd *sed_cmd, const char *line)
                        altered++;
                        break;
 
-               case 's': /* oo, a fun one :-) */
-
-                       /* we only substitute if the substitution 'search' expression matches */
-                       if (regexec(sed_cmd->sub_match, line, 0, NULL, 0) == 0) {
-                               regmatch_t regmatch;
-                               int i;
-                               char *ptr = (char *)line;
-
-                               while (*ptr) {
-                                       /* if we can match the search string... */
-                                       if (regexec(sed_cmd->sub_match, ptr, 1, &regmatch, 0) == 0) {
-                                               /* print everything before the match, */
-                                               for (i = 0; i < regmatch.rm_so; i++)
-                                                       fputc(ptr[i], stdout);
-                                               /* then print the substitution in its place */
-                                               fputs(sed_cmd->replace, stdout);
-                                               /* then advance past the match */
-                                               ptr += regmatch.rm_eo;
-                                               /* and let the calling function know that something
-                                                * has been changed */
-                                               altered++;
-
-                                               /* if we're not doing this globally... */
-                                               if (!sed_cmd->sub_g)
-                                                       break;
-                                       }
-                                       /* if we COULD NOT match the search string (meaning we've gone past
-                                        * all previous instances), get out */
-                                       else
-                                               break;
-                               }
+               case 's':
+                       altered = do_subst_command(sed_cmd, line);
+                       break;
 
-                               /* is there anything left to print? */
-                               if (*ptr) 
-                                       fputs(ptr, stdout);
-                       }
+               case 'a':
+                       fputs(line, stdout);
+                       fputs(sed_cmd->editline, stdout);
+                       altered++;
+                       break;
 
+               case 'i':
+                       fputs(sed_cmd->editline, stdout);
+                       break;
+
+               case 'c':
+                       fputs(sed_cmd->editline, stdout);
+                       altered++;
                        break;
        }
 
@@ -464,15 +602,23 @@ extern int sed_main(int argc, char **argv)
 {
        int opt;
 
-    /* do special-case option parsing */
+       /* do special-case option parsing */
        if (argv[1] && (strcmp(argv[1], "--help") == 0))
                usage(sed_usage);
 
+#if 0
+       /* destroy command strings on exit */
+       if (atexit(destroy_cmd_strs) == -1) {
+               perror("sed");
+               exit(1);
+       }
+#endif
+
        /* do normal option parsing */
        while ((opt = getopt(argc, argv, "Vhne:f:")) > 0) {
                switch (opt) {
                        case 'V':
-                               printf("Print Busybox version here\n");
+                               printf("BusyBox v%s (%s)\n", BB_VER, BB_BT);
                                exit(0);
                                break;
                        case 'h':
@@ -514,7 +660,7 @@ extern int sed_main(int argc, char **argv)
                for (i = optind; i < argc; i++) {
                        file = fopen(argv[i], "r");
                        if (file == NULL) {
-                               fprintf(stderr, "sed: %s: %s\n", argv[i], strerror(errno));
+                               errorMsg("%s: %s\n", argv[i], strerror(errno));
                        } else {
                                process_file(file);
                                fclose(file);
@@ -522,8 +668,5 @@ extern int sed_main(int argc, char **argv)
                }
        }
        
-       exit_sed(0, NULL);
-
-       /* not reached */
        return 0;
 }