1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
|
static const char CVSID[] = "$Id: shell.c,v 1.35 2004/09/02 08:49:56 edg Exp $";
/*******************************************************************************
* *
* shell.c -- Nirvana Editor shell command execution *
* *
* Copyright (C) 1999 Mark Edel *
* *
* This is free software; you can redistribute it and/or modify it under the *
* terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 2 of the License, or (at your option) any later *
* version. In addition, you may distribute version of this program linked to *
* Motif or Open Motif. See README for details. *
* *
* This software is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
* for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* software; if not, write to the Free Software Foundation, Inc., 59 Temple *
* Place, Suite 330, Boston, MA 02111-1307 USA *
* *
* Nirvana Text Editor *
* December, 1993 *
* *
* Written by Mark Edel *
* *
*******************************************************************************/
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include "shell.h"
#include "textBuf.h"
#include "text.h"
#include "nedit.h"
#include "window.h"
#include "preferences.h"
#include "file.h"
#include "macro.h"
#include "interpret.h"
#include "../util/DialogF.h"
#include "../util/misc.h"
#include "menu.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#ifndef __MVS__
#include <sys/param.h>
#endif
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#ifdef notdef
#ifdef IBM
#define NBBY 8
#include <sys/select.h>
#endif
#include <time.h>
#endif
#ifdef __EMX__
#include <process.h>
#endif
#include <Xm/Xm.h>
#include <Xm/MessageB.h>
#include <Xm/Text.h>
#include <Xm/Form.h>
#include <Xm/PushBG.h>
#ifdef HAVE_DEBUG_H
#include "../debug.h"
#endif
/* Tuning parameters */
#define IO_BUF_SIZE 4096 /* size of buffers for collecting cmd output */
#define MAX_OUT_DIALOG_ROWS 30 /* max height of dialog for command output */
#define MAX_OUT_DIALOG_COLS 80 /* max width of dialog for command output */
#define OUTPUT_FLUSH_FREQ 1000 /* how often (msec) to flush output buffers
when process is taking too long */
#define BANNER_WAIT_TIME 6000 /* how long to wait (msec) before putting up
Shell Command Executing... banner */
/* flags for issueCommand */
#define ACCUMULATE 1
#define ERROR_DIALOGS 2
#define REPLACE_SELECTION 4
#define RELOAD_FILE_AFTER 8
#define OUTPUT_TO_DIALOG 16
#define OUTPUT_TO_STRING 32
/* element of a buffer list for collecting output from shell processes */
typedef struct bufElem {
struct bufElem *next;
int length;
char contents[IO_BUF_SIZE];
} buffer;
/* data attached to window during shell command execution with
information for controling and communicating with the process */
typedef struct {
int flags;
int stdinFD, stdoutFD, stderrFD;
pid_t childPid;
XtInputId stdinInputID, stdoutInputID, stderrInputID;
buffer *outBufs, *errBufs;
char *input;
char *inPtr;
Widget textW;
int leftPos, rightPos;
int inLength;
XtIntervalId bannerTimeoutID, flushTimeoutID;
char bannerIsUp;
char fromMacro;
} shellCmdInfo;
static void issueCommand(WindowInfo *window, const char *command, char *input,
int inputLen, int flags, Widget textW, int replaceLeft,
int replaceRight, int fromMacro);
static void stdoutReadProc(XtPointer clientData, int *source, XtInputId *id);
static void stderrReadProc(XtPointer clientData, int *source, XtInputId *id);
static void stdinWriteProc(XtPointer clientData, int *source, XtInputId *id);
static void finishCmdExecution(WindowInfo *window, int terminatedOnError);
static pid_t forkCommand(Widget parent, const char *command, const char *cmdDir,
int *stdinFD, int *stdoutFD, int *stderrFD);
static void addOutput(buffer **bufList, buffer *buf);
static char *coalesceOutput(buffer **bufList, int *length);
static void freeBufList(buffer **bufList);
static void removeTrailingNewlines(char *string);
static void createOutputDialog(Widget parent, char *text);
static void destroyOutDialogCB(Widget w, XtPointer callback, XtPointer closure);
static void measureText(char *text, int wrapWidth, int *rows, int *cols,
int *wrapped);
static void truncateString(char *string, int length);
static void bannerTimeoutProc(XtPointer clientData, XtIntervalId *id);
static void flushTimeoutProc(XtPointer clientData, XtIntervalId *id);
static void safeBufReplace(textBuffer *buf, int *start, int *end,
const char *text);
static char *shellCommandSubstitutes(const char *inStr, const char *fileStr,
const char *lineStr);
static int shellSubstituter(char *outStr, const char *inStr, const char *fileStr,
const char *lineStr, int outLen, int predictOnly);
/*
** Filter the current selection through shell command "command". The selection
** is removed, and replaced by the output from the command execution. Failed
** command status and output to stderr are presented in dialog form.
*/
void FilterSelection(WindowInfo *window, const char *command, int fromMacro)
{
int left, right, textLen;
char *text;
/* Can't do two shell commands at once in the same window */
if (window->shellCmdData != NULL) {
XBell(TheDisplay, 0);
return;
}
/* Get the selection and the range in character positions that it
occupies. Beep and return if no selection */
text = BufGetSelectionText(window->buffer);
if (*text == '\0') {
XtFree(text);
XBell(TheDisplay, 0);
return;
}
textLen = strlen(text);
BufUnsubstituteNullChars(text, window->buffer);
left = window->buffer->primary.start;
right = window->buffer->primary.end;
/* Issue the command and collect its output */
issueCommand(window, command, text, textLen, ACCUMULATE | ERROR_DIALOGS |
REPLACE_SELECTION, window->lastFocus, left, right, fromMacro);
}
/*
** Execute shell command "command", depositing the result at the current
** insert position or in the current selection if the window has a
** selection.
*/
void ExecShellCommand(WindowInfo *window, const char *command, int fromMacro)
{
int left, right, flags = 0;
char *subsCommand, fullName[MAXPATHLEN];
int pos, line, column;
char lineNumber[11];
/* Can't do two shell commands at once in the same window */
if (window->shellCmdData != NULL) {
XBell(TheDisplay, 0);
return;
}
/* get the selection or the insert position */
pos = TextGetCursorPos(window->lastFocus);
if (GetSimpleSelection(window->buffer, &left, &right))
flags = ACCUMULATE | REPLACE_SELECTION;
else
left = right = pos;
/* Substitute the current file name for % and the current line number
for # in the shell command */
strcpy(fullName, window->path);
strcat(fullName, window->filename);
TextPosToLineAndCol(window->lastFocus, pos, &line, &column);
sprintf(lineNumber, "%d", line);
subsCommand = shellCommandSubstitutes(command, fullName, lineNumber);
if (subsCommand == NULL)
{
DialogF(DF_ERR, window->shell, 1, "Shell Command",
"Shell command is too long due to\n"
"filename substitutions with '%%' or\n"
"line number substitutions with '#'", "OK");
return;
}
/* issue the command */
issueCommand(window, subsCommand, NULL, 0, flags, window->lastFocus, left,
right, fromMacro);
free(subsCommand);
}
/*
** Execute shell command "command", on input string "input", depositing the
** in a macro string (via a call back to ReturnShellCommandOutput).
*/
void ShellCmdToMacroString(WindowInfo *window, const char *command,
const char *input)
{
char *inputCopy;
/* Make a copy of the input string for issueCommand to hold and free
upon completion */
inputCopy = *input == '\0' ? NULL : XtNewString(input);
/* fork the command and begin processing input/output */
issueCommand(window, command, inputCopy, strlen(input),
ACCUMULATE | OUTPUT_TO_STRING, NULL, 0, 0, True);
}
/*
** Execute the line of text where the the insertion cursor is positioned
** as a shell command.
*/
void ExecCursorLine(WindowInfo *window, int fromMacro)
{
char *cmdText;
int left, right, insertPos;
char *subsCommand, fullName[MAXPATHLEN];
int pos, line, column;
char lineNumber[11];
/* Can't do two shell commands at once in the same window */
if (window->shellCmdData != NULL) {
XBell(TheDisplay, 0);
return;
}
/* get all of the text on the line with the insert position */
pos = TextGetCursorPos(window->lastFocus);
if (!GetSimpleSelection(window->buffer, &left, &right)) {
left = right = pos;
left = BufStartOfLine(window->buffer, left);
right = BufEndOfLine(window->buffer, right);
insertPos = right;
} else
insertPos = BufEndOfLine(window->buffer, right);
cmdText = BufGetRange(window->buffer, left, right);
BufUnsubstituteNullChars(cmdText, window->buffer);
/* insert a newline after the entire line */
BufInsert(window->buffer, insertPos, "\n");
/* Substitute the current file name for % and the current line number
for # in the shell command */
strcpy(fullName, window->path);
strcat(fullName, window->filename);
TextPosToLineAndCol(window->lastFocus, pos, &line, &column);
sprintf(lineNumber, "%d", line);
subsCommand = shellCommandSubstitutes(cmdText, fullName, lineNumber);
if (subsCommand == NULL)
{
DialogF(DF_ERR, window->shell, 1, "Shell Command",
"Shell command is too long due to\n"
"filename substitutions with '%%' or\n"
"line number substitutions with '#'", "OK");
return;
}
/* issue the command */
issueCommand(window, subsCommand, NULL, 0, 0, window->lastFocus, insertPos+1,
insertPos+1, fromMacro);
free(subsCommand);
XtFree(cmdText);
}
/*
** Do a shell command, with the options allowed to users (input source,
** output destination, save first and load after) in the shell commands
** menu.
*/
void DoShellMenuCmd(WindowInfo *window, const char *command,
int input, int output,
int outputReplacesInput, int saveFirst, int loadAfter, int fromMacro)
{
int flags = 0;
char *text;
char *subsCommand, fullName[MAXPATHLEN];
int left, right, textLen;
int pos, line, column;
char lineNumber[11];
WindowInfo *inWindow = window;
Widget outWidget;
/* Can't do two shell commands at once in the same window */
if (window->shellCmdData != NULL) {
XBell(TheDisplay, 0);
return;
}
/* Substitute the current file name for % and the current line number
for # in the shell command */
strcpy(fullName, window->path);
strcat(fullName, window->filename);
pos = TextGetCursorPos(window->lastFocus);
TextPosToLineAndCol(window->lastFocus, pos, &line, &column);
sprintf(lineNumber, "%d", line);
subsCommand = shellCommandSubstitutes(command, fullName, lineNumber);
if (subsCommand == NULL)
{
DialogF(DF_ERR, window->shell, 1, "Shell Command",
"Shell command is too long due to\n"
"filename substitutions with '%%' or\n"
"line number substitutions with '#'", "OK");
return;
}
/* Get the command input as a text string. If there is input, errors
shouldn't be mixed in with output, so set flags to ERROR_DIALOGS */
if (input == FROM_SELECTION) {
text = BufGetSelectionText(window->buffer);
if (*text == '\0') {
XtFree(text);
free(subsCommand);
XBell(TheDisplay, 0);
return;
}
flags |= ACCUMULATE | ERROR_DIALOGS;
} else if (input == FROM_WINDOW) {
text = BufGetAll(window->buffer);
flags |= ACCUMULATE | ERROR_DIALOGS;
} else if (input == FROM_EITHER) {
text = BufGetSelectionText(window->buffer);
if (*text == '\0') {
XtFree(text);
text = BufGetAll(window->buffer);
}
flags |= ACCUMULATE | ERROR_DIALOGS;
} else /* FROM_NONE */
text = NULL;
/* If the buffer was substituting another character for ascii-nuls,
put the nuls back in before exporting the text */
if (text != NULL) {
textLen = strlen(text);
BufUnsubstituteNullChars(text, window->buffer);
} else
textLen = 0;
/* Assign the output destination. If output is to a new window,
create it, and run the command from it instead of the current
one, to free the current one from waiting for lengthy execution */
if (output == TO_DIALOG) {
outWidget = NULL;
flags |= OUTPUT_TO_DIALOG;
left = right = 0;
} else if (output == TO_NEW_WINDOW) {
EditNewFile(GetPrefOpenInTab()?inWindow:NULL, NULL, False, NULL, window->path);
outWidget = WindowList->textArea;
inWindow = WindowList;
left = right = 0;
CheckCloseDim();
} else { /* TO_SAME_WINDOW */
outWidget = window->lastFocus;
if (outputReplacesInput && input != FROM_NONE) {
if (input == FROM_WINDOW) {
left = 0;
right = window->buffer->length;
} else if (input == FROM_SELECTION) {
GetSimpleSelection(window->buffer, &left, &right);
flags |= ACCUMULATE | REPLACE_SELECTION;
} else if (input == FROM_EITHER) {
if (GetSimpleSelection(window->buffer, &left, &right))
flags |= ACCUMULATE | REPLACE_SELECTION;
else {
left = 0;
right = window->buffer->length;
}
}
} else {
if (GetSimpleSelection(window->buffer, &left, &right))
flags |= ACCUMULATE | REPLACE_SELECTION;
else
left = right = TextGetCursorPos(window->lastFocus);
}
}
/* If the command requires the file be saved first, save it */
if (saveFirst) {
if (!SaveWindow(window)) {
if (input != FROM_NONE)
XtFree(text);
free(subsCommand);
return;
}
}
/* If the command requires the file to be reloaded after execution, set
a flag for issueCommand to deal with it when execution is complete */
if (loadAfter)
flags |= RELOAD_FILE_AFTER;
/* issue the command */
issueCommand(inWindow, subsCommand, text, textLen, flags, outWidget, left,
right, fromMacro);
free(subsCommand);
}
/*
** Cancel the shell command in progress
*/
void AbortShellCommand(WindowInfo *window)
{
shellCmdInfo *cmdData = window->shellCmdData;
if (cmdData == NULL)
return;
kill(- cmdData->childPid, SIGTERM);
finishCmdExecution(window, True);
}
/*
** Issue a shell command and feed it the string "input". Output can be
** directed either to text widget "textW" where it replaces the text between
** the positions "replaceLeft" and "replaceRight", to a separate pop-up dialog
** (OUTPUT_TO_DIALOG), or to a macro-language string (OUTPUT_TO_STRING). If
** "input" is NULL, no input is fed to the process. If an input string is
** provided, it is freed when the command completes. Flags:
**
** ACCUMULATE Causes output from the command to be saved up until
** the command completes.
** ERROR_DIALOGS Presents stderr output separately in popup a dialog,
** and also reports failed exit status as a popup dialog
** including the command output.
** REPLACE_SELECTION Causes output to replace the selection in textW.
** RELOAD_FILE_AFTER Causes the file to be completely reloaded after the
** command completes.
** OUTPUT_TO_DIALOG Send output to a pop-up dialog instead of textW
** OUTPUT_TO_STRING Output to a macro-language string instead of a text
** widget or dialog.
**
** REPLACE_SELECTION, ERROR_DIALOGS, and OUTPUT_TO_STRING can only be used
** along with ACCUMULATE (these operations can't be done incrementally).
*/
static void issueCommand(WindowInfo *window, const char *command, char *input,
int inputLen, int flags, Widget textW, int replaceLeft,
int replaceRight, int fromMacro)
{
int stdinFD, stdoutFD, stderrFD;
XtAppContext context = XtWidgetToApplicationContext(window->shell);
shellCmdInfo *cmdData;
pid_t childPid;
/* verify consistency of input parameters */
if ((flags & ERROR_DIALOGS || flags & REPLACE_SELECTION ||
flags & OUTPUT_TO_STRING) && !(flags & ACCUMULATE))
return;
/* a shell command called from a macro must be executed in the same
window as the macro, regardless of where the output is directed,
so the user can cancel them as a unit */
if (fromMacro)
window = MacroRunWindow();
/* put up a watch cursor over the waiting window */
if (!fromMacro)
BeginWait(window->shell);
/* enable the cancel menu item */
if (!fromMacro)
SetSensitive(window, window->cancelShellItem, True);
/* fork the subprocess and issue the command */
childPid = forkCommand(window->shell, command, window->path, &stdinFD,
&stdoutFD, (flags & ERROR_DIALOGS) ? &stderrFD : NULL);
/* set the pipes connected to the process for non-blocking i/o */
if (fcntl(stdinFD, F_SETFL, O_NONBLOCK) < 0)
perror("NEdit: Internal error (fcntl)");
if (fcntl(stdoutFD, F_SETFL, O_NONBLOCK) < 0)
perror("NEdit: Internal error (fcntl1)");
if (flags & ERROR_DIALOGS) {
if (fcntl(stderrFD, F_SETFL, O_NONBLOCK) < 0)
perror("NEdit: Internal error (fcntl2)");
}
/* if there's nothing to write to the process' stdin, close it now */
if (input == NULL)
close(stdinFD);
/* Create a data structure for passing process information around
amongst the callback routines which will process i/o and completion */
cmdData = (shellCmdInfo *)XtMalloc(sizeof(shellCmdInfo));
window->shellCmdData = cmdData;
cmdData->flags = flags;
cmdData->stdinFD = stdinFD;
cmdData->stdoutFD = stdoutFD;
cmdData->stderrFD = stderrFD;
cmdData->childPid = childPid;
cmdData->outBufs = NULL;
cmdData->errBufs = NULL;
cmdData->input = input;
cmdData->inPtr = input;
cmdData->textW = textW;
cmdData->bannerIsUp = False;
cmdData->fromMacro = fromMacro;
cmdData->leftPos = replaceLeft;
cmdData->rightPos = replaceRight;
cmdData->inLength = inputLen;
/* Set up timer proc for putting up banner when process takes too long */
if (fromMacro)
cmdData->bannerTimeoutID = 0;
else
cmdData->bannerTimeoutID = XtAppAddTimeOut(context, BANNER_WAIT_TIME,
bannerTimeoutProc, window);
/* Set up timer proc for flushing output buffers periodically */
if ((flags & ACCUMULATE) || textW == NULL)
cmdData->flushTimeoutID = 0;
else
cmdData->flushTimeoutID = XtAppAddTimeOut(context, OUTPUT_FLUSH_FREQ,
flushTimeoutProc, window);
/* set up callbacks for activity on the file descriptors */
cmdData->stdoutInputID = XtAppAddInput(context, stdoutFD,
(XtPointer)XtInputReadMask, stdoutReadProc, window);
if (input != NULL)
cmdData->stdinInputID = XtAppAddInput(context, stdinFD,
(XtPointer)XtInputWriteMask, stdinWriteProc, window);
else
cmdData->stdinInputID = 0;
if (flags & ERROR_DIALOGS)
cmdData->stderrInputID = XtAppAddInput(context, stderrFD,
(XtPointer)XtInputReadMask, stderrReadProc, window);
else
cmdData->stderrInputID = 0;
/* If this was called from a macro, preempt the macro untill shell
command completes */
if (fromMacro)
PreemptMacro();
}
/*
** Called when the shell sub-process stdout stream has data. Reads data into
** the "outBufs" buffer chain in the window->shellCommandData data structure.
*/
static void stdoutReadProc(XtPointer clientData, int *source, XtInputId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
shellCmdInfo *cmdData = window->shellCmdData;
buffer *buf;
int nRead;
/* read from the process' stdout stream */
buf = (buffer *)XtMalloc(sizeof(buffer));
nRead = read(cmdData->stdoutFD, buf->contents, IO_BUF_SIZE);
/* error in read */
if (nRead == -1) { /* error */
if (errno != EWOULDBLOCK && errno != EAGAIN) {
perror("NEdit: Error reading shell command output");
XtFree((char *)buf);
finishCmdExecution(window, True);
}
return;
}
/* end of data. If the stderr stream is done too, execution of the
shell process is complete, and we can display the results */
if (nRead == 0) {
XtFree((char *)buf);
XtRemoveInput(cmdData->stdoutInputID);
cmdData->stdoutInputID = 0;
if (cmdData->stderrInputID == 0)
finishCmdExecution(window, False);
return;
}
/* characters were read successfully, add buf to linked list of buffers */
buf->length = nRead;
addOutput(&cmdData->outBufs, buf);
}
/*
** Called when the shell sub-process stderr stream has data. Reads data into
** the "errBufs" buffer chain in the window->shellCommandData data structure.
*/
static void stderrReadProc(XtPointer clientData, int *source, XtInputId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
shellCmdInfo *cmdData = window->shellCmdData;
buffer *buf;
int nRead;
/* read from the process' stderr stream */
buf = (buffer *)XtMalloc(sizeof(buffer));
nRead = read(cmdData->stderrFD, buf->contents, IO_BUF_SIZE);
/* error in read */
if (nRead == -1) {
if (errno != EWOULDBLOCK && errno != EAGAIN) {
perror("NEdit: Error reading shell command error stream");
XtFree((char *)buf);
finishCmdExecution(window, True);
}
return;
}
/* end of data. If the stdout stream is done too, execution of the
shell process is complete, and we can display the results */
if (nRead == 0) {
XtFree((char *)buf);
XtRemoveInput(cmdData->stderrInputID);
cmdData->stderrInputID = 0;
if (cmdData->stdoutInputID == 0)
finishCmdExecution(window, False);
return;
}
/* characters were read successfully, add buf to linked list of buffers */
buf->length = nRead;
addOutput(&cmdData->errBufs, buf);
}
/*
** Called when the shell sub-process stdin stream is ready for input. Writes
** data from the "input" text string passed to issueCommand.
*/
static void stdinWriteProc(XtPointer clientData, int *source, XtInputId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
shellCmdInfo *cmdData = window->shellCmdData;
int nWritten;
nWritten = write(cmdData->stdinFD, cmdData->inPtr, cmdData->inLength);
if (nWritten == -1) {
if (errno == EPIPE) {
/* Just shut off input to broken pipes. User is likely feeding
it to a command which does not take input */
XtRemoveInput(cmdData->stdinInputID);
cmdData->stdinInputID = 0;
close(cmdData->stdinFD);
cmdData->inPtr = NULL;
} else if (errno != EWOULDBLOCK && errno != EAGAIN) {
perror("NEdit: Write to shell command failed");
finishCmdExecution(window, True);
}
} else {
cmdData->inPtr += nWritten;
cmdData->inLength -= nWritten;
if (cmdData->inLength <= 0) {
XtRemoveInput(cmdData->stdinInputID);
cmdData->stdinInputID = 0;
close(cmdData->stdinFD);
cmdData->inPtr = NULL;
}
}
}
/*
** Timer proc for putting up the "Shell Command in Progress" banner if
** the process is taking too long.
*/
static void bannerTimeoutProc(XtPointer clientData, XtIntervalId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
shellCmdInfo *cmdData = window->shellCmdData;
cmdData->bannerIsUp = True;
SetModeMessage(window,
"Shell Command in Progress -- Press Ctrl+. to Cancel");
cmdData->bannerTimeoutID = 0;
}
/*
** Buffer replacement wrapper routine to be used for inserting output from
** a command into the buffer, which takes into account that the buffer may
** have been shrunken by the user (eg, by Undo). If necessary, the starting
** and ending positions (part of the state of the command) are corrected.
*/
static void safeBufReplace(textBuffer *buf, int *start, int *end,
const char *text)
{
if (*start > buf->length)
*start = buf->length;
if (*end > buf->length)
*end = buf->length;
BufReplace(buf, *start, *end, text);
}
/*
** Timer proc for flushing output buffers periodically when the process
** takes too long.
*/
static void flushTimeoutProc(XtPointer clientData, XtIntervalId *id)
{
WindowInfo *window = (WindowInfo *)clientData;
shellCmdInfo *cmdData = window->shellCmdData;
textBuffer *buf = TextGetBuffer(cmdData->textW);
int len;
char *outText;
/* shouldn't happen, but it would be bad if it did */
if (cmdData->textW == NULL)
return;
outText = coalesceOutput(&cmdData->outBufs, &len);
if (len != 0) {
if (BufSubstituteNullChars(outText, len, buf)) {
safeBufReplace(buf, &cmdData->leftPos, &cmdData->rightPos, outText);
TextSetCursorPos(cmdData->textW, cmdData->leftPos+strlen(outText));
cmdData->leftPos += len;
cmdData->rightPos = cmdData->leftPos;
} else
fprintf(stderr, "NEdit: Too much binary data\n");
}
XtFree(outText);
/* re-establish the timer proc (this routine) to continue processing */
cmdData->flushTimeoutID = XtAppAddTimeOut(
XtWidgetToApplicationContext(window->shell),
OUTPUT_FLUSH_FREQ, flushTimeoutProc, clientData);
}
/*
** Clean up after the execution of a shell command sub-process and present
** the output/errors to the user as requested in the initial issueCommand
** call. If "terminatedOnError" is true, don't bother trying to read the
** output, just close the i/o descriptors, free the memory, and restore the
** user interface state.
*/
static void finishCmdExecution(WindowInfo *window, int terminatedOnError)
{
shellCmdInfo *cmdData = window->shellCmdData;
textBuffer *buf;
int status, failure, errorReport, reselectStart, outTextLen, errTextLen;
int resp, cancel = False, fromMacro = cmdData->fromMacro;
char *outText, *errText = NULL;
/* Cancel any pending i/o on the file descriptors */
if (cmdData->stdoutInputID != 0)
XtRemoveInput(cmdData->stdoutInputID);
if (cmdData->stdinInputID != 0)
XtRemoveInput(cmdData->stdinInputID);
if (cmdData->stderrInputID != 0)
XtRemoveInput(cmdData->stderrInputID);
/* Close any file descriptors remaining open */
close(cmdData->stdoutFD);
if (cmdData->flags & ERROR_DIALOGS)
close(cmdData->stderrFD);
if (cmdData->inPtr != NULL)
close(cmdData->stdinFD);
/* Free the provided input text */
if (cmdData->input != NULL)
XtFree(cmdData->input);
/* Cancel pending timeouts */
if (cmdData->flushTimeoutID != 0)
XtRemoveTimeOut(cmdData->flushTimeoutID);
if (cmdData->bannerTimeoutID != 0)
XtRemoveTimeOut(cmdData->bannerTimeoutID);
/* Clean up waiting-for-shell-command-to-complete mode */
if (!cmdData->fromMacro) {
EndWait(window->shell);
SetSensitive(window, window->cancelShellItem, False);
if (cmdData->bannerIsUp)
ClearModeMessage(window);
}
/* If the process was killed or became inaccessable, give up */
if (terminatedOnError) {
freeBufList(&cmdData->outBufs);
freeBufList(&cmdData->errBufs);
waitpid(cmdData->childPid, &status, 0);
goto cmdDone;
}
/* Assemble the output from the process' stderr and stdout streams into
null terminated strings, and free the buffer lists used to collect it */
outText = coalesceOutput(&cmdData->outBufs, &outTextLen);
if (cmdData->flags & ERROR_DIALOGS)
errText = coalesceOutput(&cmdData->errBufs, &errTextLen);
/* Wait for the child process to complete and get its return status */
waitpid(cmdData->childPid, &status, 0);
/* Present error and stderr-information dialogs. If a command returned
error output, or if the process' exit status indicated failure,
present the information to the user. */
if (cmdData->flags & ERROR_DIALOGS)
{
failure = WIFEXITED(status) && WEXITSTATUS(status) != 0;
errorReport = *errText != '\0';
if (failure && errorReport)
{
removeTrailingNewlines(errText);
truncateString(errText, DF_MAX_MSG_LENGTH);
resp = DialogF(DF_WARN, window->shell, 2, "Warning", "%s", "Cancel",
"Proceed", errText);
cancel = resp == 1;
} else if (failure)
{
truncateString(outText, DF_MAX_MSG_LENGTH-70);
resp = DialogF(DF_WARN, window->shell, 2, "Command Failure",
"Command reported failed exit status.\n"
"Output from command:\n%s", "Cancel", "Proceed", outText);
cancel = resp == 1;
} else if (errorReport)
{
removeTrailingNewlines(errText);
truncateString(errText, DF_MAX_MSG_LENGTH);
resp = DialogF(DF_INF, window->shell, 2, "Information", "%s",
"Proceed", "Cancel", errText);
cancel = resp == 2;
}
XtFree(errText);
if (cancel)
{
XtFree(outText);
goto cmdDone;
}
}
/* If output is to a dialog, present the dialog. Otherwise insert the
(remaining) output in the text widget as requested, and move the
insert point to the end */
if (cmdData->flags & OUTPUT_TO_DIALOG) {
removeTrailingNewlines(outText);
if (*outText != '\0')
createOutputDialog(window->shell, outText);
} else if (cmdData->flags & OUTPUT_TO_STRING) {
ReturnShellCommandOutput(window,outText, WEXITSTATUS(status));
} else {
buf = TextGetBuffer(cmdData->textW);
if (!BufSubstituteNullChars(outText, outTextLen, buf)) {
fprintf(stderr,"NEdit: Too much binary data in shell cmd output\n");
outText[0] = '\0';
}
if (cmdData->flags & REPLACE_SELECTION) {
reselectStart = buf->primary.rectangular ? -1 : buf->primary.start;
BufReplaceSelected(buf, outText);
TextSetCursorPos(cmdData->textW, buf->cursorPosHint);
if (reselectStart != -1)
BufSelect(buf, reselectStart, reselectStart + strlen(outText));
} else {
safeBufReplace(buf, &cmdData->leftPos, &cmdData->rightPos, outText);
TextSetCursorPos(cmdData->textW, cmdData->leftPos+strlen(outText));
}
}
/* If the command requires the file to be reloaded afterward, reload it */
if (cmdData->flags & RELOAD_FILE_AFTER)
RevertToSaved(window);
/* Command is complete, free data structure and continue macro execution */
XtFree(outText);
cmdDone:
XtFree((char *)cmdData);
window->shellCmdData = NULL;
if (fromMacro)
ResumeMacroExecution(window);
}
/*
** Fork a subprocess to execute a command, return file descriptors for pipes
** connected to the subprocess' stdin, stdout, and stderr streams. cmdDir
** sets the default directory for the subprocess. If stderrFD is passed as
** NULL, the pipe represented by stdoutFD is connected to both stdin and
** stderr. The function value returns the pid of the new subprocess, or -1
** if an error occured.
*/
static pid_t forkCommand(Widget parent, const char *command, const char *cmdDir,
int *stdinFD, int *stdoutFD, int *stderrFD)
{
int childStdoutFD, childStdinFD, childStderrFD, pipeFDs[2];
int dupFD;
pid_t childPid;
/* Ignore SIGPIPE signals generated when user attempts to provide
input for commands which don't take input */
signal(SIGPIPE, SIG_IGN);
/* Create pipes to communicate with the sub process. One end of each is
returned to the caller, the other half is spliced to stdin, stdout
and stderr in the child process */
if (pipe(pipeFDs) != 0) {
perror("NEdit: Internal error (opening stdout pipe)");
return -1;
}
*stdoutFD = pipeFDs[0];
childStdoutFD = pipeFDs[1];
if (pipe(pipeFDs) != 0) {
perror("NEdit: Internal error (opening stdin pipe)");
return -1;
}
*stdinFD = pipeFDs[1];
childStdinFD = pipeFDs[0];
if (stderrFD == NULL)
childStderrFD = childStdoutFD;
else {
if (pipe(pipeFDs) != 0) {
perror("NEdit: Internal error (opening stdin pipe)");
return -1;
}
*stderrFD = pipeFDs[0];
childStderrFD = pipeFDs[1];
}
/* Fork the process */
childPid = fork();
/*
** Child process context (fork returned 0), clean up the
** child ends of the pipes and execute the command
*/
if (0 == childPid) {
/* close the parent end of the pipes in the child process */
close(*stdinFD);
close(*stdoutFD);
if (stderrFD != NULL)
close(*stderrFD);
/* close current stdin, stdout, and stderr file descriptors before
substituting pipes */
close(fileno(stdin));
close(fileno(stdout));
close(fileno(stderr));
/* duplicate the child ends of the pipes to have the same numbers
as stdout & stderr, so it can substitute for stdout & stderr */
dupFD = dup2(childStdinFD, fileno(stdin));
if (dupFD == -1)
perror("dup of stdin failed");
dupFD = dup2(childStdoutFD, fileno(stdout));
if (dupFD == -1)
perror("dup of stdout failed");
dupFD = dup2(childStderrFD, fileno(stderr));
if (dupFD == -1)
perror("dup of stderr failed");
/* now close the original child end of the pipes
(we now have the 0, 1 and 2 descriptors in their place) */
close(childStdinFD);
close(childStdoutFD);
close(childStderrFD);
/* make this process the leader of a new process group, so the sub
processes can be killed, if necessary, with a killpg call */
#ifndef __EMX__ /* OS/2 doesn't have this */
setsid();
#endif
/* change the current working directory to the directory of the current
file. */
if(cmdDir[0] != 0)
if(chdir(cmdDir) == -1)
perror("chdir to directory of current file failed");
/* execute the command using the shell specified by preferences */
execl(GetPrefShell(), GetPrefShell(), "-c", command, (char *)0);
/* if we reach here, execl failed */
fprintf(stderr, "Error starting shell: %s\n", GetPrefShell());
exit(EXIT_FAILURE);
}
/* Parent process context, check if fork succeeded */
if (childPid == -1)
{
DialogF(DF_ERR, parent, 1, "Shell Command",
"Error starting shell command process\n(fork failed)",
"OK");
}
/* close the child ends of the pipes */
close(childStdinFD);
close(childStdoutFD);
if (stderrFD != NULL)
close(childStderrFD);
return childPid;
}
/*
** Add a buffer full of output to a buffer list
*/
static void addOutput(buffer **bufList, buffer *buf)
{
buf->next = *bufList;
*bufList = buf;
}
/*
** coalesce the contents of a list of buffers into a contiguous memory block,
** freeing the memory occupied by the buffer list. Returns the memory block
** as the function result, and its length as parameter "length".
*/
static char *coalesceOutput(buffer **bufList, int *outLength)
{
buffer *buf, *rBufList = NULL;
char *outBuf, *outPtr, *p;
int i, length = 0;
/* find the total length of data read */
for (buf=*bufList; buf!=NULL; buf=buf->next)
length += buf->length;
/* allocate contiguous memory for returning data */
outBuf = XtMalloc(length+1);
/* reverse the buffer list */
while (*bufList != NULL) {
buf = *bufList;
*bufList = buf->next;
buf->next = rBufList;
rBufList = buf;
}
/* copy the buffers into the output buffer */
outPtr = outBuf;
for (buf=rBufList; buf!=NULL; buf=buf->next) {
p = buf->contents;
for (i=0; i<buf->length; i++)
*outPtr++ = *p++;
}
/* terminate with a null */
*outPtr = '\0';
/* free the buffer list */
freeBufList(&rBufList);
*outLength = outPtr - outBuf;
return outBuf;
}
static void freeBufList(buffer **bufList)
{
buffer *buf;
while (*bufList != NULL) {
buf = *bufList;
*bufList = buf->next;
XtFree((char *)buf);
}
}
/*
** Remove trailing newlines from a string by substituting nulls
*/
static void removeTrailingNewlines(char *string)
{
char *endPtr = &string[strlen(string)-1];
while (endPtr >= string && *endPtr == '\n')
*endPtr-- = '\0';
}
/*
** Create a dialog for the output of a shell command. The dialog lives until
** the user presses the Dismiss button, and is then destroyed
*/
static void createOutputDialog(Widget parent, char *text)
{
Arg al[50];
int ac, rows, cols, hasScrollBar, wrapped;
Widget form, textW, button;
XmString st1;
/* measure the width and height of the text to determine size for dialog */
measureText(text, MAX_OUT_DIALOG_COLS, &rows, &cols, &wrapped);
if (rows > MAX_OUT_DIALOG_ROWS) {
rows = MAX_OUT_DIALOG_ROWS;
hasScrollBar = True;
} else
hasScrollBar = False;
if (cols > MAX_OUT_DIALOG_COLS)
cols = MAX_OUT_DIALOG_COLS;
if (cols == 0)
cols = 1;
/* Without completely emulating Motif's wrapping algorithm, we can't
be sure that we haven't underestimated the number of lines in case
a line has wrapped, so let's assume that some lines could be obscured
*/
if (wrapped)
hasScrollBar = True;
ac = 0;
form = CreateFormDialog(parent, "shellOutForm", al, ac);
ac = 0;
XtSetArg(al[ac], XmNlabelString, st1=MKSTRING("OK")); ac++;
XtSetArg(al[ac], XmNmarginWidth, BUTTON_WIDTH_MARGIN); ac++;
XtSetArg(al[ac], XmNhighlightThickness, 0); ac++;
XtSetArg(al[ac], XmNbottomAttachment, XmATTACH_FORM); ac++;
XtSetArg(al[ac], XmNtopAttachment, XmATTACH_NONE); ac++;
button = XmCreatePushButtonGadget(form, "ok", al, ac);
XtManageChild(button);
XtVaSetValues(form, XmNdefaultButton, button, NULL);
XtVaSetValues(form, XmNcancelButton, button, NULL);
XmStringFree(st1);
XtAddCallback(button, XmNactivateCallback, destroyOutDialogCB,
XtParent(form));
ac = 0;
XtSetArg(al[ac], XmNrows, rows); ac++;
XtSetArg(al[ac], XmNcolumns, cols); ac++;
XtSetArg(al[ac], XmNresizeHeight, False); ac++;
XtSetArg(al[ac], XmNtraversalOn, False); ac++;
XtSetArg(al[ac], XmNwordWrap, True); ac++;
XtSetArg(al[ac], XmNscrollHorizontal, False); ac++;
XtSetArg(al[ac], XmNscrollVertical, hasScrollBar); ac++;
XtSetArg(al[ac], XmNhighlightThickness, 0); ac++;
XtSetArg(al[ac], XmNspacing, 0); ac++;
XtSetArg(al[ac], XmNeditMode, XmMULTI_LINE_EDIT); ac++;
XtSetArg(al[ac], XmNeditable, False); ac++;
XtSetArg(al[ac], XmNvalue, text); ac++;
XtSetArg(al[ac], XmNtopAttachment, XmATTACH_FORM); ac++;
XtSetArg(al[ac], XmNleftAttachment, XmATTACH_FORM); ac++;
XtSetArg(al[ac], XmNbottomAttachment, XmATTACH_WIDGET); ac++;
XtSetArg(al[ac], XmNrightAttachment, XmATTACH_FORM); ac++;
XtSetArg(al[ac], XmNbottomWidget, button); ac++;
textW = XmCreateScrolledText(form, "outText", al, ac);
AddMouseWheelSupport(textW);
XtManageChild(textW);
XtVaSetValues(XtParent(form), XmNtitle, "Output from Command", NULL);
ManageDialogCenteredOnPointer(form);
}
/*
** Dispose of the command output dialog when user presses Dismiss button
*/
static void destroyOutDialogCB(Widget w, XtPointer callback, XtPointer closure)
{
XtDestroyWidget((Widget)callback);
}
/*
** Measure the width and height of a string of text. Assumes 8 character
** tabs. wrapWidth specifies a number of columns at which text wraps.
*/
static void measureText(char *text, int wrapWidth, int *rows, int *cols,
int *wrapped)
{
int maxCols = 0, line = 1, col = 0, wrapCol;
char *c;
*wrapped = 0;
for (c=text; *c!='\0'; c++) {
if (*c=='\n') {
line++;
col = 0;
continue;
}
if (*c == '\t') {
col += 8 - (col % 8);
wrapCol = 0; /* Tabs at end of line are not drawn when wrapped */
} else if (*c == ' ') {
col++;
wrapCol = 0; /* Spaces at end of line are not drawn when wrapped */
} else {
col++;
wrapCol = 1;
}
/* Note: there is a small chance that the number of lines is
over-estimated when a line ends with a space or a tab (ie, followed
by a newline) and that whitespace crosses the boundary, because
whitespace at the end of a line does not cause wrapping. Taking
this into account is very hard, but an over-estimation is harmless.
The worst that can happen is that some extra blank lines are shown
at the end of the dialog (in contrast to an under-estimation, which
could make the last lines invisible).
On the other hand, without emulating Motif's wrapping algorithm
completely, we can't be sure that we don't underestimate the number
of lines (Motif uses word wrap, and this counting algorithm uses
character wrap). Therefore, we remember whether there is a line
that has wrapped. In that case we allways install a scroll bar.
*/
if (col > wrapWidth) {
line++;
*wrapped = 1;
col = wrapCol;
} else if (col > maxCols) {
maxCols = col;
}
}
*rows = line;
*cols = maxCols;
}
/*
** Truncate a string to a maximum of length characters. If it shortens the
** string, it appends "..." to show that it has been shortened. It assumes
** that the string that it is passed is writeable.
*/
static void truncateString(char *string, int length)
{
if ((int)strlen(string) > length)
memcpy(&string[length-3], "...", 4);
}
/*
** Substitute the string fileStr in inStr wherever % appears and
** lineStr in inStr wherever # appears, storing the
** result in outStr. If predictOnly is non-zero, the result string length
** is predicted without creating the string. Returns the length of the result
** string or -1 in case of an error.
**
*/
static int shellSubstituter(char *outStr, const char *inStr, const char *fileStr,
const char *lineStr, int outLen, int predictOnly)
{
const char *inChar;
char *outChar = NULL;
int outWritten = 0;
int fileLen, lineLen;
inChar = inStr;
if (!predictOnly) {
outChar = outStr;
}
fileLen = strlen(fileStr);
lineLen = strlen(lineStr);
while (*inChar != '\0') {
if (!predictOnly && outWritten >= outLen) {
return(-1);
}
if (*inChar == '%') {
if (*(inChar + 1) == '%') {
inChar += 2;
if (!predictOnly) {
*outChar++ = '%';
}
outWritten++;
} else {
if (!predictOnly) {
if (outWritten + fileLen >= outLen) {
return(-1);
}
strncpy(outChar, fileStr, fileLen);
outChar += fileLen;
}
outWritten += fileLen;
inChar++;
}
} else if (*inChar == '#') {
if (*(inChar + 1) == '#') {
inChar += 2;
if (!predictOnly) {
*outChar++ = '#';
}
outWritten++;
} else {
if (!predictOnly) {
if (outWritten + lineLen >= outLen) {
return(-1);
}
strncpy(outChar, lineStr, lineLen);
outChar += lineLen;
}
outWritten += lineLen;
inChar++;
}
} else {
if (!predictOnly) {
*outChar++ = *inChar;
}
inChar++;
outWritten++;
}
}
if (!predictOnly) {
if (outWritten >= outLen) {
return(-1);
}
*outChar = '\0';
}
++outWritten;
return(outWritten);
}
static char *shellCommandSubstitutes(const char *inStr, const char *fileStr,
const char *lineStr)
{
int cmdLen;
char *subsCmdStr = NULL;
cmdLen = shellSubstituter(NULL, inStr, fileStr, lineStr, 0, 1);
if (cmdLen >= 0) {
subsCmdStr = malloc(cmdLen);
if (subsCmdStr) {
cmdLen = shellSubstituter(subsCmdStr, inStr, fileStr, lineStr, cmdLen, 0);
if (cmdLen < 0) {
free(subsCmdStr);
subsCmdStr = NULL;
}
}
}
return(subsCmdStr);
}
|