source: other-projects/trunk/anttasks/src/org/greenstone/anttasks/RegexSearchReplace.java@ 17902

Last change on this file since 17902 was 17902, checked in by oranfry, 15 years ago

made rsr support filesets

File size: 8.1 KB
Line 
1/*
2 * RegexSearchReplace.java
3 * A task to replace occurences of a given pattern with a given replacement in a given file
4 *
5 * Copyright (C) 2005 New Zealand Digital Library, http://www.nzdl.org
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21package org.greenstone.anttasks;
22
23import java.util.ArrayList;
24import org.apache.tools.ant.*;
25import org.apache.tools.ant.taskdefs.*;
26import java.util.*;
27import java.io.*;
28import java.util.regex.*;
29import org.apache.tools.ant.types.FileSet;
30import org.apache.tools.ant.DirectoryScanner;
31
32public class RegexSearchReplace extends Task {
33
34 private File file = null;
35 private ArrayList jobs = null;
36 private FileSet fileset = null;
37 private String pattern = null;
38 private String replacement = null;
39 private boolean winPath = false;
40
41 public static void main( String[] args ) {
42
43 RegexSearchReplace rsr = new RegexSearchReplace();
44 rsr.setFile(new File (args[0]));
45 rsr.setPattern(args[1]);
46 rsr.setReplacement(args[2]);
47
48 rsr.execute();
49
50 }
51
52 public void execute() {
53
54 if ( file == null && fileset == null ) {
55 throw new BuildException( "Error - No file or fileset specified !!" );
56 }
57
58 if ( file != null && !file.exists() ) {
59 throw new BuildException( "Error - File not found !!" );
60 }
61
62 DirectoryScanner dirScanner = null;
63 if ( fileset != null ) {
64 dirScanner = fileset.getDirectoryScanner();
65 dirScanner.scan();
66 }
67
68 if ( jobs == null && pattern == null ) {
69 throw new BuildException( "Error - No pattern attribute and no nested jobs !!" );
70 }
71
72 if ( jobs != null && pattern != null ) {
73 throw new BuildException( "Error - Both pattern attribute and nested jobs given !!" );
74 }
75
76 if ( pattern != null && replacement == null ) {
77 throw new BuildException( "Error - pattern attribute given but no replacement attribute given !!" );
78 }
79
80 if ( jobs != null ) {
81 for ( int i=0; i<jobs.size(); i++ ) {
82 if ( ((RegexSearchReplaceJob)(jobs.get(i))).getPattern() == null ) {
83 throw new BuildException( "Error - One of the jobs lacks a pattern!!" );
84 }
85 if ( ((RegexSearchReplaceJob)(jobs.get(i))).getReplacement() == null ) {
86 throw new BuildException( "Error - One of the jobs lacks a replacement!!" );
87 }
88 }
89 }
90
91
92 //sus out filename(s)
93 File[] files = null;
94 if ( file != null ) {
95 files = new File[1];
96 files[0] = file;
97 } else {
98 String[] fileStrings = dirScanner.getIncludedFiles();
99 files = new File[fileStrings.length];
100 for ( int i=0; i<fileStrings.length; i++ ) {
101 files[i] = new File( dirScanner.getBasedir() + File.separator + fileStrings[i] );
102 }
103 }
104
105 //output greeting
106 System.out.println();
107 System.out.println( "--------------------" );
108 System.out.println( " RegexSearchReplace " );
109 System.out.println( "--------------------" );
110
111 //output replacement(s)
112 System.out.println( "Replacements:" );
113 if ( pattern != null ) {
114 System.out.println( " " + pattern + " -> " + replacement );
115 } else {
116 for ( int i=0; i<jobs.size(); i++ ) {
117 System.out.println( " " + ((RegexSearchReplaceJob)(jobs.get(i))).getPattern() + " -> " + ((RegexSearchReplaceJob)(jobs.get(i))).getReplacement() );
118 }
119 }
120
121 //output filename(s)
122 /*
123 if ( file != null ) {
124 System.out.println( "Replace in file: " + file );
125 } else {
126 System.out.println( "Replace in files:" );
127 for ( int i = 0; i < files.length; i++ ) {
128 System.out.println(files[i]);
129 }
130 }
131 */
132
133
134 System.out.println( "Files: " );
135 for ( int fileIndex=0; fileIndex<files.length; fileIndex++ ) {
136
137 int noReplaces = 0;
138
139 File inputFile = files[fileIndex];
140
141 //create the output stream
142 BufferedWriter out = null;
143 File temp = null;
144 try {
145 //create temp file.
146 temp = File.createTempFile("rsr", ".tmp");
147
148 //delete temp file when program exits.
149 temp.deleteOnExit();
150
151 //writer to temp file
152 out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(temp), "UTF8") );
153
154 } catch (IOException e) {
155 throw new BuildException( "Error - Couldn't create or open the temp file" );
156 }
157
158
159 //create the input stream
160 BufferedReader in = null;
161 try {
162 in = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), "UTF8") );
163 } catch ( Exception e ) {
164 throw new BuildException( "Error - Couldn't open the specified file" );
165 }
166
167 //pass the file through, searching and replacing
168 String line = null;
169 boolean hasMoreLines = true;
170 while ( hasMoreLines ) {
171
172 try {
173 line = in.readLine();
174 } catch ( Exception e ) {
175 System.err.println( e.getMessage() );
176 throw new BuildException( "Error - Couldn't read from the specified file" );
177 }
178
179 if ( line == null ) {
180 hasMoreLines = false;
181 } else {
182
183 String oldLine = line;
184 if ( pattern != null ) {
185 String rp = replacement;
186 if ( winPath ) {
187 rp = rp.replaceAll("\\\\","\\\\\\\\");
188 }
189 line = line.replaceAll((String)pattern, (String)rp);
190 } else {
191 for ( int i=0; i<jobs.size(); i++ ) {
192 String rp = ((RegexSearchReplaceJob)(jobs.get(i))).getReplacement();
193 if ( ((RegexSearchReplaceJob)(jobs.get(i))).getWinPath() ) {
194 rp = rp.replaceAll("\\\\","\\\\\\\\");
195 }
196 line = line.replaceAll( ((RegexSearchReplaceJob)(jobs.get(i))).getPattern(), rp );
197 }
198 }
199
200 if ( !oldLine.equals( line ) ) {
201 noReplaces++;
202 }
203
204 try {
205 out.write( line );
206 out.newLine();
207 } catch ( Exception e ) {
208 throw new BuildException( "Error - Couldn't write to the temp file" );
209 }
210 }
211 }
212
213 try {
214 //close them both up
215 in.close();
216 out.close();
217 } catch ( Exception e ) {
218 throw new BuildException( "Error - Couldn't close a file" );
219 }
220
221
222 //copy the new file (temp) over the original
223 InputStream i;
224 OutputStream o;
225 try {
226 i = new FileInputStream(temp);
227 o = new FileOutputStream(inputFile);
228
229 } catch ( Exception e ) {
230 throw new BuildException( "Error - Couldn't open the temp file" );
231 }
232
233 try {
234
235 // Transfer bytes from in to out
236 byte[] buf = new byte[1024];
237 int len;
238 while ((len = i.read(buf)) > 0) {
239 o.write(buf, 0, len);
240 }
241
242 //close them up
243 i.close();
244 o.close();
245 } catch ( Exception e ) {
246 throw new BuildException( "Error - Couldn't write to the specified file" );
247 }
248
249
250 if ( noReplaces == 0 ) {
251 System.out.println( " " + inputFile + " : No Changes Made" );
252 } else if ( noReplaces == 1 ) {
253 System.out.println( " " + inputFile + " : Successfully changed 1 line" );
254 } else {
255 System.out.println( " " + inputFile + " : Successfully changed " + noReplaces + " lines" );
256 }
257
258 }
259 System.out.println();
260
261 }
262
263 public void setFile(File file) {
264 if ( this.fileset != null || this.file != null ) {
265 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
266 }
267 this.file = file;
268 }
269
270 public void setPattern(String pattern) {
271 this.pattern = pattern;
272 }
273
274 public void setReplacement(String replacement) {
275 replacement = replacement.replaceAll( "\\\\", "\\\\\\\\" );
276 this.replacement = replacement;
277 }
278
279 public void setWinPath( boolean isWinPath ) {
280 this.winPath = isWinPath;
281 }
282
283 public RegexSearchReplaceJob createJob() {
284 RegexSearchReplaceJob job = new RegexSearchReplaceJob();
285 if ( jobs == null ) {
286 jobs = new ArrayList();
287 }
288 jobs.add( job );
289 return job;
290
291 }
292
293 public FileSet createFileset() {
294 if ( this.fileset != null || this.file != null ) {
295 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
296 }
297 fileset = new FileSet();
298 return fileset;
299 }
300
301}
Note: See TracBrowser for help on using the repository browser.