Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 748d30608a242acc5b219187f1ca1e1bcde5152e (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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
/*
 * Copyright (c) 2015, 2016, 2018 Eike Stepper (Loehne, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v20.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.oomph.setup.presentation.templates;

import org.eclipse.oomph.base.Annotation;
import org.eclipse.oomph.base.BasePackage;
import org.eclipse.oomph.base.ModelElement;
import org.eclipse.oomph.base.util.BaseResourceImpl;
import org.eclipse.oomph.setup.AnnotationConstants;
import org.eclipse.oomph.setup.CompoundTask;
import org.eclipse.oomph.setup.Configuration;
import org.eclipse.oomph.setup.Installation;
import org.eclipse.oomph.setup.ProductVersion;
import org.eclipse.oomph.setup.Scope;
import org.eclipse.oomph.setup.SetupTask;
import org.eclipse.oomph.setup.Stream;
import org.eclipse.oomph.setup.VariableChoice;
import org.eclipse.oomph.setup.VariableTask;
import org.eclipse.oomph.setup.Workspace;
import org.eclipse.oomph.setup.editor.SetupTemplate;
import org.eclipse.oomph.setup.internal.core.SetupContext;
import org.eclipse.oomph.setup.internal.core.StringFilterRegistry;
import org.eclipse.oomph.setup.ui.PropertyField;
import org.eclipse.oomph.ui.LabelDecorator;
import org.eclipse.oomph.ui.UIUtil;
import org.eclipse.oomph.util.CollectionUtil;
import org.eclipse.oomph.util.IOUtil;
import org.eclipse.oomph.util.StringUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EStructuralFeature.Setting;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Internal;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.EcoreUtil.Copier;
import org.eclipse.emf.edit.provider.IItemFontProvider;
import org.eclipse.emf.edit.ui.provider.ExtendedFontRegistry;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Eike Stepper
 */
public class GenericSetupTemplate extends SetupTemplate
{
  private static final Pattern STRING_EXPANSION_PATTERN = Pattern.compile("\\$(\\{([^${}|/]+)(\\|([^{}/]+))?([^{}]*)}|\\$)");

  private static final Pattern GIT_REPOSITORY_URL_PATTERN = Pattern.compile("\\s*url\\s*=\\s*([^ ]+)");

  private final URI templateLocation;

  private Composite composite;

  private ModelElement setupModelElement;

  private final Map<VariableTask, PropertyField> fields = new LinkedHashMap<VariableTask, PropertyField>();

  private Set<PropertyField> dirtyFields = new HashSet<PropertyField>();

  private final Map<String, VariableTask> variables = new LinkedHashMap<String, VariableTask>();

  private Map<VariableTask, Set<EStructuralFeature.Setting>> usages;

  private PropertyField focusField;

  private final Map<EObject, Set<EStructuralFeature>> focusUsages = new HashMap<EObject, Set<EStructuralFeature>>();

  private LabelDecorator decorator;

  public GenericSetupTemplate(String label, URI templateLocation)
  {
    super(label);
    this.templateLocation = templateLocation;
  }

  @Override
  public Control createControl(Composite parent)
  {
    composite = new Composite(parent, SWT.NONE);

    GridLayout layout = new GridLayout(3, false);
    layout.marginWidth = 0;
    layout.marginHeight = 0;
    layout.horizontalSpacing = 10;
    layout.verticalSpacing = 10;
    composite.setLayout(layout);

    return composite;
  }

  @Override
  public String getMessage()
  {
    for (PropertyField field : fields.values())
    {
      if (StringUtil.isEmpty(field.getValue()))
      {
        return "";
      }
    }

    String location = expandString("${setup.location}", null);
    Path path = new Path(location);
    String[] segments = path.segments();

    if (segments.length == 0 || path.getDevice() != null)
    {
      return "The location '" + location + "' specified by the folder path is not a valid project path";
    }

    String projectName = segments[0];
    if (!path.isValidSegment(projectName))
    {
      return "The project '" + projectName + "' specified by the folder path is not a valid project name";
    }

    IProject project = EcorePlugin.getWorkspaceRoot().getProject(projectName);
    if (!project.isAccessible())
    {
      return "The project '" + projectName + "' specified by the folder path is not accessible";
    }

    IContainer container = project;
    for (int i = 1; i < segments.length; ++i)
    {
      String folderName = segments[i];
      if (!path.isValidSegment(folderName))
      {
        return "The folder segment '" + folderName + "' specified by the folder path is not a valid folder name";
      }

      IFile file = container.getFile(new Path(folderName));
      if (file.exists())
      {
        return "A file exists at '" + file.getFullPath() + "' specified by the folder path";
      }

      container = container.getFolder(new Path(folderName));
    }

    String filename = expandString("${setup.filename}", null);
    filename = expandString(filename, null);
    if (!path.isValidSegment(filename))
    {
      return "The filename '" + filename + "' is not a valid filename";
    }

    if (!filename.endsWith(".setup"))
    {
      return "The filename '" + filename + "' must use the file extension '.setup'";
    }

    IFile file = container.getFile(new Path(filename));
    if (file.exists())
    {
      return "The file '" + file.getFullPath() + "' already exists";
    }

    return null;
  }

  @Override
  public LabelDecorator getDecorator()
  {
    if (decorator == null)
    {
      decorator = new LabelDecorator()
      {
        @Override
        public Font decorateFont(Font font, Object element)
        {
          if (focusUsages.containsKey(element))
          {
            return ExtendedFontRegistry.INSTANCE.getFont(font, IItemFontProvider.BOLD_FONT);
          }

          if (element instanceof EStructuralFeature.Setting)
          {
            EStructuralFeature.Setting setting = (Setting)element;
            Set<EStructuralFeature> eStructuralFeatures = focusUsages.get(setting.getEObject());
            if (eStructuralFeatures != null && eStructuralFeatures.contains(setting.getEStructuralFeature()))
            {
              return ExtendedFontRegistry.INSTANCE.getFont(font, IItemFontProvider.BOLD_FONT);
            }
          }
          else if (element instanceof Resource)
          {
            VariableTask focusVariable = getFocusVariable();
            if (focusVariable != null)
            {
              String name = focusVariable.getName();
              if ("setup.location".equals(name) || "setup.filename".equals(name))
              {
                return ExtendedFontRegistry.INSTANCE.getFont(font, IItemFontProvider.BOLD_FONT);
              }
            }
          }

          return super.decorateFont(font, element);
        }
      };
    }

    return decorator;
  }

  private VariableTask getFocusVariable()
  {
    for (Map.Entry<VariableTask, PropertyField> entry : fields.entrySet())
    {
      if (entry.getValue() == focusField)
      {
        return entry.getKey();
      }
    }

    return null;
  }

  @Override
  public void updatePreview()
  {
    VariableTask focusVariable = getFocusVariable();
    if (focusVariable != null)
    {
      updateSelection(focusVariable);
    }
  }

  protected void updateSelection(VariableTask variable)
  {
    TreeViewer previewer = getContainer().getPreviewer();
    if (previewer != null)
    {
      focusUsages.clear();
      Set<Setting> settings = usages == null ? null : usages.get(variable);
      if (settings != null)
      {
        for (Setting setting : settings)
        {
          CollectionUtil.add(focusUsages, setting.getEObject(), setting.getEStructuralFeature());
        }
      }

      previewer.refresh(true);

      if (focusUsages.isEmpty())
      {
        String name = variable.getName();
        if ("setup.location".equals(name) || "setup.filename".equals(name))
        {
          previewer.setSelection(new StructuredSelection(getResource()), true);
        }
      }
      else
      {
        previewer.setSelection(new StructuredSelection(focusUsages.keySet().toArray()), true);
      }
    }
  }

  @Override
  protected void init()
  {
    super.init();

    Resource resource = getResource();
    ResourceSet resourceSet = resource.getResourceSet();
    setupModelElement = (ModelElement)resourceSet.getEObject(templateLocation, true);

    final Font normalFont = composite.getFont();
    final Font boldFont = ExtendedFontRegistry.INSTANCE.getFont(normalFont, IItemFontProvider.BOLD_FONT);

    CompoundTask compoundTask = (CompoundTask)setupModelElement.eResource().getEObject("template.variables");
    Control firstControl = null;
    VariableTask firstVariable = null;
    String defaultLocation = getContainer().getDefaultLocation();
    for (SetupTask setupTask : compoundTask.getSetupTasks())
    {
      final VariableTask variable = (VariableTask)setupTask;
      final PropertyField field = PropertyField.createField(variable);
      field.fill(composite);
      field.setValue(variable.getValue(), false);
      field.addValueListener(new PropertyField.ValueListener()
      {
        public void valueChanged(String oldValue, String newValue) throws Exception
        {
          dirtyFields.add(field);
          modelChanged(variable);
        }
      });

      field.getControl().addFocusListener(new FocusAdapter()
      {
        @Override
        public void focusGained(FocusEvent e)
        {
          if (focusField != null)
          {
            if (focusField != field)
            {
              focusField.getLabel().setFont(normalFont);
            }
          }

          if (focusField != field)
          {
            focusField = field;
            field.getLabel().setFont(boldFont);

            updateSelection(variable);
          }
        }
      });

      field.getLabel().setFont(boldFont);

      if (firstControl == null)
      {
        firstControl = field.getControl();
        firstVariable = variable;
      }

      variables.put(variable.getName(), variable);
      fields.put(variable, field);

      if ("setup.location".equals(variable.getName()))
      {
        field.setValue(defaultLocation);
      }
    }

    computeTemplateDefaults(true);

    Composite parent = composite.getParent();
    int currentHeight = composite.getSize().y;
    int newHeight = composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).y;
    GridData data = UIUtil.applyGridData(parent);
    data.heightHint = newHeight;

    if (currentHeight < newHeight)
    {
      Shell shell = parent.getShell();
      Point size = shell.getSize();
      shell.setSize(size.x, size.y + newHeight - currentHeight);
    }

    parent.setRedraw(false);
    parent.pack();
    parent.getParent().layout();

    for (PropertyField field : fields.values())
    {
      field.getLabel().setFont(normalFont);
    }

    parent.setRedraw(true);

    modelChanged(firstVariable);

    if (firstControl instanceof Text)
    {
      Text text = (Text)firstControl;
      text.selectAll();
    }

    firstControl.setFocus();
  }

  private void modelChanged(final VariableTask triggerVariable)
  {
    computeTemplateDefaults(false);

    Copier copier = new EcoreUtil.Copier();
    ModelElement copy = (ModelElement)copier.copy(setupModelElement);
    copier.copyReferences();

    Set<Resource> resources = new HashSet<Resource>();
    for (Map.Entry<EObject, EObject> entry : copier.entrySet())
    {
      EObject key = entry.getKey();
      if (key != setupModelElement)
      {
        Internal eDirectResource = ((InternalEObject)key).eDirectResource();
        if (eDirectResource != null)
        {
          Resource resource = new BaseResourceImpl(eDirectResource.getURI());
          resources.add(resource);
          resource.getContents().add(entry.getValue());
        }
      }
    }

    Set<PropertyField> originalDirtyPropertyFields = new HashSet<PropertyField>(dirtyFields);
    for (VariableTask variable : variables.values())
    {
      PropertyField field = fields.get(variable);
      if (!dirtyFields.contains(field))
      {
        String value = variable.getValue();
        if (!StringUtil.isEmpty(value))
        {
          value = expandString(value, null);
          field.setValue(value, false);
        }

        dirtyFields.add(field);
      }
    }

    usages = new HashMap<VariableTask, Set<EStructuralFeature.Setting>>();
    Set<EObject> eObjectsToDelete = new HashSet<EObject>();
    Set<Annotation> featureSubstitutions = new LinkedHashSet<Annotation>();
    for (Iterator<EObject> it = EcoreUtil.getAllContents(Collections.singleton(copy)); it.hasNext();)
    {
      InternalEObject eObject = (InternalEObject)it.next();
      for (EAttribute eAttribute : eObject.eClass().getEAllAttributes())
      {
        EDataType eAttributeType = eAttribute.getEAttributeType();
        Class<?> instanceClass = eAttributeType.getInstanceClass();
        if ((instanceClass == String.class || instanceClass == URI.class) && !eAttribute.isDerived())
        {
          if (!eAttribute.isMany())
          {
            String value = EcoreUtil.convertToString(eAttributeType, eObject.eGet(eAttribute));
            if (value != null)
            {
              Set<VariableTask> usedVariables = new HashSet<VariableTask>();
              String replacement = expandString(value, usedVariables);
              CollectionUtil.addAll(usages, usedVariables, eObject.eSetting(eAttribute));
              eObject.eSet(eAttribute, EcoreUtil.createFromString(eAttributeType, replacement));
            }
          }
        }
      }

      if (eObject instanceof Annotation)
      {
        Annotation annotation = (Annotation)eObject;
        if (AnnotationConstants.ANNOTATION_FEATURE_SUBSTITUTION.equals(annotation.getSource()))
        {
          featureSubstitutions.add(annotation);
          eObjectsToDelete.add(annotation);
        }
      }
      else if (eObject instanceof CompoundTask)
      {
        CompoundTask compoundTask = (CompoundTask)eObject;
        if ("template.variables".equals(compoundTask.getID()))
        {
          EObject eContainer = compoundTask.eContainer();
          eObjectsToDelete.add(eContainer instanceof Scope ? compoundTask : eContainer);
        }
      }
    }

    for (Annotation annotation : featureSubstitutions)
    {
      ModelElement modelElement = annotation.getModelElement();
      EClass eClass = modelElement.eClass();
      for (Map.Entry<String, String> detail : annotation.getDetails())
      {
        EStructuralFeature eStructuralFeature = eClass.getEStructuralFeature(detail.getKey());
        if (eStructuralFeature instanceof EAttribute)
        {
          try
          {
            modelElement.eSet(eStructuralFeature, EcoreUtil.createFromString(((EAttribute)eStructuralFeature).getEAttributeType(), detail.getValue()));
            for (Map.Entry<VariableTask, Set<Setting>> entry : usages.entrySet())
            {
              Set<Setting> settings = entry.getValue();
              for (Setting setting : settings)
              {
                if (setting.getEObject() == detail && setting.getEStructuralFeature() == BasePackage.Literals.STRING_TO_STRING_MAP_ENTRY__VALUE)
                {
                  settings.add(((InternalEObject)modelElement).eSetting(eStructuralFeature));
                  break;
                }
              }
            }
          }
          catch (RuntimeException ex)
          {
            // Ignore.
          }
        }
      }
    }

    for (EObject eObject : eObjectsToDelete)
    {
      EcoreUtil.delete(eObject);
    }

    for (Resource resource : resources)
    {
      URI uri = resource.getURI();
      String expandedURI = expandString(uri.toString(), null);
      resource.setURI(URI.createURI(expandedURI));
    }

    final Resource resource = getResource();

    final List<String> strings = new ArrayList<String>();
    final TreeViewer previewer = getContainer().getPreviewer();
    if (previewer != null)
    {
      for (Object object : previewer.getExpandedElements())
      {
        if (object instanceof EObject)
        {
          EObject eObject = (EObject)object;
          strings.add(resource.getURIFragment(eObject));
        }
      }

      previewer.getControl().setRedraw(false);
      updateResource(copy);

      UIUtil.asyncExec(new Runnable()
      {
        public void run()
        {
          if (!previewer.getControl().isDisposed())
          {
            List<EObject> eObjects = new ArrayList<EObject>();
            for (String fragment : strings)
            {
              EObject eObject = resource.getEObject(fragment);
              if (eObject != null)
              {
                eObjects.add(eObject);
              }
            }

            previewer.setExpandedElements(eObjects.toArray());
            updateSelection(triggerVariable);

            previewer.getControl().setRedraw(true);
          }
        }
      });
    }
    else
    {
      updateResource(copy);
    }

    dirtyFields = originalDirtyPropertyFields;

    getContainer().validate();
  }

  private void updateResource(ModelElement setup)
  {
    final Resource resource = getResource();

    EList<EObject> contents = resource.getContents();
    if (contents.isEmpty())
    {
      contents.add(setup);
    }
    else
    {
      contents.set(0, setup);
    }

    String location = expandString("${setup.location}", null);
    String fileName = expandString("${setup.filename}", null);
    resource.setURI(URI.createURI("platform:/resource" + new Path(location).makeAbsolute() + "/" + fileName));
  }

  private String expandString(String string, Set<VariableTask> usedVariables)
  {
    if (string == null)
    {
      return null;
    }

    StringBuilder result = new StringBuilder();
    int previous = 0;
    for (Matcher matcher = STRING_EXPANSION_PATTERN.matcher(string); matcher.find();)
    {
      result.append(string.substring(previous, matcher.start()));
      String key = matcher.group(1);
      if ("$".equals(key))
      {
        result.append('$');
      }
      else
      {
        key = matcher.group(2);
        String suffix = matcher.group(5);
        VariableTask variable = variables.get(key);
        if (variable == null)
        {
          result.append(matcher.group());
        }
        else
        {
          if (usedVariables != null)
          {
            usedVariables.add(variable);
          }

          PropertyField field = fields.get(variable);
          String value = dirtyFields.contains(field) ? field.getValue() : variable.getValue();
          if (StringUtil.isEmpty(value))
          {
            result.append(matcher.group());
          }
          else
          {
            String filters = matcher.group(4);
            if (filters != null)
            {
              for (String filterName : filters.split("\\|"))
              {
                value = filter(variable, value, filterName);
              }
            }

            result.append(value);
            result.append(suffix);
          }
        }
      }

      previous = matcher.end();
    }

    result.append(string.substring(previous));
    return result.toString();
  }

  private String filter(VariableTask variable, String value, String filterName)
  {
    if (filterName.equals("label"))
    {
      for (VariableChoice choice : variable.getChoices())
      {
        if (value.equals(choice.getValue()))
        {
          return choice.getLabel();
        }
      }
    }

    if (filterName.equals("firstSegment"))
    {
      URI uri = URI.createURI(value);
      return uri.segmentCount() > 0 ? uri.segment(0) : "";
    }

    if (filterName.equals("not"))
    {
      return "false".equals(value) ? "true" : "false";
    }

    if (filterName.equals("description"))
    {
      return value.startsWith("...") ? StringUtil.NL + "Before enabling this task, replace '...' with the repository path of this setup's containing project."
          : "";
    }

    if (filterName.equals("requiredJavaVersion"))
    {
      if ("Juno".equals(value))
      {
        return "1.5";
      }

      if ("Kepler".equals(value) || "Luna".equals(value))
      {
        return "1.6";
      }

      if ("Mars".equals(value))
      {
        return "1.7";
      }

      return "1.8";
    }

    if (filterName.equals("isClonePath"))
    {
      return filter(variable, value, "clonePath").startsWith("...") ? "false" : "true";
    }

    if (filterName.equals("clonePath"))
    {
      try
      {
        IProject project = EcorePlugin.getWorkspaceRoot().getProject(new Path(value).segment(0));
        IPath location = project.getLocation();
        StringBuilder path = new StringBuilder();
        if (location != null)
        {
          for (File file = location.toFile(); file != null; file = file.getParentFile())
          {
            File[] gitFile = file.listFiles(new FileFilter()
            {
              public boolean accept(File pathname)
              {
                return ".git".equals(pathname.getName());
              }
            });

            if (gitFile.length == 1)
            {
              return path.toString();
            }

            if (path.length() != 0)
            {
              path.insert(0, '/');
            }

            path.insert(0, file.getName());
          }

          return ".../" + location.segment(0);
        }
      }
      catch (Exception ex)
      {
        // Ignore.
      }

      return "...";
    }

    return StringFilterRegistry.INSTANCE.filter(value, filterName);
  }

  private void computeTemplateDefaults(boolean initial)
  {
    if (variables.containsKey("project.name"))
    {
      String fileLocation = expandString("${setup.location}", null);
      if (fileLocation != null)
      {
        Path path = new Path(fileLocation);
        if (path.segmentCount() > 0)
        {
          try
          {
            IProject project = EcorePlugin.getWorkspaceRoot().getProject(path.segment(0));
            IPath location = project.getLocation();
            if (location != null)
            {
              for (File file = location.toFile(); file != null; file = file.getParentFile())
              {
                File[] gitFile = file.listFiles(new FileFilter()
                {
                  public boolean accept(File pathname)
                  {
                    return ".git".equals(pathname.getName());
                  }
                });

                if (gitFile.length == 1)
                {
                  List<String> lines = IOUtil.readLines(new File(gitFile[0], "config"), "UTF-8");
                  for (String line : lines)
                  {
                    Matcher matcher = GIT_REPOSITORY_URL_PATTERN.matcher(line);
                    if (matcher.matches())
                    {
                      URI repositoryURI = URI.createURI(matcher.group(1));
                      String host = repositoryURI.host();
                      List<String> segments = repositoryURI.isHierarchical() ? repositoryURI.segmentsList()
                          : URI.createURI(repositoryURI.opaquePart()).segmentsList();
                      String firstSegment = segments.get(0);
                      String lastSegment = segments.get(segments.size() - 1);
                      List<String> qualifiedName = StringUtil.explode(lastSegment, ".-");
                      String projectRemoteURIs = null;
                      if ("git.eclipse.org".equals(host))
                      {
                        if ("r".equals(firstSegment) || "gitroot".equals(firstSegment))
                        {
                          segments.remove(0);
                        }

                        if ("r".equals(firstSegment) || repositoryURI.port() != null)
                        {
                          projectRemoteURIs = "eclipse.git.gerrit.remoteURIs";
                        }

                        if ("org".equals(qualifiedName.get(0)))
                        {
                          qualifiedName.remove(0);
                        }

                        if ("eclipse".equals(qualifiedName.get(0)))
                        {
                          qualifiedName.remove(0);
                        }
                      }
                      else if ("github.com".equals(host))
                      {
                        if ("eclipse".equals(firstSegment))
                        {
                          projectRemoteURIs = "github.remoteURIs";
                        }
                      }

                      String projectName = StringUtil.implode(qualifiedName, '.');

                      for (ListIterator<String> it = qualifiedName.listIterator(); it.hasNext();)
                      {
                        String nameSegment = it.next();
                        it.set(nameSegment.length() <= 4 ? nameSegment.toUpperCase() : StringUtil.cap(nameSegment));
                      }

                      String projectLabel = StringUtil.implode(qualifiedName, ' ');

                      applyVariableValue("project.label", projectLabel);
                      applyVariableValue("project.name", projectName);
                      applyVariableValue("project.git.path", StringUtil.implode(segments, '/'));
                      if (projectRemoteURIs != null)
                      {
                        applyVariableValue("project.remote.uris", projectRemoteURIs);
                      }

                      return;
                    }
                  }
                }
              }
            }
          }
          catch (Exception ex)
          {
            // Ignore.
          }

          String firstSegment = path.segment(0);
          List<String> qualifiedName = StringUtil.explode(firstSegment, ".-_ ");
          if (!qualifiedName.isEmpty())
          {
            ArrayList<String> domainPrefixes = new ArrayList<String>(Arrays.asList(Locale.getISOCountries()));
            domainPrefixes.add("COM");
            domainPrefixes.add("ORG");
            if (domainPrefixes.contains(qualifiedName.get(0).toUpperCase()))
            {
              qualifiedName.remove(0);
              if (qualifiedName.size() > 1)
              {
                qualifiedName.remove(0);
              }
            }

            String nameSegment = qualifiedName.get(0);
            String projectName = nameSegment.toLowerCase();
            String projectLabel = nameSegment.length() <= 4 ? nameSegment.toUpperCase() : StringUtil.cap(nameSegment);
            applyVariableValue("project.label", projectLabel);
            applyVariableValue("project.name", projectName);
            return;
          }
        }
      }

      restoreDefaultValue("project.label");
      restoreDefaultValue("project.name");
      restoreDefaultValue("project.git.path");
      restoreDefaultValue("project.remote.uris");
    }
    else if (initial && templateLocation.lastSegment().contains("Copy") && setupModelElement instanceof Configuration)
    {
      Configuration configuration = (Configuration)setupModelElement;
      SetupContext setupContext = SetupContext.create(setupModelElement.eResource().getResourceSet());

      Installation installation = configuration.getInstallation();
      if (installation != null)
      {
        Installation actualInstallation = setupContext.getInstallation();
        if (actualInstallation != null)
        {
          ProductVersion productVersion = actualInstallation.getProductVersion();
          if (productVersion != null)
          {
            Resource eResource = productVersion.eResource();
            if (eResource != null && !"catalog".equals(eResource.getURI().scheme()))
            {
              installation.setProductVersion(productVersion);
            }
          }

          copyContents(installation, actualInstallation);
          computeDefaultAttributes(installation, actualInstallation, "installation.");
        }
      }

      Workspace workspace = configuration.getWorkspace();
      if (workspace != null)
      {
        Workspace actualWorkspace = setupContext.getWorkspace();
        if (actualWorkspace != null)
        {
          EList<Stream> streams = actualWorkspace.getStreams();
          workspace.getStreams().addAll(streams);
          copyContents(workspace, actualWorkspace);
          computeDefaultAttributes(workspace, actualWorkspace, "workspace.");
        }
      }
    }
  }

  private void copyContents(Scope target, Scope source)
  {
    EList<Annotation> annotations = source.getAnnotations();
    EList<SetupTask> setupTasks = source.getSetupTasks();

    EcoreUtil.Copier copier = new EcoreUtil.Copier();
    Collection<Annotation> annotationCopies = copier.copyAll(annotations);
    Collection<SetupTask> setupTaskCopies = copier.copyAll(setupTasks);
    copier.copyReferences();

    target.getAnnotations().addAll(annotationCopies);
    target.getSetupTasks().addAll(setupTaskCopies);

    Set<EObject> eObjectsToDelete = new HashSet<EObject>();
    for (Iterator<EObject> it = target.eAllContents(); it.hasNext();)
    {
      EObject eObject = it.next();
      if (eObject instanceof SetupTask && !((SetupTask)eObject).getRestrictions().isEmpty())
      {
        eObjectsToDelete.add(eObject);
      }
    }

    EcoreUtil.deleteAll(eObjectsToDelete, true);
  }

  private void computeDefaultAttributes(Scope target, Scope source, String variablePrefix)
  {
    String name = source.getName();
    if (!StringUtil.isEmpty(name) && name != null && !(name + ".").equals(variablePrefix))
    {
      applyVariableValue(variablePrefix + "name", name);
    }

    String label = source.getLabel();
    if (!StringUtil.isEmpty(label))
    {
      applyVariableValue(variablePrefix + "label", label);
    }

    String description = source.getDescription();
    if (!StringUtil.isEmpty(description))
    {
      applyVariableValue(variablePrefix + "description", description);
    }
  }

  private void applyVariableValue(String name, String value)
  {
    VariableTask variable = variables.get(name);
    if (variable != null)
    {
      PropertyField field = fields.get(variable);
      if (!dirtyFields.contains(field))
      {
        if (variable.getDefaultValue() == null)
        {
          variable.setDefaultValue(variable.getValue());
        }
        variable.setValue(value);
        field.setValue(value, false);
      }
    }
  }

  private void restoreDefaultValue(String name)
  {
    VariableTask variable = variables.get(name);
    if (variable != null)
    {
      PropertyField field = fields.get(variable);
      if (!dirtyFields.contains(field))
      {
        String defaultValue = variable.getDefaultValue();
        if (defaultValue != null)
        {
          variable.setValue(defaultValue);
          field.setValue(defaultValue, false);
        }
      }
    }
  }
}

Back to the top