Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 77026 | Differences between
and this patch

Collapse All | Expand All

(-)plugin.xml (+24 lines)
Lines 90-95 Link Here
90
               id="org.eclipse.releng.tools.fixCopyrights">
90
               id="org.eclipse.releng.tools.fixCopyrights">
91
         </action>
91
         </action>
92
      </objectContribution>
92
      </objectContribution>
93
      <objectContribution
94
            objectClass="org.eclipse.core.resources.IResource"
95
            id="org.eclipse.releng.internal.tools.AdvancedCopyrightContribution">
96
         <action
97
               label="Advanced Fix Copyrights..."
98
               class="org.eclipse.releng.tools.AdvancedFixCopyrightAction"
99
               menubarPath="additions"
100
               enablesFor="+"
101
               id="org.eclipse.releng.tools.advancedFixCopyrights">
102
         </action>
103
      </objectContribution>
93
   </extension>
104
   </extension>
94
   
105
   
95
   	<!-- ********** Action Sets ************** -->
106
   	<!-- ********** Action Sets ************** -->
Lines 110-114 Link Here
110
	  </actionSet>
121
	  </actionSet>
111
	</extension>
122
	</extension>
112
   
123
   
124
	<!-- ********** Preference Pages ************** -->
125
	<extension point="org.eclipse.ui.preferencePages">
126
      <page
127
            name="Copyright Tool"
128
            class="org.eclipse.releng.tools.preferences.CopyrightPreferencePage"
129
            id="org.eclipse.releng.tools.preferences.CopyrightPreferencePage">
130
      </page>
131
	</extension>
132
	
133
	<!-- ********** Preference Initializing ************** -->
134
	<extension point="org.eclipse.core.runtime.preferences">
135
		<initializer class="org.eclipse.releng.tools.preferences.RelEngPreferenceInitializer"/>
136
	</extension>
