Skip to main content
summaryrefslogtreecommitdiffstats
blob: 39910e1c3e0111281cf92f0b04012104f3a39579 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
 * Copyright (c) 2013 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.emf.cdo.releng.gitbash.repository;

import org.eclipse.emf.cdo.releng.gitbash.AbstractAction;
import org.eclipse.emf.cdo.releng.gitbash.Activator;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Eike Stepper
 */
public class UpdateCopyrightsAction extends AbstractAction<Repository>
{
  private static final IWorkbench WORKBENCH = PlatformUI.getWorkbench();

  private static final String[] IGNORED_PATHS = { "resourcemanager.java", "menucardtemplate.java",
      "org.eclipse.emf.cdo.releng.version.tests/tests", "org.eclipse.net4j.jms.api/src" };

  private static final String[] REQUIRED_EXTENSIONS = { ".java", ".ant", "build.xml", "plugin.xml", "fragment.xml",
      "feature.xml", "plugin.properties", "fragment.properties", "feature.properties", "about.properties",
      "build.properties", "messages.properties", "copyright.txt", ".exsd", "org.eclipse.jdt.ui.prefs" };

  private static final String[] OPTIONAL_EXTENSIONS = { ".properties", ".xml", ".html", ".css", ".ecore", ".genmodel",
      ".mwe", ".xpt", ".ext" };

  private static final String[] IGNORED_MESSAGES = { "update copyrights", "updated copyrights", "adjust legal headers",
      "adjusted legal headers", "update legal headers", "updated legal headers", "adjust copyrights",
      "adjusted copyrights", "fix copyrights", "fixed copyrights", "fix legal headers", "fixed legal headers" };

  private static final Pattern COPYRIGHT_PATTERN = Pattern
      .compile("(.*?)Copyright \\(c\\) ([0-9 ,-]+) (.*?) and others\\.(.*)");

  private static final Calendar CALENDAR = GregorianCalendar.getInstance();

  private static final int CURRENT_YEAR = CALENDAR.get(Calendar.YEAR);

  private static final String NL = System.getProperty("line.separator");

  private Git git;

  private File workTree;

  private int workTreeLength;

  private List<String> missingCopyrights = new ArrayList<String>();

  private int rewriteCount;

  private int fileCount;

  public UpdateCopyrightsAction()
  {
    super(Repository.class);
  }

  protected boolean isCheckOnly()
  {
    return false;
  }

  @Override
  protected void run(final Shell shell, final Repository repository) throws Exception
  {
    IRunnableWithProgress runnable = new IRunnableWithProgress()
    {
      public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
      {
        try
        {
          git = new Git(repository);
          workTree = repository.getWorkTree();
          workTreeLength = workTree.getAbsolutePath().length() + 1;

          fileCount = countFiles(workTree);
          monitor.beginTask("Copyrights", fileCount);

          final long start = System.currentTimeMillis();
          checkFolder(monitor, workTree);

          shell.getDisplay().syncExec(new Runnable()
          {
            public void run()
            {
              try
              {
                handleResult(shell, workTree, formatDuration(start));
              }
              catch (Exception ex)
              {
                Activator.log(ex);
              }
            }
          });
        }
        catch (OperationCanceledException ex)
        {
          // Do nothing
        }
        catch (Exception ex)
        {
          throw new InvocationTargetException(ex);
        }
        finally
        {
          missingCopyrights.clear();
          rewriteCount = 0;
          fileCount = 0;
          workTree = null;
          git = null;
          monitor.done();
        }
      }
    };

    WORKBENCH.getProgressService().run(true, true, runnable);
  }

  private int countFiles(File folder) throws Exception
  {
    int count = 0;
    for (File file : folder.listFiles())
    {
      String fileName = file.getName();
      if (file.isDirectory() && !fileName.equals(".git"))
      {
        count += countFiles(file);
      }
      else
      {
        String path = getPath(file);
        if (hasString(path, IGNORED_PATHS))
        {
          continue;
        }

        ++count;
      }
    }

    return count;
  }

