Stuart McCulloch | 3fdcd85 | 2011-10-17 10:31:43 +0000 | [diff] [blame^] | 1 | package aQute.libg.sed; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.util.*; |
| 5 | import java.util.regex.*; |
| 6 | |
| 7 | public class Sed { |
| 8 | final File file; |
| 9 | final Replacer macro; |
| 10 | File output; |
| 11 | |
| 12 | final Map<Pattern, String> replacements = new LinkedHashMap<Pattern, String>(); |
| 13 | |
| 14 | public Sed(Replacer macro, File file) { |
| 15 | assert file.isFile(); |
| 16 | this.file = file; |
| 17 | this.macro = macro; |
| 18 | } |
| 19 | |
| 20 | public void setOutput(File f) { |
| 21 | output = f; |
| 22 | } |
| 23 | |
| 24 | public void replace(String pattern, String replacement) { |
| 25 | replacements.put(Pattern.compile(pattern), replacement); |
| 26 | } |
| 27 | |
| 28 | public void doIt() throws IOException { |
| 29 | BufferedReader brdr = new BufferedReader(new FileReader(file)); |
| 30 | File out; |
| 31 | if (output != null) |
| 32 | out = output; |
| 33 | else |
| 34 | out = new File(file.getAbsolutePath() + ".tmp"); |
| 35 | File bak = new File(file.getAbsolutePath() + ".bak"); |
| 36 | PrintWriter pw = new PrintWriter(new FileWriter(out)); |
| 37 | try { |
| 38 | String line; |
| 39 | while ((line = brdr.readLine()) != null) { |
| 40 | for (Pattern p : replacements.keySet()) { |
| 41 | String replace = replacements.get(p); |
| 42 | Matcher m = p.matcher(line); |
| 43 | |
| 44 | StringBuffer sb = new StringBuffer(); |
| 45 | while (m.find()) { |
| 46 | String tmp = setReferences(m, replace); |
| 47 | tmp = macro.process(tmp); |
| 48 | m.appendReplacement(sb, Matcher.quoteReplacement(tmp)); |
| 49 | } |
| 50 | m.appendTail(sb); |
| 51 | |
| 52 | line = sb.toString(); |
| 53 | } |
| 54 | pw.println(line); |
| 55 | } |
| 56 | pw.close(); |
| 57 | if (output == null) { |
| 58 | file.renameTo(bak); |
| 59 | out.renameTo(file); |
| 60 | } |
| 61 | } finally { |
| 62 | brdr.close(); |
| 63 | pw.close(); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | private String setReferences(Matcher m, String replace) { |
| 68 | StringBuilder sb = new StringBuilder(); |
| 69 | for (int i = 0; i < replace.length(); i++) { |
| 70 | char c = replace.charAt(i); |
| 71 | if (c == '$' && i < replace.length() - 1 |
| 72 | && Character.isDigit(replace.charAt(i + 1))) { |
| 73 | int n = replace.charAt(i + 1) - '0'; |
| 74 | if ( n <= m.groupCount() ) |
| 75 | sb.append(m.group(n)); |
| 76 | i++; |
| 77 | } else |
| 78 | sb.append(c); |
| 79 | } |
| 80 | return sb.toString(); |
| 81 | } |
| 82 | } |