113
137
114
</plugin>
138
</plugin>
(-)src/org/eclipse/releng/tools/messages.properties (+8 lines)
Lines 48-50 Link Here
48
RelEngPlugin.2=maps
48
RelEngPlugin.2=maps
49
RelEngPlugin.3=RelEngPluginResources
49
RelEngPlugin.3=RelEngPluginResources
50
ProjectValidationDialog.2=Project Validation
50
ProjectValidationDialog.2=Project Validation
51
RelEngPreferenceInitializer.0=Copyright (c) ${date} IBM Corporation and others.\nAll rights reserved. This program and the accompanying materials\nare made available under the terms of the Eclipse Public License v1.0\nwhich accompanies this distribution, and is available at\nhttp://www.eclipse.org/legal/epl-v10.html\n\nContributors:\n    IBM Corporation - initial API and implementation
52
CopyrightPreferencePage.0=Use "${date}" to substitute in "creation_year, revision_year"
53
CopyrightPreferencePage.1=Default creation year:
54
CopyrightPreferencePage.2=Replace all existing copyright comments with this copyright template
55
CopyrightPreferencePage.3=Fix up existing copyright comments to follow copyright template format
56
CopyrightPreferencePage.4=Skip over properties files
57
CopyrightPreferencePage.5=Copyright template
58
CopyrightPreferencePage.6=Default creation year must be a positive number
(-)src/org/eclipse/releng/tools/AdvancedCopyrightComment.java (+301 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.releng.tools;
12
13
import java.io.PrintWriter;
14
import java.io.StringWriter;
15
import java.util.ArrayList;
16
import java.util.Iterator;
17
import java.util.List;
18
import java.util.StringTokenizer;
19
20
import org.eclipse.jface.preference.IPreferenceStore;
21
import org.eclipse.releng.tools.preferences.RelEngCopyrightConstants;
22
23
public class AdvancedCopyrightComment {
24
	private static final String DATE_VAR = "${date}"; //$NON-NLS-1$
25
	private static final String NEW_LINE = "\r\n"; //$NON-NLS-1$
26
	private static final String CARRIAGE_RETURN = "\r"; //$NON-NLS-1$
27
28
    public static final int UNKNOWN_COMMENT = -1;
29
    public static final int JAVA_COMMENT = 1;
30
    public static final int PROPERTIES_COMMENT = 2;
31
32
    private int commentStyle = 0;
33
    private int creationYear = -1;
34
    private int revisionYear = -1;
35
    private List contributors;
36
    private String preYearComment = null;
37
    private String postYearComment = null;
38
39
    private AdvancedCopyrightComment(int commentStyle, int creationYear, int revisionYear, List contributors, String preYearComment, String postYearComment) {
40
        this.commentStyle = commentStyle;
41
       	this.creationYear = creationYear == -1 ? getPreferenceStore().getInt(RelEngCopyrightConstants.CREATION_YEAR_KEY) : creationYear;
42
        this.revisionYear = revisionYear;
43
        this.contributors = contributors;
44
        this.preYearComment = preYearComment;
45
        this.postYearComment = postYearComment;
46
    }
47
    
48
    private AdvancedCopyrightComment(int commentStyle, int creationYear, int revisionYear, List contributors) {
49
    	this(commentStyle, creationYear, revisionYear, contributors, null, null);
50
    }
51
52
    public static AdvancedCopyrightComment defaultComment(int commentStyle) {
53
        return new AdvancedCopyrightComment(commentStyle, -1, -1, null);
54
    }
55
    
56
    public int getRevisionYear() {
57
        return revisionYear == -1 ? creationYear : revisionYear;
58
    }
59
60
    public void setRevisionYear(int year) {
61
        if (revisionYear != -1 || creationYear != year)
62
            revisionYear = year;
63
    }
64
65
    private static String getLinePrefix(int commentStyle) {
66
        switch(commentStyle) {
67
        case JAVA_COMMENT:
68
            return " * ";  //$NON-NLS-1$
69
        case PROPERTIES_COMMENT:
70
            return "# "; //$NON-NLS-1$
71
        default:
72
            return null;
73
        }
74
	}
75
76
	private void writeCommentStart(PrintWriter writer) {
77
	    switch(commentStyle) {
78
	    case JAVA_COMMENT:
79
			writer.println("/*******************************************************************************"); //$NON-NLS-1$
80
			break;
81
	    case PROPERTIES_COMMENT:
82
		    writer.println("###############################################################################"); //$NON-NLS-1$
83
		    break;
84
	    }
85
	}
86
87
	private void writeContributions(PrintWriter writer, String linePrefix) {
88
		writer.println(linePrefix);
89
		writer.println(linePrefix + "Contributors:"); //$NON-NLS-1$
90
91
		if (contributors == null || contributors.size() <= 0)
92
		    writer.println(linePrefix + "    IBM Corporation - initial API and implementation"); //$NON-NLS-1$
93
		else {
94
			Iterator i = contributors.iterator();
95
			while (i.hasNext())
96
			    writer.println(linePrefix + "    " + (String)i.next());  //$NON-NLS-1$
97
		}
98
	}
99
100
	private void writeCommentEnd(PrintWriter writer) {
101
	    switch(commentStyle) {
102
	    case JAVA_COMMENT:
103
			writer.println(" *******************************************************************************/"); //$NON-NLS-1$
104
			break;
105
	    case PROPERTIES_COMMENT:
106
		    writer.println("###############################################################################"); //$NON-NLS-1$
107
		    break;
108
	    }
109
	}
110
	
111
	/**
112
	 * Get the copyright tool preference store
113
	 * @return
114
	 */
115
    private static IPreferenceStore getPreferenceStore() {
116
    	return RelEngPlugin.getDefault().getPreferenceStore();
117
    }
118
	
119
	/**
120
	 * Get the copyright statement in form of an array of Strings where
121
	 * each item is a line of the copyright statement.
122
	 * @return String[]
123
	 */
124
	private static String[] getLegalLines() {
125
		StringTokenizer st = new StringTokenizer(getPreferenceStore().getString(RelEngCopyrightConstants.COPYRIGHT_TEMPLATE_KEY), CARRIAGE_RETURN+NEW_LINE, true);
126
		ArrayList lines = new ArrayList();
127
		String previous = NEW_LINE;
128
		while (st.hasMoreTokens()) {
129
			String current = st.nextToken();
130
			// add empty lines to array as well
131
			if (NEW_LINE.equals(previous) || CARRIAGE_RETURN.equals(previous)) {
132
				lines.add(current);
133
			}
134
			previous = current;
135
		}
136
		String[] stringLines = new String[lines.size()];
137
		stringLines = (String[])lines.toArray(stringLines); 
138
		return stringLines;
139
	}
140
	
141
	/**
142
	 * Return the body of this copyright comment or null if it cannot be built.
143
	 */
144
	public String getCopyrightComment() {
145
		// instead of overwriting an existing comment, just try to insert the new year
146
		if ((preYearComment != null || postYearComment != null) && (!getPreferenceStore().getBoolean(RelEngCopyrightConstants.FIX_UP_EXISTING_KEY))) {
147
			String copyrightString = preYearComment == null ? "" : preYearComment; //$NON-NLS-1$
148
			copyrightString = copyrightString + creationYear;
149
			
150
			if (revisionYear != -1 && revisionYear != creationYear)
151
		        copyrightString = copyrightString + ", " + revisionYear; //$NON-NLS-1$
152
			
153
			String endString = postYearComment == null ? "" : postYearComment; //$NON-NLS-1$
154
			copyrightString = copyrightString + postYearComment;
155
			return copyrightString;
156
		}
157
		
158
	    String linePrefix = getLinePrefix(commentStyle);
159
	    if (linePrefix == null)
160
	        return null;
161
162
	    StringWriter out = new StringWriter();
163
		PrintWriter writer = new PrintWriter(out);
164
		try {
165
		    writeCommentStart(writer);
166
			writeLegal(writer, linePrefix);
167
			// dont do anything special with contributors right now
168
//			writeContributions(writer, linePrefix);
169
		    writeCommentEnd(writer);
170
171
			return out.toString();
172
		} finally {
173
		    writer.close();
174
		}
175
	}
176
	
177
	/**
178
	 * Write out the copyright statement, line by line, adding in the created/revision
179
	 * year as well as comment line prefixes.
180
	 * 
181
	 * @param writer
182
	 * @param linePrefix
183
	 */
184
	private void writeLegal(PrintWriter writer, String linePrefix) {
185
		String[] legalLines = getLegalLines();
186
		for (int i=0; i < legalLines.length; ++i) {
187
			String currentLine = legalLines[i];
188
			int offset = currentLine.indexOf(DATE_VAR);
189
			// if this is the line, containing the ${date}, add in the year
190
			if (offset > -1) {
191
				writer.print(linePrefix + currentLine.substring(0, offset)+creationYear);
192
				if (revisionYear != -1 && revisionYear != creationYear)
193
			        writer.print(", " + revisionYear); //$NON-NLS-1$
194
				writer.println(currentLine.substring(offset+DATE_VAR.length(), currentLine.length()));
195
			} else {
196
				// just write out the line
197
				if (NEW_LINE.equals(currentLine) || CARRIAGE_RETURN.equals(currentLine)) {
198
					// handle empty lines
199
					writer.print(linePrefix + currentLine);
200
				} else {
201
					writer.println(linePrefix + currentLine);
202
				}
203
			}
204
		}
205
	}
206
	
207
    /**
208
     * Create an instance the same as the argument comment but with the revision year
209
     * updated if needed.  Return the default comment if the argument comment is null
210
     * or an empty string.  Return null if the argument comment is not recognized as
211
     * an IBM copyright comment.
212
     */
213
    public static AdvancedCopyrightComment parse(BlockComment comment, int commentStyle) {
214
    	AdvancedCopyrightComment copyright = null;
215
        
216
    	if (comment == null) {
217
    		copyright = defaultComment(commentStyle);
218
    	} else {
219
    		// To make the comment search a little more flexible, the parse algorithm will 
220
    		// only parse the line containing the ${date}
221
	   	    String body = comment.getContents();
222
	   	    
223
	   	    // find the line with ${date}
224
	   	    String[] legalLines = getLegalLines();
225
	   	    int i = 0;
226
	   	    int yearOffset = -1;
227
	   	    while (i < legalLines.length && yearOffset == -1) {
228
	   	    	String line = legalLines[i];
229
	   	    	yearOffset = line.indexOf(DATE_VAR);
230
	   	    	++i;
231
	   	    }
232
	   	    // ${date} found
233
	   	    if (yearOffset != -1) {
234
	   	    	String yearLine = legalLines[i-1];
235
	   	   	    // split that line up and just search for the contents before and after
236
	   	    	// NOTE: this won't really work well if the text surrounding the year is
237
	   	    	// generic, or if the year is at the beginning or end of the line
238
	   	    	String preYear = yearLine.substring(0, yearOffset);
239
	   	    	String postYear = yearLine.substring(yearOffset+DATE_VAR.length(), yearLine.length());
240
	   	    	
241
	   	    	int preYearOffset = body.indexOf(preYear);
242
	   	    	if (preYearOffset != -1) {
243
	   	    		int postYearOffset = body.indexOf(postYear, preYearOffset);
244
	   	    		if (postYearOffset != -1) {
245
	   	    	   	    // then you know between that is the year
246
	   	    			String yearRange = body.substring(preYearOffset+preYear.length(), postYearOffset);
247
	   	    	   	    int comma = yearRange.indexOf(","); //$NON-NLS-1$
248
	
249
	   	    	   	    String startStr = comma == -1 ? yearRange : yearRange.substring(0, comma);
250
	   	    	   	    String endStr = comma == -1 ? null : yearRange.substring(comma + 1);
251
	
252
	   	    	   	    int startYear = -1;
253
	   	    	   	    if (startStr != null)
254
	   	    		   	    try {
255
	   	    		   	        startYear = Integer.parseInt(startStr.trim());
256
	   	    		   	    } catch(NumberFormatException e) {
257
	   	    		   	        // do nothing
258
	   	    		   	    }
259
	
260
	   	    	   	    int endYear = -1;
261
	   	    	   	    if (endStr != null) {
262
	   	    	   	        try {
263
	   	    	   	            endYear = Integer.parseInt(endStr.trim());
264
	   	    	   	        } catch(NumberFormatException e) {
265
	   	    	   	            // do nothing
266
	   	    	   	        }
267
	   	    	   	    }
268
	   	    	   	    // save the copyright comment's contents before and after the year so that
269
	   	    	   	    // the comment will remain untouched rather than overwritten if the template is
270
	   	    	   	    // almost the same
271
	   	    	   	    String pre = body.substring(0, preYearOffset+preYear.length());
272
	   	    	   	    String post = body.substring(postYearOffset);
273
	   	    	   	     
274
	   	    	   	    copyright = new AdvancedCopyrightComment(commentStyle, startYear, endYear, null, pre, post);
275
	   	    		}
276
	   	    	}
277
	   	    }
278
    	}
279
280
    	// don't do anything special with contributors right now
281
//   	    int contrib = body.indexOf("Contributors:", start); //$NON-NLS-1$
282
//   	    String contribComment = body.substring(contrib);
283
//   	    StringTokenizer tokens = new StringTokenizer(contribComment, "\r\n"); //$NON-NLS-1$
284
//   	    tokens.nextToken();
285
//   	    ArrayList contributors = new ArrayList();
286
//        String linePrefix = getLinePrefix(commentStyle);
287
//   	    while(tokens.hasMoreTokens()) {
288
//   	        String contributor = tokens.nextToken();
289
//   	        if (contributor.indexOf("***********************************") == -1 //$NON-NLS-1$
290
//   	         && contributor.indexOf("###################################") == -1) { //$NON-NLS-1$
291
//   	            int c = contributor.indexOf(linePrefix);
292
//   	            if (c != -1)
293
//   	                contributor = contributor.substring(c + linePrefix.length());
294
//   	            contributors.add(contributor.trim());
295
//   	        }
296
//   	    }
297
//
298
//        return new IBMCopyrightComment(commentStyle, startYear, endYear, contributors);
299
    	return copyright;
300
    }
301
}
(-)src/org/eclipse/releng/tools/AdvancedFixCopyrightAction.java (+337 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.releng.tools;
12
13
import java.io.File;
14
import java.io.FileNotFoundException;
15
import java.io.FileOutputStream;
16
import java.io.IOException;
17
import java.lang.reflect.InvocationTargetException;
18
import java.util.ArrayList;
19
import java.util.Calendar;
20
import java.util.GregorianCalendar;
21
import java.util.HashMap;
22
import java.util.Iterator;
23
import java.util.List;
24
import java.util.Map;
25
import java.util.Set;
26
27
import org.eclipse.core.resources.IFile;
28
import org.eclipse.core.resources.IResource;
29
import org.eclipse.core.resources.IResourceVisitor;
30
import org.eclipse.core.runtime.CoreException;
31
import org.eclipse.core.runtime.IAdaptable;
32
import org.eclipse.core.runtime.IProgressMonitor;
33
import org.eclipse.core.runtime.NullProgressMonitor;
34
import org.eclipse.core.runtime.Platform;
35
import org.eclipse.core.runtime.SubProgressMonitor;
36
import org.eclipse.jface.action.IAction;
37
import org.eclipse.jface.operation.IRunnableWithProgress;
38
import org.eclipse.jface.viewers.ISelection;
39
import org.eclipse.jface.viewers.IStructuredSelection;
40
import org.eclipse.releng.tools.preferences.RelEngCopyrightConstants;
41
import org.eclipse.team.core.TeamException;
42
import org.eclipse.team.internal.ccvs.core.ICVSRemoteFile;
43
import org.eclipse.team.internal.ccvs.core.ICVSRemoteResource;
44
import org.eclipse.team.internal.ccvs.core.ILogEntry;
45
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
46
import org.eclipse.ui.IActionDelegate;
47
import org.eclipse.ui.IObjectActionDelegate;
48
import org.eclipse.ui.IWorkbenchPart;
49
import org.eclipse.ui.PlatformUI;
50
51
public class AdvancedFixCopyrightAction implements IObjectActionDelegate {
52
53
    public class MyInnerClass implements IResourceVisitor {
54
        public IProgressMonitor monitor;
55
        public boolean visit(IResource resource) throws CoreException {
56
            if (resource.getType() == IResource.FILE) {
57
                processFile((IFile) resource, monitor);
58
            }
59
            return true;
60
        }
61
    }
62
63
    private String propertiesCopyright;
64
    private String javaCopyright;
65
    private String newLine = System.getProperty("line.separator"); //$NON-NLS-1$
66
    private Map log = new HashMap();
67
68
    // The current selection
69
    protected IStructuredSelection selection;
70
71
    private static final int currentYear = new GregorianCalendar().get(Calendar.YEAR);
72
73
    /**
74
     * Constructor for Action1.
75
     */
76
    public AdvancedFixCopyrightAction() {
77
        super();
78
    }
79
80
    /**
81
     * Returns the selected resources.
82
     * 
83
     * @return the selected resources
84
     */
85
    protected IResource[] getSelectedResources() {
86
        ArrayList resources = null;
87
        if (!selection.isEmpty()) {
88
            resources = new ArrayList();
89
            Iterator elements = selection.iterator();
90
            while (elements.hasNext()) {
91
                Object next = elements.next();
92
                if (next instanceof IResource) {
93
                    resources.add(next);
94
                    continue;
95
                }
96
                if (next instanceof IAdaptable) {
97
                    IAdaptable a = (IAdaptable) next;
98
                    Object adapter = a.getAdapter(IResource.class);
99
                    if (adapter instanceof IResource) {
100
                        resources.add(adapter);
101
                        continue;
102
                    }
103
                }
104
            }
105
        }
106
        if (resources != null && !resources.isEmpty()) {
107
            IResource[] result = new IResource[resources.size()];
108
            resources.toArray(result);
109
            return result;
110
        }
111
        return new IResource[0];
112
    }
113
114
    /**
115
     * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
116
     */
117
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
118
    }
119
120
    /**
121
     * @see IActionDelegate#run(IAction)
122
     */
123
    public void run(IAction action) {
124
125
        log = new HashMap();
126
        try {
127
            PlatformUI.getWorkbench().getProgressService().run(true, /* fork */
128
            true, /* cancellable */
129
            new IRunnableWithProgress() {
130
131
                public void run(IProgressMonitor monitor)
132
                        throws InvocationTargetException, InterruptedException {
133
                    try {
134
                    	long start = System.currentTimeMillis();
135
                        monitor.beginTask("Fixing copyrights...", //$NON-NLS-1$
136
                                IProgressMonitor.UNKNOWN);
137
138
                        System.out.println("Start Fixing Copyrights"); //$NON-NLS-1$
139
                        IResource[] results = getSelectedResources();
140
                        System.out.println("Resources selected: " //$NON-NLS-1$
141
                                + results.length);
142
                        for (int i = 0; i < results.length; i++) {
143
                            IResource resource = results[i];
144
                            System.out.println(resource.getName());
145
                            try {
146
                                MyInnerClass myInnerClass = new MyInnerClass();
147
                                myInnerClass.monitor = monitor;
148
                                resource.accept(myInnerClass);
149
                            } catch (CoreException e1) {
150
                                e1.printStackTrace();
151
                            }
152
                        }
153
154
                        writeLogs();
155
                   		displayLogs();
156
                        System.out.println("Done Fixing Copyrights"); //$NON-NLS-1$
157
                        long end = System.currentTimeMillis();
158
                        System.out.println("Total time: "+(end-start)+"ms"); //$NON-NLS-1$ //$NON-NLS-2$
159
160
                    } finally {
161
                        monitor.done();
162
                    }
163
                }
164
            });
165
        } catch (InvocationTargetException e) {
166
            // TODO Auto-generated catch block
167
            e.printStackTrace();
168
        } catch (InterruptedException e) {
169
            // TODO Auto-generated catch block
170
            e.printStackTrace();
171
        }
172
    }
173
174
    /**
175
     * Lookup and return the year in which the argument file was revised.  Return -1 if
176
     * the revision year cannot be found.
177
     */
178
    private int getCVSModificationYear(IFile file, IProgressMonitor monitor) {
179
        try {
180
            monitor.beginTask("Fetching logs from CVS", 100); //$NON-NLS-1$
181
182
            try {
183
                ICVSRemoteResource cvsFile = CVSWorkspaceRoot.getRemoteResourceFor(file);
184
                if (cvsFile != null) {
185
	                // get the log entry for the revision loaded in the workspace
186
	                ILogEntry entry = ((ICVSRemoteFile)cvsFile)
187
	                        .getLogEntry(new SubProgressMonitor(monitor, 100));
188
	                return entry.getDate().getYear() + 1900;
189
                }
190
            } catch (TeamException e) {
191
                // do nothing
192
            }
193
        } finally {
194
            monitor.done();
195
        }
196
197
        return -1;
198
    }
199
200
    /**
201
     *  
202
     */
203
    private void writeLogs() {
204
205
        FileOutputStream aStream;
206
        try {
207
            File aFile = new File(Platform.getLocation().toFile(),
208
                    "copyrightLog.txt"); //$NON-NLS-1$
209
            aStream = new FileOutputStream(aFile);
210
            Set aSet = log.entrySet();
211
            Iterator errorIterator = aSet.iterator();
212
            while (errorIterator.hasNext()) {
213
                Map.Entry anEntry = (Map.Entry) errorIterator.next();
214
                String errorDescription = (String) anEntry.getKey();
215
                aStream.write(errorDescription.getBytes());
216
                aStream.write(newLine.getBytes());
217
                List fileList = (List) anEntry.getValue();
218
                Iterator listIterator = fileList.iterator();
219
                while (listIterator.hasNext()) {
220
                    String fileName = (String) listIterator.next();
221
                    aStream.write("     ".getBytes()); //$NON-NLS-1$
222
                    aStream.write(fileName.getBytes());
223
                    aStream.write(newLine.getBytes());
224
                }
225
            }
226
            aStream.close();
227
        } catch (FileNotFoundException e) {
228
            e.printStackTrace();
229
        } catch (IOException e) {
230
            e.printStackTrace();
231
        }
232
    }
233
234
    private void displayLogs() {
235
236
        Set aSet = log.entrySet();
237
        Iterator errorIterator = aSet.iterator();
238
        while (errorIterator.hasNext()) {
239
            Map.Entry anEntry = (Map.Entry) errorIterator.next();
240
            String errorDescription = (String) anEntry.getKey();
241
            System.out.println(errorDescription);
242
            List fileList = (List) anEntry.getValue();
243
            Iterator listIterator = fileList.iterator();
244
            while (listIterator.hasNext()) {
245
                String fileName = (String) listIterator.next();
246
                System.out.println("     " + fileName); //$NON-NLS-1$
247
            }
248
        }
249
    }
250
251
    /**
252
     * @param file
253
     */
254
    private void processFile(IFile file, IProgressMonitor monitor) {
255
        SourceFile aSourceFile;
256
257
        String extension = file.getFileExtension();
258
        if (extension == null)
259
            return;
260
        monitor.subTask(file.getFullPath().toOSString());
261
        int fileType = AdvancedCopyrightComment.UNKNOWN_COMMENT;
262
        extension = extension.toLowerCase();
263
        if (extension.equals("java")) { //$NON-NLS-1$
264
        	fileType = AdvancedCopyrightComment.JAVA_COMMENT;
265
            aSourceFile = new JavaFile(file);
266
        } else if (extension.equals("properties")) { //$NON-NLS-1$
267
        	// if stop processing if ignoring properties files
268
        	if (RelEngPlugin.getDefault().getPreferenceStore().getBoolean(RelEngCopyrightConstants.IGNORE_PROPERTIES_KEY)) {
269
        		return;
270
        	}
271
        	fileType = AdvancedCopyrightComment.PROPERTIES_COMMENT;
272
            aSourceFile = new PropertiesFile(file);
273
        } else
274
            return;
275
276
        if (aSourceFile.hasMultipleCopyrights()) {
277
            warn(file, null, "Multiple copyrights found.  File UNCHANGED."); //$NON-NLS-1$//$NON-NLS-2$
278
            return;
279
        }
280
281
        BlockComment copyrightComment = aSourceFile.firstCopyrightComment();
282
        AdvancedCopyrightComment ibmCopyright = AdvancedCopyrightComment.parse(copyrightComment, fileType);
283
        if (ibmCopyright == null) {
284
        	// if replacing all existing comments, use default copyright comment
285
        	if (RelEngPlugin.getDefault().getPreferenceStore().getBoolean(RelEngCopyrightConstants.REPLACE_ALL_EXISTING_KEY)) {
286
                warn(file, copyrightComment, "Could not interpret copyright comment, using default comment"); //$NON-NLS-1$
287
        		ibmCopyright = AdvancedCopyrightComment.defaultComment(fileType);
288
        	} else {
289
                warn(file, copyrightComment, "Could not interpret copyright comment"); //$NON-NLS-1$
290
                return;
291
        	}
292
        }
293
294
        // figure out if the comment should be updated by comparing the date range
295
        // in the comment to the last modification time provided by CVS
296
297
        int revised = ibmCopyright.getRevisionYear();
298
        int lastMod = revised;
299
        if (lastMod < currentYear)
300
            lastMod = getCVSModificationYear(file, new NullProgressMonitor());
301
302
        // only exit if existing copyright comment already contains the year
303
        // of last modification
304
        if (lastMod <= revised && (copyrightComment != null))
305
            return;
306
307
        // either replace old copyright or put the new one at the top of the file
308
        ibmCopyright.setRevisionYear(lastMod);
309
        if (copyrightComment == null)
310
            aSourceFile.insert(ibmCopyright.getCopyrightComment());
311
        else {
312
            if (!copyrightComment.atTop())
313
                warn(file, copyrightComment, "Old copyright not at start of file, new copyright replaces old in same location"); //$NON-NLS-1$
314
            aSourceFile.replace(copyrightComment, ibmCopyright.getCopyrightComment());
315
        }
316
    }
317
318
    private void warn(IFile file, BlockComment firstBlockComment,
319
            String errorDescription) {
320
        List aList = (List) log.get(errorDescription);
321
        if (aList == null) {
322
            aList = new ArrayList();
323
            log.put(errorDescription, aList);
324
        }
325
        aList.add(file.getName());
326
    }
327
328
    /**
329
     * @see IActionDelegate#selectionChanged(IAction, ISelection)
330
     */
331
    public void selectionChanged(IAction action, ISelection selection) {
332
        if (selection instanceof IStructuredSelection) {
333
            this.selection = (IStructuredSelection) selection;
334
        }
335
    }
336
337
}
(-)src/org/eclipse/releng/tools/preferences/CopyrightPreferencePage.java (+305 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.releng.tools.preferences;
12
13
import org.eclipse.jface.preference.IPreferenceStore;
14
import org.eclipse.jface.preference.PreferencePage;
15
import org.eclipse.jface.text.Document;
16
import org.eclipse.jface.text.IDocument;
17
import org.eclipse.jface.text.source.SourceViewer;
18
import org.eclipse.jface.text.source.SourceViewerConfiguration;
19
import org.eclipse.releng.tools.Messages;
20
import org.eclipse.releng.tools.RelEngPlugin;
21
import org.eclipse.swt.SWT;
22
import org.eclipse.swt.events.KeyAdapter;
23
import org.eclipse.swt.events.KeyEvent;
24
import org.eclipse.swt.events.KeyListener;
25
import org.eclipse.swt.events.SelectionAdapter;
26
import org.eclipse.swt.events.SelectionEvent;
27
import org.eclipse.swt.events.SelectionListener;
28
import org.eclipse.swt.graphics.Font;
29
import org.eclipse.swt.layout.GridData;
30
import org.eclipse.swt.layout.GridLayout;
31
import org.eclipse.swt.widgets.Button;
32
import org.eclipse.swt.widgets.Composite;
33
import org.eclipse.swt.widgets.Control;
34
import org.eclipse.swt.widgets.Label;
35
import org.eclipse.swt.widgets.Text;
36
import org.eclipse.ui.IWorkbench;
37
import org.eclipse.ui.IWorkbenchPreferencePage;
38
39
/**
40
 * Copyright tools preference page
41
 */
42
public class CopyrightPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
43
	private Composite fComposite;
44
	private Label fCopyrightLabel;
45
	private SourceViewer fEditor;
46
	private Text fInstructions;
47
	private Label fCreationYearLabel;
48
	private Text fCreationYear;
49
	private Button fReplaceAllExisting;
50
	private Button fFixExisting;
51
	private Button fIgnoreProperties;
52
	
53
	/* (non-Javadoc)
54
	 * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
55
	 */
56
	public void init(IWorkbench workbench) {
57
		// TODO Auto-generated method stub
58
59
	}
60
	/* (non-Javadoc)
61
	 * @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
62
	 */
63
	protected Control createContents(Composite parent) {
64
		Font font = parent.getFont();
65
66
		//The main composite
67
		fComposite = new Composite(parent, SWT.NONE);
68
		GridLayout layout = new GridLayout();
69
		layout.numColumns = 2;
70
		layout.marginWidth = 0;
71
		layout.marginHeight = 0;
72
		fComposite.setLayout(layout);
73
		fComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
74
		fComposite.setFont(font);
75
76
		// copyright template editor
77
		fEditor = createEditor(fComposite);
78
		
79
		GridData data = new GridData(GridData.FILL_HORIZONTAL);
80
		data.horizontalSpan = 2;
81
		data.horizontalIndent = 0;
82
		fInstructions = new Text(fComposite, SWT.READ_ONLY);
83
		fInstructions.setText(Messages.getString("CopyrightPreferencePage.0")); //$NON-NLS-1$
84
		fInstructions.setLayoutData(data);
85
		
86
		// default creation year
87
		fCreationYearLabel = new Label(fComposite, SWT.NONE);
88
		fCreationYearLabel.setText(Messages.getString("CopyrightPreferencePage.1")); //$NON-NLS-1$
89
		fCreationYear = new Text(fComposite, SWT.BORDER);
90
		fCreationYear.setTextLimit(4);
91
		
92
		// replace all existing copyright statement
93
		fReplaceAllExisting = new Button(fComposite, SWT.CHECK);
94
		fReplaceAllExisting.setText(Messages.getString("CopyrightPreferencePage.2")); //$NON-NLS-1$
95
		data = new GridData();
96
		data.horizontalSpan = 2;
97
		fReplaceAllExisting.setLayoutData(data);
98
		
99
		// fix up existing copyright statement
100
		fFixExisting = new Button(fComposite, SWT.CHECK);
101
		fFixExisting.setText(Messages.getString("CopyrightPreferencePage.3")); //$NON-NLS-1$
102
		data = new GridData();
103
		data.horizontalSpan = 2;
104
		fFixExisting.setLayoutData(data);
105
		
106
		// ignore properties files
107
		fIgnoreProperties = new Button(fComposite, SWT.CHECK);
108
		fIgnoreProperties.setText(Messages.getString("CopyrightPreferencePage.4")); //$NON-NLS-1$
109
		data = new GridData();
110
		data.horizontalSpan = 2;
111
		fIgnoreProperties.setLayoutData(data);
112
		
113
		KeyListener listener1 = new KeyAdapter() {
114
			/* (non-Javadoc)
115
			 * @see org.eclipse.swt.events.KeyAdapter#keyReleased(org.eclipse.swt.events.KeyEvent)
116
			 */
117
			public void keyReleased(KeyEvent e) {
118
				validateValues();
119
			}
120
		};
121
		fCreationYear.addKeyListener(listener1);
122
		
123
		SelectionListener listener2 = new SelectionAdapter() {
124
			public void widgetSelected(SelectionEvent e) {
125
				handleReplaceAllEnabled(fReplaceAllExisting.getSelection(), fFixExisting.getSelection());
126
			}
127
		};
128
		fReplaceAllExisting.addSelectionListener(listener2);
129
		
130
		initializeValues();
131
		return fComposite;
132
	}
133
134
	/**
135
	 * Create the sourceviewer editor to be used to edit the copyright template
136
	 */
137
	private SourceViewer createEditor(Composite parent) {
138
		fCopyrightLabel = new Label(parent, SWT.NONE);
139
		fCopyrightLabel.setText(Messages.getString("CopyrightPreferencePage.5")); //$NON-NLS-1$
140
		GridData data= new GridData();
141
		data.horizontalSpan= 2;
142
		fCopyrightLabel.setLayoutData(data);
143
		
144
		SourceViewer viewer= createViewer(parent);
145
146
		IDocument document= new Document();
147
		viewer.setEditable(true);
148
		viewer.setDocument(document);
149
		
150
		// just use a default 10 lines
151
		int nLines = 10;
152
//		int nLines= document.getNumberOfLines();
153
//		if (nLines < 5) {
154
//			nLines= 5;
155
//		} else if (nLines > 12) {
156
//			nLines= 12;	
157
//		}
158
				
159
		Control control= viewer.getControl();
160
		data= new GridData(GridData.FILL_HORIZONTAL);
161
		data.widthHint= convertWidthInCharsToPixels(80);
162
		data.heightHint= convertHeightInCharsToPixels(nLines);
163
		data.horizontalSpan = 2;
164
		control.setLayoutData(data);
165
		
166
		// TODO add content assist support
167
//		viewer.addTextListener(new ITextListener() {
168
//			public void textChanged(TextEvent event) {
169
//				if (event.getDocumentEvent() != null)
170
//					doSourceChanged(event.getDocumentEvent().getDocument());
171
//			}
172
//		});
173
//
174
//		viewer.addSelectionChangedListener(new ISelectionChangedListener() {			
175
//			public void selectionChanged(SelectionChangedEvent event) {
176
//				updateSelectionDependentActions();
177
//			}
178
//		});
179
//
180
//	 	viewer.prependVerifyKeyListener(new VerifyKeyListener() {
181
//			public void verifyKey(VerifyEvent event) {
182
//				handleVerifyKeyPressed(event);
183
//			}
184
//		});
185
		
186
		return viewer;
187
	}
188
	
189
	/**
190
	 * Creates the viewer to be used to display the copyright.
191
	 * 
192
	 * @param parent the parent composite of the viewer
193
	 * @return a configured <code>SourceViewer</code>
194
	 */
195
	private SourceViewer createViewer(Composite parent) {
196
		SourceViewer viewer= new SourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
197
		SourceViewerConfiguration configuration= new SourceViewerConfiguration() {
198
			// TODO add content assist support
199
//			public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
200
//				
201
//				ContentAssistant assistant= new ContentAssistant();
202
//				assistant.enableAutoActivation(true);
203
//				assistant.enableAutoInsert(true);
204
//				assistant.setContentAssistProcessor(fTemplateProcessor, IDocument.DEFAULT_CONTENT_TYPE);
205
//				return assistant;
206
//			}
207
		};
208
		viewer.configure(configuration);
209
		return viewer;
210
	}
211
	
212
	/**
213
	 * Initialize the control values in this preference page
214
	 */
215
	private void initializeValues() {
216
		IPreferenceStore store = getPreferenceStore();
217
218
		fEditor.getDocument().set(store.getString(RelEngCopyrightConstants.COPYRIGHT_TEMPLATE_KEY));
219
		fCreationYear.setText(store.getString(RelEngCopyrightConstants.CREATION_YEAR_KEY));
220
		fReplaceAllExisting.setSelection(store.getBoolean(RelEngCopyrightConstants.REPLACE_ALL_EXISTING_KEY));
221
		handleReplaceAllEnabled(fReplaceAllExisting.getSelection(), store.getBoolean(RelEngCopyrightConstants.FIX_UP_EXISTING_KEY));
222
		fIgnoreProperties.setSelection(store.getBoolean(RelEngCopyrightConstants.IGNORE_PROPERTIES_KEY));		
223
	}
224
	
225
	/**
226
	 * Validate the control values in this preference page
227
	 */
228
	private void validateValues() {
229
		String ERROR_MESSAGE = Messages.getString("CopyrightPreferencePage.6"); //$NON-NLS-1$
230
		
231
		String errorMsg = null;
232
		
233
		// creation year must be an integer
234
		String creationYear = fCreationYear.getText();
235
		try {
236
			int year = Integer.parseInt(creationYear);
237
			if (year < 0) {
238
				errorMsg = ERROR_MESSAGE;
239
			}
240
		} catch (NumberFormatException e) {
241
			errorMsg = ERROR_MESSAGE;
242
		}
243
		setErrorMessage(errorMsg);
244
		setValid(errorMsg == null);
245
	}
246
	
247
	/**
248
	 * Handles when the Replace all copyrights checkbox is checked/unchecked.
249
	 * When checked, fix up copyright checkbox is disabled and checked
250
	 * When unchecked, fix up copyright checkbox is enabled and set to default value 
251
	 * @param replaceAll
252
	 * @param defaultValue
253
	 */
254
	private void handleReplaceAllEnabled(boolean replaceAll, boolean defaultValue) {
255
		if (fReplaceAllExisting.isEnabled() && !replaceAll)
256
			fFixExisting.setEnabled(true);
257
		else
258
			fFixExisting.setEnabled(false);
259
		
260
		if (replaceAll) {
261
			fFixExisting.setSelection(replaceAll);
262
		} else {
263
			fFixExisting.setSelection(defaultValue);
264
		}
265
	}
266
267
	/* (non-Javadoc)
268
	 * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore()
269
	 */
270
	protected IPreferenceStore doGetPreferenceStore() {
271
		return RelEngPlugin.getDefault().getPreferenceStore();
272
	}
273
274
	/* (non-Javadoc)
275
	 * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
276
	 */
277
	protected void performDefaults() {
278
		IPreferenceStore store = getPreferenceStore();
279
		
280
		fEditor.getDocument().set(store.getDefaultString(RelEngCopyrightConstants.COPYRIGHT_TEMPLATE_KEY));
281
		fCreationYear.setText(store.getDefaultString(RelEngCopyrightConstants.CREATION_YEAR_KEY));
282
		fReplaceAllExisting.setSelection(getPreferenceStore().getDefaultBoolean(RelEngCopyrightConstants.REPLACE_ALL_EXISTING_KEY));
283
		handleReplaceAllEnabled(fReplaceAllExisting.getSelection(), getPreferenceStore().getDefaultBoolean(RelEngCopyrightConstants.FIX_UP_EXISTING_KEY));
284
		fIgnoreProperties.setSelection(getPreferenceStore().getDefaultBoolean(RelEngCopyrightConstants.IGNORE_PROPERTIES_KEY));
285
		
286
		super.performDefaults();
287
	}
288
	
289
	/* (non-Javadoc)
290
	 * @see org.eclipse.jface.preference.IPreferencePage#performOk()
291
	 */
292
	public boolean performOk() {
293
		IPreferenceStore store = getPreferenceStore();
294
295
		store.setValue(RelEngCopyrightConstants.COPYRIGHT_TEMPLATE_KEY, fEditor.getDocument().get());
296
		store.setValue(RelEngCopyrightConstants.CREATION_YEAR_KEY, fCreationYear.getText());
297
		store.setValue(RelEngCopyrightConstants.REPLACE_ALL_EXISTING_KEY, fReplaceAllExisting.getSelection());
298
		store.setValue(RelEngCopyrightConstants.FIX_UP_EXISTING_KEY, fFixExisting.getSelection());
299
		store.setValue(RelEngCopyrightConstants.IGNORE_PROPERTIES_KEY, fIgnoreProperties.getSelection());
300
		
301
		RelEngPlugin.getDefault().savePluginPreferences();
302
		
303
		return super.performOk();
304
	}
305
}
(-)src/org/eclipse/releng/tools/preferences/RelEngCopyrightConstants.java (+22 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.releng.tools.preferences;
12
13
/**
14
 * Contains all the constants used by the releng copyright tool
15
 */
16
public class RelEngCopyrightConstants {
17
	public final static String COPYRIGHT_TEMPLATE_KEY = "org.eclipse.releng.tools.copyrightTemplate"; //$NON-NLS-1$
18
	public final static String CREATION_YEAR_KEY = "org.eclipse.releng.tools.creationYear"; //$NON-NLS-1$
19
	public final static String FIX_UP_EXISTING_KEY = "org.eclipse.releng.tools.fixUpExisting"; //$NON-NLS-1$
20
	public final static String REPLACE_ALL_EXISTING_KEY = "org.eclipse.releng.tools.replaceAllExisting"; //$NON-NLS-1$
21
	public final static String IGNORE_PROPERTIES_KEY = "org.eclipse.releng.tools.ignoreProperties"; //$NON-NLS-1$
22
}
(-)src/org/eclipse/releng/tools/preferences/RelEngPreferenceInitializer.java (+36 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2004 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.releng.tools.preferences;
12
13
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
14
import org.eclipse.jface.preference.IPreferenceStore;
15
import org.eclipse.releng.tools.Messages;
16
import org.eclipse.releng.tools.RelEngPlugin;
17
18
/**
19
 * Initializes default preferences for release engineering tool
20
 */
21
public class RelEngPreferenceInitializer extends AbstractPreferenceInitializer {
22
	private final String LEGAL_LINE = Messages.getString("RelEngPreferenceInitializer.0"); //$NON-NLS-1$
23
	
24
	/* (non-Javadoc)
25
	 * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
26
	 */
27
	public void initializeDefaultPreferences() {
28
        IPreferenceStore store = RelEngPlugin.getDefault().getPreferenceStore();
29
        store.setDefault(RelEngCopyrightConstants.COPYRIGHT_TEMPLATE_KEY, LEGAL_LINE);
30
        store.setDefault(RelEngCopyrightConstants.CREATION_YEAR_KEY, 2003);
31
        store.setDefault(RelEngCopyrightConstants.FIX_UP_EXISTING_KEY, false);
32
        store.setDefault(RelEngCopyrightConstants.REPLACE_ALL_EXISTING_KEY, false);
33
        store.setDefault(RelEngCopyrightConstants.IGNORE_PROPERTIES_KEY, false);
34
	}
35
36
}

Return to bug 77026