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 | package Torello.Java; import Torello.Java.Verbosity; import Torello.Java.IOExceptionHandler; import Torello.Java.FileNode; import Torello.Java.FileRW; import Torello.Java.StrPrint; import Torello.Java.StrIndexOf; import Torello.Java.Q; import Torello.Java.Additional.AppendableSafe; import Torello.Java.Additional.BiAppendable; import static Torello.Java.C.BGREEN; import static Torello.Java.C.BRED; import static Torello.Java.C.RESET; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.Collectors; import java.io.IOException; class SingleLineStrMatch { // Re-Use the Pointer, I guess private static final String I4 = Helper.I4; // Only Method static List<FileNode> match( final Iterable<FileNode> files, final String matchStr, final String replaceStr, final boolean askFirst, final IOExceptionHandler ioeh, final Appendable outputSaver, final boolean useUNIXColors, final Verbosity verbosity ) throws IOException { if (matchStr.indexOf('\n') != -1) throw new IllegalArgumentException( "Parameter 'matchStr' contains at least one newline '\n' character. Use the " + "Multi-Line SED method." ); if (replaceStr.indexOf('\n') != -1) throw new IllegalArgumentException( "Parameter 'replaceStr' contains at least one newline '\n' character. Use the " + "Multi-Line SED method." ); Helper.CHECK(askFirst, verbosity); // This value is used repeatedly in this loop, so it is better left as a constant final int MATCH_STR_LEN = matchStr.length(); // This Stream-Builder contains the list of FileNode's that are modified. Stream.Builder<FileNode> ret = Stream.builder(); Appendable appendable = (outputSaver == null) // If no 'outputSaver' was provided, then just send text to Standard-Out ? System.out // This just allows for printing to **BOTH** System.out **AND** the 'outputSaver' : new BiAppendable (System.out, new AppendableSafe(outputSaver, AppendableSafe.USE_APPENDABLE_ERROR)); // A very short "Consumer" that really just prints the file-name, nothing more. Consumer<String> fileNamePrinter = Helper.getFileNamePrinter (appendable, useUNIXColors, verbosity.level); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // MAIN-LOOP: Iterate all the FileNode's // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** for (FileNode file : files) { // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Load the File, and then Find any / all Matches // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** String fileName = file.getFullPathName(); String fileAsStr = null; // Print the file-name, if the verbosity level mandates that it be printed fileNamePrinter.accept(fileName); try { fileAsStr = FileRW.loadFileToString(fileName); } catch (IOException e) { if (ioeh != null) ioeh.accept(file, e); else throw e; // if ioeh ignores the exception rather than halting the program, then just continue // the loop on to the next match continue; } // Retrieve the starting String-index of each and every match in the file int[] posArr = StrIndexOf.all(fileAsStr, matchStr); if (posArr.length == 0) continue; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // For-Loop: Print the Matches to System.out // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // These are used (only in one place) at the very end of this loop, for printing only // They are "re-initialized" below. The '-1' initialization is just to shut up the // Java-Compiler int prevPos = -1, prevLineNumber = -1; // This is a "Printing Stream" which saves PrintingRecSingleLine instances. This // allows the spacing to be properly computed before actually writing the text to // System.out Stream.Builder<PrintingRecSingleLine> PRSLB = Stream.builder(); for (int i=0; i < posArr.length; /* Loop-Increment happens inside inner for-loop */) { final int pos = posArr[i]; // The line of text within the Text-File containing the positon of the match final String line = StrPrint.line(fileAsStr, pos); // It is POSSIBLE for there to be more than one match on a single line // It is NOT POSSIBLE for there to be zero matches.... int[] posArrLine = StrIndexOf.all(line, matchStr); // The purpose of this Record is to save output-data into a record, so that the // spacing may be computed **BEFORE** printing to System.out. This allows for // making sure that all String-Matches are **EVENLY-SPACED** when printed to // System.out final PrintingRecSingleLine saverRecord = new PrintingRecSingleLine(); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Generate the Original Line... but with UNIX (Escape-Sequence) HiLiting-Colors // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** StringBuilder sb = new StringBuilder(); int prev = 0; // If the user has requested No UNIX-Colors, then this whole loop can just be // skipped, and the original line that was extracted may simply be printed to the // terminal, telling the user about the match, with no color codes. See the // Else-Statement that is after this If-Branch if (useUNIXColors) { // Iterate all matches on just one line of the input-text. for (int j=0; j < posArrLine.length; j++) { final int posLine = posArrLine[j]; // Overlapping matches need to be skipped. The best way to determine // whether there is an over-lapping match is just to check if the start of // the match occurs at a String-Index that is before the end of the // previous-match. If so, just continue. if (j > 0) if (posArr[j] < (posArr[j-1] + MATCH_STR_LEN)) continue; sb .append(line.substring(prev, posLine)) // Stuff that didn't match .append(BRED) .append(matchStr) // Text that did match .append(RESET); prev = posLine + MATCH_STR_LEN; } // Last-Ending Unmatched-Stuff, Don't forget to append it! sb.append(line.substring(prev)); // This is the exact same "Original Line" of text, but with UNIX Color-Codes saverRecord.saveOriginalLine(sb.toString()); // Reset the StringBuilder & 'prev' for the next loop sb.setLength(0); prev = 0; } // **ELSE-IF** no UNIX-Colors are used to print the message to the user, then the // "Original-Line" ... well ... is still the same Original-Line. So save that. else saverRecord.saveOriginalLine(line); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Generate the Updated / New Line - with Escape-Sequence Colors // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Iterate all matches on just one line of the input-text. for (int j=0; j < posArrLine.length; j++) { final int posLine = posArrLine[j]; // Overlapping matches need to be skipped. (as before, same as in code above) if (j > 0) if (posArr[j] < (posArr[j-1] + MATCH_STR_LEN)) continue; sb .append(line.substring(prev, posLine)) // Stuff that didn't match .append(useUNIXColors ? BGREEN : "") .append(replaceStr) // Text that did match (updated) .append(useUNIXColors ? RESET : ""); prev = posLine + MATCH_STR_LEN; } // Last-Ending Unmatched-Stuff, Don't forget to append it! sb.append(line.substring(prev)); // This is the exact same "Original Line" of text, but with UNIX Color-Codes saverRecord.saveNewLine(sb.toString()); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Generate PrintingRecSingleLine, (Actual Printing done at very end, all at once) // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** saverRecord.saveOriginalLineLength(line.length()); saverRecord.saveNewLineLength (line.length() + (posArrLine.length * (replaceStr.length() - MATCH_STR_LEN))); // Only on the first iteration should we compute the line number, after the first // loop iteration, use the "lineNumberSince" which uses the prev-loop computations // This is just for efficiency purposes only. final int lineNumber = (i == 0) ? StrPrint.lineNumber(fileAsStr, pos) : StrPrint.lineNumberSince(fileAsStr, pos, prevLineNumber, prevPos); saverRecord.saveLineNumber(lineNumber); // Update these ... The previous line of code directly above is the only place // where these two are used. They make it faster/easier to "find the line number" prevPos = pos; prevLineNumber = lineNumber; PRSLB.accept(saverRecord); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Don't Forget... (File-Updater Loop-Counter needs to be updated) // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** i += posArrLine.length; } // All Printing-Records as an Array PrintingRecSingleLine[] recs = PRSLB.build().toArray(PrintingRecSingleLine[]::new); if (recs.length == 0) continue; // unless Verbosity.Silent was requested, print the matches. if (verbosity.level > 0) PrintingRecSingleLine.printAll(recs, useUNIXColors, appendable, verbosity); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Query the User, Write the Replacement // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (askFirst) if (! Q.YN("Re-Write the Updated File to Disk?")) continue; // Remember, this single line of code does the actual replacement! String newFileAsStr = fileAsStr.replace(matchStr, replaceStr); try { FileRW.writeFile(newFileAsStr, fileName); } catch (IOException e) { if (ioeh != null) ioeh.accept(file, e); else throw e; // if ioeh ignores the exception rather than halting the program, then just continue // the loop on to the next match continue; } // In "Verbosity.Verbose" mode, tell the user how many changes were updated in the file if (verbosity.level == 3) appendable.append(I4 + "Updated " + recs.length + " Matches"); // This is a file that was updated, so put it in the returned list of "updated files" ret.accept(file); } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Finished, so return the list of modified FileNode's // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** return ret.build().collect(Collectors.toList()); } } |