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

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

small change to output of rsr task

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( " RegexSearchReplace " );
108 System.out.println( "--------------------" );
109
110 //output replacement(s)
111 System.out.println( "Replacements:" );
112 if ( pattern != null ) {
113 System.out.println( " " + pattern + " -> " + replacement );
114 } else {
115 for ( int i=0; i<jobs.size(); i++ ) {
116 System.out.println( " " + ((RegexSearchReplaceJob)(jobs.get(i))).getPattern() + " -> " + ((RegexSearchReplaceJob)(jobs.get(i))).getReplacement() );
117 }
118 }
119 System.out.println();
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 System.out.println( " " + inputFile );
141
142 //create the output stream
143 BufferedWriter out = null;
144 File temp = null;
145 try {
146 //create temp file.
147 temp = File.createTempFile("rsr", ".tmp");
148
149 //delete temp file when program exits.
150 temp.deleteOnExit();
151
152 //writer to temp file
153 out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(temp), "UTF8") );
154
155 } catch (IOException e) {
156 throw new BuildException( "Error - Couldn't create or open the temp file" );
157 }
158
159
160 //create the input stream
161 BufferedReader in = null;
162 try {
163 in = new BufferedReader( new InputStreamReader(new FileInputStream(inputFile), "UTF8") );
164 } catch ( Exception e ) {
165 throw new BuildException( "Error - Couldn't open the specified file" );
166 }
167
168 //pass the file through, searching and replacing
169 String line = null;
170 boolean hasMoreLines = true;
171 while ( hasMoreLines ) {
172
173 try {
174 line = in.readLine();
175 } catch ( Exception e ) {
176 System.err.println( e.getMessage() );
177 throw new BuildException( "Error - Couldn't read from the specified file" );
178 }
179
180 if ( line == null ) {
181 hasMoreLines = false;
182 } else {
183
184 String oldLine = line;
185 if ( pattern != null ) {
186 String rp = replacement;
187 if ( winPath ) {
188 rp = rp.replaceAll("\\\\","\\\\\\\\");
189 }
190 line = line.replaceAll((String)pattern, (String)rp);
191 } else {
192 for ( int i=0; i<jobs.size(); i++ ) {
193 String rp = ((RegexSearchReplaceJob)(jobs.get(i))).getReplacement();
194 if ( ((RegexSearchReplaceJob)(jobs.get(i))).getWinPath() ) {
195 rp = rp.replaceAll("\\\\","\\\\\\\\");
196 }
197 line = line.replaceAll( ((RegexSearchReplaceJob)(jobs.get(i))).getPattern(), rp );
198 }
199 }
200
201 if ( !oldLine.equals( line ) ) {
202 noReplaces++;
203 }
204
205 try {
206 out.write( line );
207 out.newLine();
208 } catch ( Exception e ) {
209 throw new BuildException( "Error - Couldn't write to the temp file" );
210 }
211 }
212 }
213
214 try {
215 //close them both up
216 in.close();
217 out.close();
218 } catch ( Exception e ) {
219 throw new BuildException( "Error - Couldn't close a file" );
220 }
221
222
223 //copy the new file (temp) over the original
224 InputStream i;
225 OutputStream o;
226 try {
227 i = new FileInputStream(temp);
228 o = new FileOutputStream(inputFile);
229
230 } catch ( Exception e ) {
231 throw new BuildException( "Error - Couldn't open the temp file" );
232 }
233
234 try {
235
236 // Transfer bytes from in to out
237 byte[] buf = new byte[1024];
238 int len;
239 while ((len = i.read(buf)) > 0) {
240 o.write(buf, 0, len);
241 }
242
243 //close them up
244 i.close();
245 o.close();
246 } catch ( Exception e ) {
247 throw new BuildException( "Error - Couldn't write to the specified file" );
248 }
249
250
251 if ( noReplaces == 0 ) {
252 System.out.println( " No Changes Made" );
253 } else if ( noReplaces == 1 ) {
254 System.out.println( " Successfully changed 1 line" );
255 } else {
256 System.out.println( " Successfully changed " + noReplaces + " lines" );
257 }
258 System.out.println();
259
260 }
261
262 }
263
264 public void setFile(File file) {
265 if ( this.fileset != null || this.file != null ) {
266 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
267 }
268 this.file = file;
269 }
270
271 public void setPattern(String pattern) {
272 this.pattern = pattern;
273 }
274
275 public void setReplacement(String replacement) {
276 replacement = replacement.replaceAll( "\\\\", "\\\\\\\\" );
277 this.replacement = replacement;
278 }
279
280 public void setWinPath( boolean isWinPath ) {
281 this.winPath = isWinPath;
282 }
283
284 public RegexSearchReplaceJob createJob() {
285 RegexSearchReplaceJob job = new RegexSearchReplaceJob();
286 if ( jobs == null ) {
287 jobs = new ArrayList();
288 }
289 jobs.add( job );
290 return job;
291
292 }
293
294 public FileSet createFileset() {
295 if ( this.fileset != null || this.file != null ) {
296 throw new BuildException( "Error - Only one file or one fileset may be given!!" );
297 }
298 fileset = new FileSet();
299 return fileset;
300 }
301
302}
Note: See TracBrowser for help on using the repository browser.