  private void checkFolder(IProgressMonitor monitor, File folder) throws Exception
  {
    for (File file : folder.listFiles())
    {
      if (monitor.isCanceled())
      {
        throw new OperationCanceledException();
      }

      String fileName = file.getName();
      if (file.isDirectory() && !fileName.equals(".git"))
      {
        checkFolder(monitor, file);
      }
      else
      {
        if (checkFile(monitor, file))
        {
          monitor.worked(1);
        }
      }
    }
  }

  private boolean checkFile(IProgressMonitor monitor, File file) throws Exception
  {
    String path = getPath(file);
    if (!hasString(path, IGNORED_PATHS))
    {
      boolean required = hasExtension(file, REQUIRED_EXTENSIONS);
      boolean optional = required || hasExtension(file, OPTIONAL_EXTENSIONS);

      if (optional)
      {
        monitor.subTask(path);

        List<String> lines = new ArrayList<String>();
        boolean copyrightFound = false;
        boolean copyrightChanged = false;

        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        try
        {
          String line;
          while ((line = bufferedReader.readLine()) != null)
          {
            Matcher matcher = COPYRIGHT_PATTERN.matcher(line);
            if (matcher.matches())
            {
              copyrightFound = true;
              if (isCheckOnly())
              {
                break;
              }

              String prefix = matcher.group(1);
              String dates = matcher.group(2);
              String owner = matcher.group(3);
              String suffix = matcher.group(4);

              String newLine = rewriteCopyright(path, line, prefix, dates, owner, suffix);
              if (newLine != line)
              {
                line = newLine;
                copyrightChanged = true;
              }
            }

            lines.add(line);
          }
        }
        finally
        {
          close(bufferedReader);
          close(fileReader);
        }

        if (required && !copyrightFound)
        {
          missingCopyrights.add(path);
        }

        if (copyrightChanged)
        {
          writeLines(file, lines);
          ++rewriteCount;
        }
      }

      return true;
    }

    return false;
  }

  private String rewriteCopyright(String path, String line, String prefix, String dates, String owner, String suffix)
      throws Exception
  {
    String newDates;

    if (path.endsWith("org.eclipse.jdt.ui.prefs") || path.endsWith("copyright.txt")
        || path.endsWith("org.eclipse.emf.cdo.license-feature/feature.properties")
        || suffix.equals(" All rights reserved.\\n\\"))
    {
      // Special handling of occurrences with a more global (then file-scoped) meaning.
      // Special handling of second occurrence in about.properties (which is visible in the UI).
      newDates = "2004-" + CURRENT_YEAR;
    }
    else
    {
      Set<Integer> years = new HashSet<Integer>();

      for (RevCommit commit : git.log().addPath(path).call())
      {
        String message = commit.getFullMessage().toLowerCase();
        if (!hasString(message, IGNORED_MESSAGES))
        {
          CALENDAR.setTimeInMillis(1000L * commit.getCommitTime());
          int year = CALENDAR.get(Calendar.YEAR);
          years.add(year);
        }
      }

      newDates = formatYears(years);
    }

    if (newDates.equals(dates))
    {
      return line;
    }

    return prefix + "Copyright (c) " + newDates + " " + owner + " and" + " others." + suffix;
  }

  private String formatYears(Collection<Integer> years)
  {
    class YearRange
    {
      private int begin;

      private int end;

      public YearRange(int begin)
      {
        this.begin = begin;
        end = begin;
      }

      public boolean add(int year)
      {
        if (year == end + 1)
        {
          end = year;
          return true;
        }

        return false;
      }

      @Override
      public String toString()
      {
        if (begin == end)
        {
          return "" + begin;
        }

        if (begin == end - 1)
        {
          return "" + begin + ", " + end;
        }

        return "" + begin + "-" + end;
      }
    }

    List<Integer> list = new ArrayList<Integer>(years);
    Collections.sort(list);

    List<YearRange> ranges = new ArrayList<YearRange>();
    YearRange lastRange = null;
    for (Integer year : list)
    {
      if (lastRange == null || !lastRange.add(year))
      {
        lastRange = new YearRange(year);
        ranges.add(lastRange);
      }
    }

    StringBuilder builder = new StringBuilder();
    for (YearRange range : ranges)
    {
      if (builder.length() != 0)
      {
        builder.append(", ");
      }

      builder.append(range);
    }

    return builder.toString();
  }

