View Javadoc

1   package org.apache.maven.jalopy;
2   
3   /* ====================================================================
4    *   Licensed to the Apache Software Foundation (ASF) under one or more
5    *   contributor license agreements.  See the NOTICE file distributed with
6    *   this work for additional information regarding copyright ownership.
7    *   The ASF licenses this file to You under the Apache License, Version 2.0
8    *   (the "License"); you may not use this file except in compliance with
9    *   the License.  You may obtain a copy of the License at
10   *
11   *       http://www.apache.org/licenses/LICENSE-2.0
12   *
13   *   Unless required by applicable law or agreed to in writing, software
14   *   distributed under the License is distributed on an "AS IS" BASIS,
15   *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   *   See the License for the specific language governing permissions and
17   *   limitations under the License.
18   * ====================================================================
19   */
20  
21  import de.hunsicker.jalopy.Jalopy;
22  import de.hunsicker.jalopy.storage.Convention;
23  import de.hunsicker.jalopy.storage.History;
24  
25  import java.io.File;
26  import java.io.FileNotFoundException;
27  import java.io.IOException;
28  import java.io.InputStream;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  
33  import org.codehaus.plexus.util.DirectoryScanner;
34  import org.codehaus.plexus.util.StringUtils;
35  
36  
37  /**
38   * A bean to format all source files according to code conventions.
39   *
40   * @author jruiz@exist.com
41   * @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a>
42   * @author <a href="mailto:ltheussl@apache.org">Lukas Theussl</a>
43   * @version $Id: JalopyBean.java 531612 2007-04-23 21:28:38Z ltheussl $
44   */
45  
46  public class JalopyBean
47  {
48      /** Log. */
49      private static final Log LOG = LogFactory.getLog( JalopyBean.class );
50  
51      /**
52       * Sets the file format of the output files.
53       * The file format controls what end of line character is used.
54       * Either one of "UNIX", "DOS", "MAC", "DEFAULT" or "AUTO" can be used.
55       */
56      private String fileFormat;
57  
58      /**
59       * Specifies the history policy to use.
60       * Either one of "COMMENT", "FILE" or "NONE" can be used.
61       */
62      private String historyPolicy;
63  
64      /**
65       * Indicates whether a run should be held if errors occured.
66       */
67      private boolean failOnError;
68  
69      /**
70       * Indicates whether to enable the code inspector.
71       */
72      private boolean inspect;
73  
74      /**
75       * Indicates whether keep backups of formatted source files.
76       */
77      private boolean backup;
78  
79      /**
80       * Indicates whether to force formatting of source files.
81       */
82      private boolean force;
83  
84      /**
85       * The source directory.
86       */
87      private File sourceDirectory;
88  
89      /**
90       *  The test source directory.
91       */
92      private File testSourceDirectory;
93  
94      /**
95       * Sets the preferences file to use - given either relative to
96       * the project's basedir or as an absolute local path or internet address.
97       * If omitted, the current preferences are used, if available.
98       * Otherwise the Jalopy build-in defaults will be used.
99       */
100     private File convention;
101 
102     /**
103      * For Source Directory. Specifies a fileset source file to format.
104      * This is a comma- or space-separated list of patterns of files.
105      */
106     private String srcIncludesPattern;
107 
108     /**
109      * For Source Directory. Source files excluded from format.
110      * This is a comma- or space-separated list of patterns of files.
111      */
112     private String srcExcludesPattern;
113 
114     /**
115      * For Test Directory. Specifies a fileset source file to format.
116      * This is a comma- or space-separated list of patterns of files.
117      */
118     private String testIncludesPattern;
119 
120     /**
121      * For Test Directory. Source files excluded from format.
122      * This is a comma- or space-separated list of patterns of files.
123      */
124     private String testExcludesPattern;
125 
126     /**
127      * The main method: starts formatting of source files.
128      *
129      * @throws Exception Exception
130      */
131     public void execute() throws Exception
132     {
133 
134         LOG.info("[jalopy] Jalopy Java Source Code Formatter " + Jalopy.getVersion());
135 
136         try
137         {
138             if ( getSourceDirectory().exists() )
139             {
140                 String[] filesToFormat = getIncludedFiles( getSourceDirectory(), getSrcIncludesPattern(),
141                                                            getSrcExcludesPattern() );
142 
143                 LOG.info( "[jalopy] Format " + filesToFormat.length + " source files in " + getSourceDirectory().toString() );
144                 formatFiles( getSourceDirectory(), filesToFormat );
145                 LOG.info( "[jalopy] " + filesToFormat.length + " source files formatted" );
146             }
147 
148             if ( getTestSourceDirectory().exists() )
149             {
150                 String[] filesToFormat = getIncludedFiles( getTestSourceDirectory(), getTestIncludesPattern(),
151                                                            getTestExcludesPattern() );
152 
153                 LOG.info( "[jalopy] Format " + filesToFormat.length + " source files in " + getTestSourceDirectory().toString() );
154                 formatFiles( getTestSourceDirectory(), filesToFormat );
155                 LOG.info( "[jalopy] " + filesToFormat.length + " source files formatted" );
156             }
157         }
158         catch ( Exception e )
159         {
160             e.printStackTrace();
161         }
162     }
163 
164     /**
165      * Returns a string array of files to format.
166      *
167      * @param directory The base directory
168      * @param includes The includes pattern
169      * @param excludes The excludes pattern
170      * @return String[]
171      */
172     private String[] getIncludedFiles( File directory, String includes, String excludes )
173     {
174         DirectoryScanner scanner = new DirectoryScanner();
175 
176         scanner.setBasedir( directory );
177 
178         scanner.setIncludes( StringUtils.split( includes, "," ) );
179 
180         scanner.setExcludes( StringUtils.split( excludes, "," ) );
181 
182         scanner.scan();
183 
184         String[] filesToFormat = scanner.getIncludedFiles();
185 
186         return filesToFormat;
187     }
188 
189     /**
190      * Formats the source files.
191      *
192      * @param directory The base directory
193      * @param filesToFormat A string array of files to format
194      * @throws FileNotFoundException FileNotFoundException
195      * @throws Exception Exception
196      */
197     private void formatFiles( File directory, String[] filesToFormat )
198         throws FileNotFoundException, Exception
199     {
200         Jalopy jalopy = createJalopy();
201 
202         for ( int i = 0; i < filesToFormat.length; i++ )
203         {
204             File currentFile = new File( directory, filesToFormat[i] );
205 
206             jalopy.setInput( currentFile );
207 
208             jalopy.setOutput( currentFile );
209 
210             if ( isBackup() )
211             {
212                 jalopy.setBackupDirectory( currentFile.getParentFile() );
213             }
214 
215             jalopy.format();
216 
217             logMessage( jalopy, currentFile );
218         }
219     }
220 
221     /**
222      * Logs a message depending on the jalopy exit status.
223      *
224      * @param jalopy The jalopy instance
225      * @param currentFile The file whose status is to be logged
226      * @throws Exception Exception
227      */
228     private void logMessage( Jalopy jalopy, File currentFile )
229         throws Exception
230     {
231 
232         if ( jalopy.getState() == Jalopy.State.OK )
233         {
234             LOG.debug( "[jalopy] " + currentFile + " formatted correctly." );
235         }
236         else if ( jalopy.getState() == Jalopy.State.WARN )
237         {
238             LOG.warn( "[jalopy] " + currentFile + " formatted with warnings." );
239         }
240         else if ( jalopy.getState() == Jalopy.State.ERROR )
241         {
242             LOG.error( "[jalopy] " + currentFile + " could not be formatted." );
243 
244             if ( isFailOnError() )
245             {
246                 throw new Exception( currentFile + " could not be formatted." );
247             }
248         }
249         else
250         {
251             LOG.warn( "[jalopy] " + currentFile + " formatted with unknown state." );
252         }
253     }
254 
255     /**
256      * Creates a new instance of a Jalopy formatter with all bean variables being set.
257      *
258      * @return Jalopy
259      */
260     private Jalopy createJalopy()
261     {
262         Jalopy jalopy = new Jalopy();
263 
264         try
265         {
266             if ( ( convention != null ) && convention.exists() )
267             {
268                 LOG.debug( "[jalopy] Using convention file : " + convention.getAbsoluteFile() );
269                 Jalopy.setConvention( convention );
270             }
271             else
272             {
273                 LOG.warn( "[jalopy] Convention file does not exist: " + convention.getAbsoluteFile() );
274                 LOG.warn( "[jalopy] Using default convention : jalopy.xml");
275                 InputStream in = this.getClass().getClassLoader().getResourceAsStream( "plugin-resources/jalopy.xml" );
276                 Convention.importSettings( in, Convention.EXTENSION_XML );
277             }
278         }
279         catch ( IOException ex )
280         {
281             ex.printStackTrace();
282         }
283 
284         jalopy.setFileFormat( getFileFormat() );
285 
286         jalopy.setInspect( isInspect() );
287 
288         if ( !getHistoryPolicy().equalsIgnoreCase( "none" ) )
289         {
290             jalopy.setHistoryPolicy( History.Policy.valueOf( getHistoryPolicy() ) );
291         }
292 
293         // TODO: what are the allowed values for historyMethod?
294         //Convention settings = Convention.getInstance();
295         //History.Method historyMethod = History.Method.valueOf( settings.get( ConventionKeys.HISTORY_METHOD,
296         //                                                                     ConventionDefaults.HISTORY_METHOD ) );
297         //jalopy.setHistoryMethod( historyMethod );
298 
299         jalopy.setBackup( isBackup() );
300 
301         jalopy.setForce( isForce() );
302 
303         return jalopy;
304     }
305 
306     /**
307      * Returns the fileFormat property.
308      *
309      * @return String
310      */
311     public String getFileFormat()
312     {
313         return fileFormat;
314     }
315 
316     /**
317      * Sets the fileFormat property.
318      *
319      * @param newfileFormat The new property
320      */
321     public void setFileFormat( String newfileFormat )
322     {
323         this.fileFormat = newfileFormat;
324     }
325 
326     /**
327      * Returns the failOnError property.
328      *
329      * @return boolean
330      */
331     public boolean isFailOnError()
332     {
333         return failOnError;
334     }
335 
336     /**
337      * Sets the failOnError property.
338      *
339      * @param newfailOnError The new property
340      */
341     public void setFailOnError( boolean newfailOnError )
342     {
343         this.failOnError = newfailOnError;
344     }
345 
346     /**
347      * Returns the inspect property.
348      *
349      * @return boolean
350      */
351     public boolean isInspect()
352     {
353         return inspect;
354     }
355 
356     /**
357      * Sets the inspect property.
358      *
359      * @param newinspect The new property
360      */
361     public void setInspect( boolean newinspect )
362     {
363         this.inspect = newinspect;
364     }
365 
366     /**
367      * Returns the backup property.
368      *
369      * @return boolean
370      */
371     public boolean isBackup()
372     {
373         return backup;
374     }
375 
376     /**
377      * Sets the backup property.
378      *
379      * @param newbackup The new property
380      */
381     public void setBackup( boolean newbackup )
382     {
383         this.backup = newbackup;
384     }
385 
386     /**
387      * Returns the force property.
388      *
389      * @return boolean
390      */
391     public boolean isForce()
392     {
393         return force;
394     }
395 
396     /**
397      * Sets the force property.
398      *
399      * @param newforce The new property
400      */
401     public void setForce( boolean newforce )
402     {
403         this.force = newforce;
404     }
405 
406     /**
407      * Returns the sourceDirectory property.
408      *
409      * @return File
410      */
411     public File getSourceDirectory()
412     {
413         return sourceDirectory;
414     }
415 
416     /**
417      * Sets the sourceDirectory property.
418      *
419      * @param newsourceDirectory The new property
420      */
421     public void setSourceDirectory( File newsourceDirectory )
422     {
423         this.sourceDirectory = newsourceDirectory;
424     }
425 
426     /**
427      * Returns the srcIncludesPattern property.
428      *
429      * @return String
430      */
431     public String getSrcIncludesPattern()
432     {
433         return srcIncludesPattern;
434     }
435 
436     /**
437      * Sets the srcIncludesPattern property.
438      *
439      * @param newsrcIncludesPattern The new property
440      */
441     public void setSrcIncludesPattern( String newsrcIncludesPattern )
442     {
443         this.srcIncludesPattern = newsrcIncludesPattern;
444     }
445 
446     /**
447      * Returns the srcExcludesPattern property.
448      *
449      * @return String
450      */
451     public String getSrcExcludesPattern()
452     {
453         return srcExcludesPattern;
454     }
455 
456     /**
457      * Sets the srcExcludesPattern property.
458      *
459      * @param newsrcExcludesPattern The new property
460      */
461     public void setSrcExcludesPattern( String newsrcExcludesPattern )
462     {
463         this.srcExcludesPattern = newsrcExcludesPattern;
464     }
465 
466     /**
467      * Returns the historyPolicy property.
468      *
469      * @return String
470      */
471     public String getHistoryPolicy()
472     {
473         return historyPolicy;
474     }
475 
476     /**
477      * Sets the historyPolicy property.
478      *
479      * @param newhistoryPolicy The new property
480      */
481     public void setHistoryPolicy( String newhistoryPolicy )
482     {
483         this.historyPolicy = newhistoryPolicy;
484     }
485 
486     /**
487      * Returns the convention property.
488      *
489      * @return File
490      */
491     public File getConvention()
492     {
493         return convention;
494     }
495 
496     /**
497      * Sets the convention property.
498      *
499      * @param newconvention The new property
500      */
501     public void setConvention( File newconvention )
502     {
503         this.convention = newconvention;
504     }
505 
506     /**
507      * Returns the testSourceDirectory property.
508      *
509      * @return File
510      */
511     public File getTestSourceDirectory()
512     {
513         return testSourceDirectory;
514     }
515 
516     /**
517      * Sets the testSourceDirectory property.
518      *
519      * @param newtestSourceDirectory The new property
520      */
521     public void setTestSourceDirectory( File newtestSourceDirectory )
522     {
523         this.testSourceDirectory = newtestSourceDirectory;
524     }
525 
526     /**
527      * Returns the testIncludesPattern property.
528      *
529      * @return String
530      */
531     public String getTestIncludesPattern()
532     {
533         return testIncludesPattern;
534     }
535 
536     /**
537      * Sets the testIncludesPattern property.
538      *
539      * @param newtestIncludesPattern The new property
540      */
541     public void setTestIncludesPattern( String newtestIncludesPattern )
542     {
543         this.testIncludesPattern = newtestIncludesPattern;
544     }
545 
546     /**
547      * Returns the testExcludesPattern property.
548      *
549      * @return String
550      */
551     public String getTestExcludesPattern()
552     {
553         return testExcludesPattern;
554     }
555 
556     /**
557      * Sets the testExcludesPattern property.
558      *
559      * @param newtestExcludesPattern The new property
560      */
561     public void setTestExcludesPattern( String newtestExcludesPattern )
562     {
563         this.testExcludesPattern = newtestExcludesPattern;
564     }
565 }