Debian Codegraph @

src/main/java/net/sf/antcontrib/logic/OutOfDate.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2001-2004 Ant-Contrib project. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.antcontrib.logic;
17
18 import java.io.File;
19 import java.util.Enumeration;
20 import java.util.Iterator;
21 import java.util.Hashtable;
22 import java.util.Vector;
23
24 import org.apache.tools.ant.BuildException;
25 import org.apache.tools.ant.Project;
26 import org.apache.tools.ant.Task;
27 import org.apache.tools.ant.taskdefs.Parallel;
28 import org.apache.tools.ant.taskdefs.Sequential;
29 import org.apache.tools.ant.taskdefs.condition.Condition;
30 import org.apache.tools.ant.types.Mapper;
31 import org.apache.tools.ant.types.Path;
32 import org.apache.tools.ant.util.FileNameMapper;
33 import org.apache.tools.ant.util.FileUtils;
34
35 import org.apache.tools.ant.types.EnumeratedAttribute;
36
37 /**
38 * Task to help in calling tasks if generated files are older
39 * than source files.
40 * Sets a given property or runs an internal task.
41 *
42 * Based on
43 * org.apache.org.apache.tools.ant.taskdefs.UpToDate
44 *
45 * @author peter reilly
46 */
47
48 public class OutOfDate extends Task implements Condition {
49
50 /**
51 * Enumerated type for collection attribute
52 *
53 * @see EnumeratedAttribute
54 */
55 public static class CollectionEnum extends EnumeratedAttribute {
56 /** Constants for the enumerations */
57 public static final int
58 SOURCES = 0, TARGETS = 1, ALLSOURCES = 2, ALLTARGETS = 3;
59
60 /**
61 * get the values
62 * @return an array of the allowed values for this attribute.
63 */
64 public String[] getValues() {
65 return new String[] {"sources", "targets", "allsources", "alltargets"};
66 }
67 }
68
69 // attributes and nested elements
70 private Task doTask = null;
71 private String property;
72 private String value = "true";
73 private boolean force = false;
74 private int verbosity = Project.MSG_VERBOSE;
75 private Vector mappers = new Vector();
76 private Path targetpaths = null;
77 private Path sourcepaths = null;
78 private String outputSources = null;
79 private String outputSourcesPath = null;
80 private String outputTargets = null;
81 private String outputTargetsPath = null;
82 private String allTargets = null;
83 private String allTargetsPath = null;
84 private String separator = " ";
85 private DeleteTargets deleteTargets = null;
86 private int collection = CollectionEnum.SOURCES;
87
88 // variables
89 private Hashtable targetSet = new Hashtable();
90 private Hashtable sourceSet = new Hashtable();
91 private Hashtable allTargetSet = new Hashtable();
92 private Hashtable allSourceSet = new Hashtable();
93
94 /**
95 * Set the collection attribute, controls what is
96 * returned by the iterator method.
97 * <dl>
98 * <li>"sources" the sources that are newer than the corresponding targets.</li>
99 * <li>"targets" the targets that are older or not present than the corresponding
100 * sources.</li>
101 * <li>"allsources" all the sources</li>
102 * <li>"alltargets" all the targets</li>
103 * </dl>
104 * @param collection "sources" the changes
105 */
106 public void setCollection(CollectionEnum collection) {
107 this.collection = collection.getIndex();
108 }
109
110 /**
111 * Defines the FileNameMapper to use (nested mapper element).
112 * @return Mappper to be configured
113 */
114 public Mapper createMapper() {
115 MyMapper mapper = new MyMapper(getProject());
116 mappers.addElement(mapper);
117 return mapper;
118 }
119
120 /**
121 * The property to set if any of the target files are outofdate with
122 * regard to any of the source files.
123 *
124 * @param property the name of the property to set if Target is outofdate.
125 */
126 public void setProperty(String property) {
127 this.property = property;
128 }
129
130 /**
131 * The separator to use to separate the files
132 * @param separator separator used in outout properties
133 */
134
135 public void setSeparator(String separator) {
136 this.separator = separator;
137 }
138
139 /**
140 * The value to set the named property to the target files
141 * are outofdate
142 *
143 * @param value the value to set the property
144 */
145 public void setValue(String value) {
146 this.value = value;
147 }
148
149 /**
150 * whether to allways be outofdate
151 * @param force true means that outofdate is always set, default
152 * false
153 */
154 public void setForce(boolean force) {
155 this.force = force;
156 }
157
158 /**
159 * whether to have verbose output
160 * @param verbose true means that outofdate outputs debug info
161 */
162 public void setVerbose(boolean verbose) {
163 if (verbose) {
164 this.verbosity = Project.MSG_INFO;
165 } else {
166 this.verbosity = Project.MSG_VERBOSE;
167 }
168 }
169
170 /**
171 * Add to the target files
172 *
173 * @return a path to be configured
174 */
175 public Path createTargetfiles() {
176 if (targetpaths == null) {
177 targetpaths = new Path(getProject());
178 }
179 return targetpaths;
180 }
181
182 /**
183 * Add to the source files
184 *
185 * @return a path to be configured
186 */
187 public Path createSourcefiles() {
188 if (sourcepaths == null) {
189 sourcepaths = new Path(getProject());
190 }
191 return sourcepaths;
192 }
193
194 /**
195 * A property to contain the output source files
196 *
197 * @param outputSources the name of the property
198 */
199 public void setOutputSources(String outputSources) {
200 this.outputSources = outputSources;
201 }
202
203 /**
204 * A property to contain the output target files
205 *
206 * @param outputTargets the name of the property
207 */
208 public void setOutputTargets(String outputTargets) {
209 this.outputTargets = outputTargets;
210 }
211
212 /**
213 * A reference to contain the path of target files that
214 * are outofdate
215 *
216 * @param outputTargetsPath the name of the reference
217 */
218 public void setOutputTargetsPath(String outputTargetsPath) {
219 this.outputTargetsPath = outputTargetsPath;
220 }
221
222 /**
223 * A refernce to contain the path of all the targets
224 *
225 * @param allTargetsPath the name of the reference
226 */
227 public void setAllTargetsPath(String allTargetsPath) {
228 this.allTargetsPath = allTargetsPath;
229 }
230
231 /**
232 * A property to contain all the target filenames
233 *
234 * @param allTargets the name of the property
235 */
236 public void setAllTargets(String allTargets) {
237 this.allTargets = allTargets;
238 }
239
240 /**
241 * A reference to the path containing all the sources files.
242 *
243 * @param outputSourcesPath the name of the reference
244 */
245 public void setOutputSourcesPath(String outputSourcesPath) {
246 this.outputSourcesPath = outputSourcesPath;
247 }
248
249 /**
250 * optional nested delete element
251 * @return an element to be configured
252 */
253 public DeleteTargets createDeleteTargets() {
254 deleteTargets = new DeleteTargets();
255 return deleteTargets;
256 }
257
258 /**
259 * Embedded do parallel
260 * @param doTask the parallel to embed
261 */
262 public void addParallel(Parallel doTask) {
263 if (this.doTask != null) {
264 throw new BuildException(
265 "You must not nest more that one <parallel> or <sequential>"
266 + " into <outofdate>");
267 }
268 this.doTask = doTask;
269 }
270
271 /**
272 * Embedded do sequential.
273 * @param doTask the sequential to embed
274 */
275 public void addSequential(Sequential doTask) {
276 if (this.doTask != null) {
277 throw new BuildException(
278 "You must not nest more that one <parallel> or <sequential>"
279 + " into <outofdate>");
280 }
281 this.doTask = doTask;
282 }
283
284 /**
285 * Evaluate (all) target and source file(s) to
286 * see if the target(s) is/are outoutdate.
287 * @return true if any of the targets are outofdate
288 */
289 public boolean eval() {
290 boolean ret = false;
291 FileUtils fileUtils = FileUtils.newFileUtils();
292 if (sourcepaths == null) {
293 throw new BuildException(
294 "You must specify a <sourcefiles> element.");
295 }
296
297 if (targetpaths == null && mappers.size() == 0) {
298 throw new BuildException(
299 "You must specify a <targetfiles> or <mapper> element.");
300 }
301
302 // Source Paths
303 String[] spaths = sourcepaths.list();
304
305 for (int i = 0; i < spaths.length; i++) {
306 File sourceFile = new File(spaths[i]);
307 if (!sourceFile.exists()) {
308 throw new BuildException(sourceFile.getAbsolutePath()
309 + " not found.");
310 }
311 }
312
313 // Target Paths
314
315 if (targetpaths != null) {
316 String[] paths = targetpaths.list();
317 if (paths.length == 0) {
318 ret = true;
319 }
320 else {
321 for (int i = 0; i < paths.length; ++i) {
322 if (targetNeedsGen(paths[i], spaths)) {
323 ret = true;
324 }
325 }
326 }
327 }
328
329 // Mapper Paths
330 for (Enumeration e = mappers.elements(); e.hasMoreElements();) {
331 MyMapper mapper = (MyMapper) e.nextElement();
332
333 File relativeDir = mapper.getDir();
334 File baseDir = new File(getProject().getProperty("basedir"));
335 if (relativeDir == null) {
336 relativeDir = baseDir;
337 }
338 String[] rpaths = new String[spaths.length];
339 for (int i = 0; i < spaths.length; ++i) {
340 rpaths[i] = fileUtils.removeLeadingPath(relativeDir, new File(spaths[i]));
341 }
342
343 FileNameMapper fileNameMapper = mapper.getImplementation();
344 for (int i = 0; i < spaths.length; ++i) {
345 String[] mapped = fileNameMapper.mapFileName(rpaths[i]);
346 if (mapped != null) {
347 for (int j = 0; j < mapped.length; ++j) {
348 if (outOfDate(new File(spaths[i]),
349 fileUtils.resolveFile(
350 baseDir, mapped[j]))) {
351 ret = true;
352 }
353 }
354 }
355 }
356 }
357
358 if (allTargets != null) {
359 this.getProject().setNewProperty(
360 allTargets, setToString(allTargetSet));
361 }
362
363 if (allTargetsPath != null) {
364 this.getProject().addReference(
365 allTargetsPath, setToPath(allTargetSet));
366 }
367
368 if (outputSources != null) {
369 this.getProject().setNewProperty(
370 outputSources, setToString(sourceSet));
371 }
372
373 if (outputTargets != null) {
374 this.getProject().setNewProperty(
375 outputTargets, setToString(targetSet));
376 }
377
378 if (outputSourcesPath != null) {
379 this.getProject().addReference(
380 outputSourcesPath, setToPath(sourceSet));
381 }
382
383 if (outputTargetsPath != null) {
384 this.getProject().addReference(
385 outputTargetsPath, setToPath(targetSet));
386 }
387
388 if (force) {
389 ret = true;
390 }
391
392 if (ret && deleteTargets != null) {
393 deleteTargets.execute();
394 }
395
396 if (ret) {
397 if (property != null) {
398 this.getProject().setNewProperty(property, value);
399 }
400 }
401
402 return ret;
403 }
404
405 private boolean targetNeedsGen(String target, String[] spaths) {
406 boolean ret = false;
407 File targetFile = new File(target);
408 for (int i = 0; i < spaths.length; i++) {
409 if (outOfDate(new File(spaths[i]), targetFile)) {
410 ret = true;
411 }
412 }
413 // Special case : there are no source files, make sure the
414 // targets exist
415 if (spaths.length == 0) {
416 if (outOfDate(null, targetFile)) {
417 ret = true;
418 }
419 }
420 return ret;
421 }
422
423 /**
424 * Call evalute and return an iterator over the result
425 * @return an iterator over the result
426 */
427 public Iterator iterator() {
428 // Perhaps should check the result and return
429 // an empty set if it returns false
430 eval();
431
432 switch (collection) {
433 case CollectionEnum.SOURCES:
434 return sourceSet.values().iterator();
435 case CollectionEnum.TARGETS:
436 return targetSet.values().iterator();
437 case CollectionEnum.ALLSOURCES:
438 return allSourceSet.values().iterator();
439 case CollectionEnum.ALLTARGETS:
440 return allTargetSet.values().iterator();
441 default:
442 return sourceSet.values().iterator();
443 }
444 }
445
446 /**
447 * Sets property to true and/or executes embedded do
448 * if any of the target file(s) do not have a more recent timestamp
449 * than (each of) the source file(s).
450 */
451 public void execute() {
452 if (!eval()) {
453 return;
454 }
455
456 if (doTask != null) {
457 doTask.perform();
458 }
459
460 }
461
462
463 private boolean outOfDate(File sourceFile, File targetFile) {
464 boolean ret = false;
465 if (sourceFile != null) {
466 allSourceSet.put(sourceFile, sourceFile);
467 }
468 allTargetSet.put(targetFile, targetFile);
469 if (!targetFile.exists()) {
470 ret = true;
471 }
472 if ((!ret) && (sourceFile != null)) {
473 ret = sourceFile.lastModified() > targetFile.lastModified();
474 }
475 if (ret) {
476 if ((sourceFile != null && sourceSet.get(sourceFile) == null)
477 || targetSet.get(targetFile) == null) {
478 log("SourceFile " + sourceFile + " outofdate "
479 + "with regard to " + targetFile, verbosity);
480 }
481 if (sourceFile != null) {
482 sourceSet.put(sourceFile, sourceFile);
483 }
484 targetSet.put(targetFile, targetFile);
485 }
486 return ret;
487 }
488
489 private String setToString(Hashtable set) {
490 StringBuffer b = new StringBuffer();
491 for (Enumeration e = set.keys(); e.hasMoreElements();) {
492 File v = (File) e.nextElement();
493 if (b.length() != 0) {
494 b.append(separator);
495 }
496 String s = v.getAbsolutePath();
497 // DOTO: The following needs more work!
498 // Handle paths contains sep
499 if (s.indexOf(separator) != -1) {
500 if (s.indexOf("\"") != -1) {
501 s = "'" + s + "'";
502 } else {
503 s = "\"" + s + "\"";
504 }
505 }
506 b.append(s);
507 }
508 return b.toString();
509 }
510
511 private Path setToPath(Hashtable set) {
512 Path ret = new Path(getProject());
513 for (Enumeration e = set.keys(); e.hasMoreElements();) {
514 File v = (File) e.nextElement();
515 Path.PathElement el = ret.createPathElement();
516 el.setLocation(v);
517 }
518 return ret;
519 }
520
521 /**
522 * nested delete targets
523 */
524 public class DeleteTargets {
525 private boolean all = false;
526 private boolean quiet = false;
527 private boolean failOnError = false;
528
529 private int myLogging = Project.MSG_INFO;
530
531 /**
532 * whether to delete all the targets
533 * or just those that are newer than the
534 * corresponding sources.
535 * @param all true to delete all, default false
536 */
537 public void setAll(boolean all) {
538 this.all = all;
539 }
540
541 /**
542 * @param quiet if true suppress messages on deleting files
543 */
544 public void setQuiet(boolean quiet) {
545 this.quiet = quiet;
546 myLogging = quiet ? Project.MSG_VERBOSE : Project.MSG_INFO;
547 }
548
549 /**
550 * @param failOnError if true halt if there is a failure to delete
551 */
552 public void setFailOnError(boolean failOnError) {
553 this.failOnError = failOnError;
554 }
555
556 private void execute() {
557 if (myLogging != Project.MSG_INFO) {
558 myLogging = verbosity;
559 }
560
561 // Quiet overrides failOnError
562 if (quiet) {
563 failOnError = false;
564 }
565
566 Path toBeDeleted = null;
567 if (all) {
568 toBeDeleted = setToPath(allTargetSet);
569 } else {
570 toBeDeleted = setToPath(targetSet);
571 }
572
573 String[] names = toBeDeleted.list();
574 for (int i = 0; i < names.length; ++i) {
575 File file = new File(names[i]);
576 if (!file.exists()) {
577 continue;
578 }
579 if (file.isDirectory()) {
580 removeDir(file);
581 continue;
582 }
583 log("Deleting " + file.getAbsolutePath(), myLogging);
584 if (!file.delete()) {
585 String message =
586 "Unable to delete file " + file.getAbsolutePath();
587 if (failOnError) {
588 throw new BuildException(message);
589 } else {
590 log(message, myLogging);
591 }
592 }
593 }
594 }
595
596 private static final int DELETE_RETRY_SLEEP_MILLIS = 10;
597 /**
598 * Attempt to fix possible race condition when deleting
599 * files on WinXP. If the delete does not work,
600 * wait a little and try again.
601 */
602 private boolean delete(File f) {
603 if (!f.delete()) {
604 try {
605 Thread.sleep(DELETE_RETRY_SLEEP_MILLIS);
606 return f.delete();
607 } catch (InterruptedException ex) {
608 return f.delete();
609 }
610 }
611 return true;
612 }
613
614 private void removeDir(File d) {
615 String[] list = d.list();
616 if (list == null) {
617 list = new String[0];
618 }
619 for (int i = 0; i < list.length; i++) {
620 String s = list[i];
621 File f = new File(d, s);
622 if (f.isDirectory()) {
623 removeDir(f);
624 } else {
625 log("Deleting " + f.getAbsolutePath(), myLogging);
626 if (!f.delete()) {
627 String message = "Unable to delete file "
628 + f.getAbsolutePath();
629 if (failOnError) {
630 throw new BuildException(message);
631 } else {
632 log(message, myLogging);
633 }
634 }
635 }
636 }
637 log("Deleting directory " + d.getAbsolutePath(), myLogging);
638 if (!delete(d)) {
639 String message = "Unable to delete directory "
640 + d.getAbsolutePath();
641 if (failOnError) {
642 throw new BuildException(message);
643 } else {
644 log(message, myLogging);
645 }
646 }
647 }
648 }
649
650 /**
651 * Wrapper for mapper - includes dir
652 */
653 public static class MyMapper extends Mapper {
654 private File dir = null;
655 /**
656 * Creates a new <code>MyMapper</code> instance.
657 *
658 * @param project the current project
659 */
660 public MyMapper(Project project) {
661 super(project);
662 }
663
664 /**
665 * @param dir the directory that the from files are relative to
666 */
667 public void setDir(File dir) {
668 this.dir = dir;
669 }
670
671 /**
672 * @return the directory that the from files are relative to
673 */
674 public File getDir() {
675 return dir;
676 }
677 }
678 }
679
680