  private String getPath(File file)
  {
    String path = file.getAbsolutePath().replace('\\', '/');
    return path.substring(workTreeLength);
  }

  private boolean hasString(String string, String[] strings)
  {
    string = string.toLowerCase();
    for (int i = 0; i < strings.length; i++)
    {
      if (string.indexOf(strings[i]) != -1)
      {
        return true;
      }
    }

    return false;
  }

  private boolean hasExtension(File file, String[] extensions)
  {
    String fileName = file.getName().toLowerCase();
    for (int i = 0; i < extensions.length; i++)
    {
      if (fileName.endsWith(extensions[i]))
      {
        return true;
      }
    }

    return false;
  }

  private void handleResult(Shell shell, File workTree, String duration) throws PartInitException
  {
    String message = "Copyrights missing: " + missingCopyrights.size();
    message += "\nCopyrights rewritten: " + rewriteCount;
    message += "\nFiles visited: " + fileCount;
    message += "\nTime needed: " + duration;

    int size = missingCopyrights.size();
    if (size != 0)
    {
      StringBuilder builder = new StringBuilder(message);
      message += "\n\nCopyrights are missing in " + size + " files.\nDo you want to open them in editors?";
      if (MessageDialog.openQuestion(shell, "Missing Copyrights", message))
      {
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IWorkbenchPage page = WORKBENCH.getActiveWorkbenchWindow().getActivePage();

        builder.append("\n");
        for (String missingCopyright : missingCopyrights)
        {
          builder.append("\nMissing: ");
          builder.append(missingCopyright);

          File externalFile = new File(workTree, missingCopyright);
          IFile file = root.getFileForLocation(new Path(externalFile.getAbsolutePath()));
          if (file != null && file.isAccessible())
          {
            IDE.openEditor(page, file);
          }
          else
          {
            IFileStore fileStore = EFS.getLocalFileSystem().getStore(externalFile.toURI());
            if (fileStore != null)
            {
              IDE.openEditorOnFileStore(page, fileStore);
            }
          }
        }

        Activator.log(new Status(IStatus.WARNING, Activator.PLUGIN_ID, builder.toString()));
      }
    }
    else
    {
      MessageDialog.openInformation(shell, "Copyrights", message);
      Activator.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, message));
    }
  }

  private static String formatDuration(long start)
  {
    double duration = System.currentTimeMillis() - start;

    String unit = "milliseconds";
    if (duration > 1000d)
    {
      duration = duration / 1000d;
      unit = "seconds";

      if (duration > 60d)
      {
        duration = duration / 60d;
        unit = "minutes";

        if (duration > 60d)
        {
          duration = duration / 60d;
          unit = "hours";
        }
      }
    }

    duration = Math.round(duration * 100d) / 100d;
    return duration + " " + unit;
  }

  private static void writeLines(File file, List<String> lines) throws IOException
  {
    Writer fileWriter = null;
    BufferedWriter bufferedWriter = null;

    try
    {
      fileWriter = new FileWriter(file);
      bufferedWriter = new BufferedWriter(fileWriter);

      for (String line : lines)
      {
        bufferedWriter.write(line);
        bufferedWriter.write(NL);
      }
    }
    finally
    {
      close(bufferedWriter);
      close(fileWriter);
    }
  }

  private static void close(Closeable closeable)
  {
    if (closeable != null)
    {
      try
      {
        closeable.close();
      }
      catch (IOException ex)
      {
        Activator.log(ex);
      }
    }
  }
}

Back to the top