Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d268b650432bc43e9b1497261f6aacf4be543c90 (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
/*****************************************************************************
 * Copyright (c) 2016 Christian W. Damus 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:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.dev.project.management.internal.operations;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.osgi.service.resolver.BundleDescription;
import org.eclipse.osgi.service.resolver.BundleSpecification;
import org.eclipse.osgi.service.resolver.ExportPackageDescription;
import org.eclipse.pde.core.plugin.IPluginModelBase;
import org.eclipse.pde.core.plugin.PluginRegistry;
import org.osgi.framework.VersionRange;

/**
 * A context in which bundle dependency analysis is computed. It maintains
 * shared state for analysis of the dependencies of any number of bundles
 * in the workspace and PDE target.
 */
public class DependencyAnalysisContext {

	private final Map<String, BundleAnalysis> bundles = new HashMap<>();
	private final Map<String, BundleAnalysis> packageProviders = new HashMap<>();

	private final VersionRules versionRules = new VersionRules();

	private final Deque<SubMonitor> monitorStack = new LinkedList<SubMonitor>();
	private SubMonitor currentMonitor;

	private final Set<BundleAnalysis> roots;

	public DependencyAnalysisContext(Collection<? extends IFile> bundleManifests) {
		super();

		pushMonitor(new NullProgressMonitor());

		roots = Collections.unmodifiableSet(init(bundleManifests));
	}

	private Set<BundleAnalysis> init(Collection<? extends IFile> bundleManifests) {
		return bundleManifests.stream()
				.map(this::getBundleID)
				.filter(Objects::nonNull)
				.map(this::internalGetBundle)
				.map(BundleAnalysis::checkCycle) // Bombs the analysis if there's any dependency cycle
				.collect(Collectors.toSet());
	}

	private String getBundleID(IFile manifest) {
		IPluginModelBase model = PluginRegistry.findModel(manifest.getProject());
		return (model == null) ? null : model.getPluginBase().getId();
	}

	public Set<BundleAnalysis> getAnalysisRoots() {
		return roots;
	}

	public boolean isAnalysisRoot(String bundleID) {
		return roots.contains(internalGetBundle(bundleID));
	}

	public BundleAnalysis getBundle(String bundleID) {
		return internalGetBundle(bundleID).analyze();
	}

	private BundleAnalysis internalGetBundle(String bundleID) {
		return bundles.computeIfAbsent(bundleID, BundleAnalysis::new);
	}

	public BundleAnalysis getProvidingBundle(String packageName) {
		return packageProviders.computeIfAbsent(packageName, this::findPackageProvider);
	}

	private BundleAnalysis findPackageProvider(String packageName) {
		// Protect against concurrent modification
		return new ArrayList<>(bundles.values()).stream()
				.map(BundleAnalysis::getAPIExports)
				.filter(api -> api.exports(packageName))
				.findAny().map(APIExports::getBundle).orElse(null);
	}

	public final void pushMonitor(IProgressMonitor monitor) {
		currentMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(monitor);
		monitorStack.push(currentMonitor);
	}

	public final void popMonitor() {
		monitorStack.pop();
		currentMonitor = monitorStack.peek();
	}

	//
	// Nested types
	//

	/**
	 * An analysis of the transitive dependencies (by <tt>Require-Bundle</tt>) and public
	 * API exports of a bundle. Bundles sort dependencies before dependents.
	 */
	public class BundleAnalysis {
		private final String bundleID;

		private DependencyGraph dependencyGraph;
		private APIExports apiExports;

		private BundleAnalysis(String bundleID) {
			super();

			this.bundleID = bundleID;
		}

		public String getBundleID() {
			return bundleID;
		}

		public BundleAnalysis checkCycle() throws IllegalStateException {
			getDependencyGraph().checkCycle();
			return this;
		}

		public VersionRange getCompatibleVersionRange() {
			return getAPIExports().getCompatibleVersionRange();
		}

		public DependencyGraph getDependencyGraph() {
			analyze();
			return dependencyGraph;
		}

		public APIExports getAPIExports() {
			analyze();
			return apiExports;
		}

		public BundleAnalysis getDependency(String bundleID) {
			return getDependencyGraph().getDependency(bundleID);
		}

		public boolean isReexported(String bundleID) {
			return getDependencyGraph().isReexported(bundleID);
		}

		/**
		 * Queries whether I express a dependency directly on the given bundle.
		 * Equivalent to {@link #hasDependency(String, boolean) hasDependency(bundleID, false)}.
		 * 
		 * @param bundleID
		 *            a bundle identifier
		 * @return whether my bundle directly requires it
		 */
		public boolean hasDependency(String bundleID) {
			return getDependencyGraph().hasDependency(bundleID);
		}

		/**
		 * Queries whether I express a dependency directly or, optionally,
		 * indirectly on the given bundle.
		 * 
		 * @param bundleID
		 *            a bundle identifier
		 * @param recursive
		 *            whether to consider transitive (indirect) dependencies
		 * 
		 * @return whether my bundle directly requires it
		 */
		public boolean hasDependency(String bundleID, boolean recursive) {
			return getDependencyGraph().hasDependency(bundleID, recursive);
		}

		/**
		 * Obtains the set of bundles that should be re-exported that are not
		 * explicitly required (they mmust be implicitly required because some
		 * other dependency re-exports them).
		 * 
		 * @return the missing re-exported dependency declarations
		 */
		public Set<BundleAnalysis> getMissingReexports() {
			return getAPIExports().getMissingReexports();
		}

		private BundleAnalysis analyze() {
			if (dependencyGraph == null) {
				dependencyGraph = new DependencyGraph(bundleID);
			}
			if (apiExports == null) {
				apiExports = new APIExports(bundleID);
			}

			return this;
		}

		public String toReexportDeclaration() {
			return String.format("%s;bundle-version=\"%s\";visibility:=reexport",
					getBundleID(),
					getCompatibleVersionRange());
		}

		/**
		 * For bundles that are workspace projects, gets the manifest file.
		 * 
		 * @return the workspace bundle's manifest, or {@code null} if I am
		 *         a target bundle
		 */
		public IFile getManifest() {
			IFile result = null;

			IPluginModelBase model = PluginRegistry.findModel(getBundleID());
			IResource resource = (model == null) ? null : model.getUnderlyingResource();
			if (resource != null) {
				switch (resource.getType()) {
				case IResource.FILE:
					if ("MANIFEST.MF".equals(resource.getName())) {
						result = (IFile) resource;
					}
					break;
				case IResource.PROJECT:
					IFile manifest = ((IProject) resource).getFile("META-INF/MANIFEST.MF"); //$NON-NLS-1$
					if ((manifest != null) && manifest.isAccessible()) {
						result = manifest;
					}
					break;
				}
			}

			return result;
		}

		/**
		 * Queries whether I am an analysis root, which is a bundle selected
		 * by the user for optimization.
		 * 
		 * @return whether I am an analysis root
		 */
		public boolean isAnalysisRoot() {
			return DependencyAnalysisContext.this.isAnalysisRoot(getBundleID());
		}

		/**
		 * A partial-ordering analoque of the {@link Comparable#compareTo(Object)} API.
		 * Bundles are only partially orderable by dependency relationships, so
		 * they are not actually {@link Comparable}.
		 * 
		 * @param o
		 *            another analysis bundle
		 * 
		 * @return my partial ordering relative to {@code o}
		 */
		public int partialCompare(BundleAnalysis o) {
			int result;

			if (o == this) {
				// Trivial case
				result = 0;
			} else if (this.hasDependency(o.getBundleID(), true)) {
				result = +1;
			} else if (o.hasDependency(this.getBundleID(), true)) {
				result = -1;
			} else {
				result = 0;
			}

			return result;
		}

		@Override
		public String toString() {
			return "Analysis of " + bundleID;
		}

		public final void pushMonitor(IProgressMonitor monitor) {
			DependencyAnalysisContext.this.pushMonitor(monitor);
		}

		public final void popMonitor() {
			DependencyAnalysisContext.this.popMonitor();
		}
	}

	/**
	 * An analysis of the dependency graph (by <tt>Require-Bundle</tt>) of a bundle.
	 */
	public class DependencyGraph {
		private final String bundleID;

		private final Map<String, BundleAnalysis> dependencies = new HashMap<>();
		private final Map<String, BundleAnalysis> reexports = new HashMap<>();

		private Set<BundleAnalysis> cycle;
		private Set<String> transitiveDependencies;

		private DependencyGraph(String bundleID) {
			super();

			this.bundleID = bundleID;

			IPluginModelBase model = PluginRegistry.findModel(bundleID);
			if (model == null) {
				throw new IllegalArgumentException("No such bundle: " + bundleID);
			}

			BundleDescription desc = model.getBundleDescription();

			if (desc != null) {
				for (BundleSpecification next : desc.getRequiredBundles()) {
					// Optional dependencies may as well not be defined. If they are
					// exposed by the API, they cannot be optional

					if (next.isResolved() && !next.isOptional()
					// The org.eclipse.utp.upr bundle actually does this!
							&& !bundleID.equals(next.getName())) {
						BundleAnalysis dep = internalGetBundle(next.getSupplier().getName());

						dependencies.put(dep.getBundleID(), dep);
						if (next.isExported()) {
							reexports.put(dep.getBundleID(), dep);
						}
					}
				}
			}
		}

		public BundleAnalysis getBundle() {
			return internalGetBundle(bundleID);
		}

		public BundleAnalysis getDependency(String bundleID) {
			BundleAnalysis result = dependencies.get(bundleID);

			if (result == null) {
				// Maybe it's a transitive dependency
				result = dependencies.values().stream()
						.map(bundle -> bundle.getDependency(bundleID))
						.filter(Objects::nonNull)
						.findAny().orElse(null);
			}

			return result;
		}

		public boolean isReexported(String bundleID) {
			// I trivially "re-export" myself
			boolean result = this.bundleID.equals(bundleID) || reexports.containsKey(bundleID);

			if (!result) {
				// Maybe it's a transitive re-export
				result = reexports.values().stream()
						.anyMatch(bundle -> bundle.isReexported(bundleID));
			}

			return result;
		}

		/**
		 * Queries whether I express a dependency directly on the given bundle.
		 * Equivalent to {@link #hasDependency(String, boolean) hasDependency(bundleID, false)}.
		 * 
		 * @param bundleID
		 *            a bundle identifier
		 * @return whether my bundle directly requires it
		 */
		public boolean hasDependency(String bundleID) {
			return dependencies.containsKey(bundleID);
		}

		/**
		 * Queries whether I express a dependency directly or, optionally,
		 * indirectly on the given bundle.
		 * 
		 * @param bundleID
		 *            a bundle identifier
		 * @param recursive
		 *            whether to consider transitive (indirect) dependencies
		 * 
		 * @return whether my bundle directly requires it
		 */
		public boolean hasDependency(String bundleID, boolean recursive) {
			boolean result = hasDependency(bundleID);

			if (!result && recursive) {
				result = transitiveDependencies.contains(bundleID);
			}

			return result;
		}

		public boolean isRedundant(String bundleID) {
			boolean result;

			if (isReexported(bundleID)) {
				// If it's re-exported, then it's only redundant if it is also re-exported
				// by some other bundle that I re-export. Account for re-exports that we
				// would be adding
				result = Stream.concat(reexports.values().stream(), getBundle().getMissingReexports().stream())
						.filter(bundle -> !bundleID.equals(bundle.getBundleID())) // Excluding the bundle itself, of course!
						.anyMatch(bundle -> bundle.isReexported(bundleID));
			} else {
				// Otherwise, it's redundant if it's re-exported by any of our dependencies
				result = dependencies.values().stream()
						.filter(bundle -> !bundle.getBundleID().equals(bundleID))
						.anyMatch(bundle -> bundle.isReexported(bundleID));
			}

			return result;
		}

		public void checkCycle() throws IllegalStateException {
			if (cycle == null) {
				cycle = computeCycle(new LinkedHashSet<>());
			}

			if (!cycle.isEmpty()) {
				List<String> list = cycle.stream()
						.map(BundleAnalysis::getBundleID)
						.collect(Collectors.toList());
				list.add(cycle.iterator().next().getBundleID()); // Close the cycle
				throw new IllegalStateException("Dependency cycle detected: " + list);
			}
		}

		// use a LinkedHashSet specifically because the cycle has a defined order
		private Set<BundleAnalysis> computeCycle(LinkedHashSet<BundleAnalysis> trace) {
			if (cycle != null) {
				// I've already been validated, so there's no possibility of finding
				// a new cycle in me
				return cycle;
			}

			BundleAnalysis self = getBundle();

			if (!trace.add(self)) {
				// We closed the cycle. Trim up to the first occurrence of myself
				for (Iterator<BundleAnalysis> iter = trace.iterator(); iter.hasNext();) {
					if (iter.next() == self) {
						break;
					} else {
						iter.remove();
					}
				}
				cycle = trace;
			} else {
				// Take this opportunity when we are exhaustively looking for a cycle, anyways,
				// to compute everybody's transitive dependencies
				transitiveDependencies = new HashSet<>();

				// We didn't close the cycle, so keep looking
				for (BundleAnalysis next : dependencies.values()) {
					DependencyGraph child = next.getDependencyGraph();
					cycle = child.computeCycle(trace);
					if (!cycle.isEmpty()) {
						// Got a cycle
						break;
					} else {
						// Collect its dependencies and its transitive dependencies
						transitiveDependencies.addAll(child.dependencies.keySet());
						transitiveDependencies.addAll(child.transitiveDependencies);
					}
				}

				// Cycle could be null if I had no dependencies
				if ((cycle == null) || cycle.isEmpty()) {
					// Some of my direct dependencies could be dependencies of some of
					// my transitive dependencies, but they are direct to me
					transitiveDependencies.removeAll(dependencies.keySet());

					// Backtrack
					trace.remove(self);

					// And mark me cycle-free
					cycle = Collections.emptySet();
				}
			}

			return cycle;
		}

		public void removeDependency(String bundleID) {
			dependencies.remove(bundleID);

			// It's now just a transitive dependency because it was redundant
			transitiveDependencies.add(bundleID);

			// And it obviously can't be reexported
			reexports.remove(bundleID);
		}

		public void reexport(String bundleID) {
			reexports.put(bundleID, internalGetBundle(bundleID));

			// This information is now stale
			getBundle().getAPIExports().recomputeMissingReexports();
		}

		@Override
		public String toString() {
			return "Dependencies of " + bundleID;
		}
	}

	/**
	 * An analysis of the public API exports of a bundle.
	 */
	public class APIExports {
		private final String bundleID;
		private VersionRange compatibleVersionRange;

		private Set<String> exports;
		private Map<String, BundleAnalysis> exposedDependencies;
		private Set<BundleAnalysis> missingReexports;

		private APIExports(String bundleID) {
			super();

			this.bundleID = bundleID;
		}

		public BundleAnalysis getBundle() {
			return internalGetBundle(bundleID);
		}

		public VersionRange getCompatibleVersionRange() {
			return compatibleVersionRange;
		}

		public boolean exports(String packageName) {
			analyze();

			return exports.contains(packageName);
		}

		public boolean isExposed(String bundleID) {
			analyze();

			return exposedDependencies.containsKey(bundleID);
		}

		public Set<BundleAnalysis> getExposedDependencies() {
			analyze();

			return new HashSet<>(exposedDependencies.values());
		}

		/**
		 * Obtains the set of bundles that should be re-exported that are not
		 * explicitly required (they mmust be implicitly required because some
		 * other dependency re-exports them).
		 * 
		 * @return the missing re-exported dependency declarations
		 */
		public Set<BundleAnalysis> getMissingReexports() {
			if (missingReexports == null) {
				missingReexports = getExposedDependencies().stream()
						.filter(bundle -> !getBundle().isReexported(bundle.getBundleID()))
						.filter(bundle -> !getBundle().hasDependency(bundle.getBundleID()))
						.filter(bundle -> !isReexportedByExposedDependency(bundle))
						.collect(Collectors.toCollection(
								() -> new TreeSet<>(Comparator.comparing(BundleAnalysis::getBundleID))));
			}

			return missingReexports;
		}

		void recomputeMissingReexports() {
			missingReexports = null;
		}

		private APIExports analyze() {
			if (exposedDependencies == null) {
				exposedDependencies = new HashMap<>();

				IPluginModelBase model = PluginRegistry.findModel(bundleID);
				BundleDescription desc = model.getBundleDescription();
				IProject project = (model.getUnderlyingResource() == null)
						? null
						: model.getUnderlyingResource().getProject();
				BundleAnalysis self = getBundle();

				if (desc == null) {
					// No exports if no bundle description
					exports = Collections.emptySet();
					compatibleVersionRange = VersionRange.valueOf("0.0.0"); //$NON-NLS-1$
				} else {
					compatibleVersionRange = versionRules.getDependencyVersionRange(
							DependencyKind.REQUIRE_BUNDLE, bundleID);

					if ((project == null) || !isAnalysisRoot(bundleID)) {
						// It's a PDE target bundle. We don't need to compute uses constraints
						// for it because we won't be attempting to edit its dependencies
						exports = Stream.of(desc.getExportPackages())
								.filter(this::isPublicExport)
								.map(ExportPackageDescription::getName)
								.collect(Collectors.toSet());
					} else {
						// It's a workspace bundle that is selected for optimization.
						// We need to compute uses constraints for it
						Map<String, ? extends Set<String>> uses = new MyCalculateUsesOperation(project, model).calculate();

						currentMonitor.setTaskName("Computing re-exported dependencies...");
						exports = new HashSet<>(uses.keySet());
						Set<String> allUsedPackages = uses.values().stream()
								.flatMap(Collection::stream)
								.distinct()
								.collect(Collectors.toSet());

						// Don't consider my own exported packages, of course
						allUsedPackages.removeAll(exports);

						for (String next : allUsedPackages) {
							BundleAnalysis provider = getProvidingBundle(next);
							if ((provider != null) && (provider != self) && !exposedDependencies.containsKey(provider.getBundleID())) {
								exposedDependencies.put(provider.getBundleID(), provider);
							}
						}
					}
				}

				exports.forEach(x -> packageProviders.put(x, self));
			}

			return this;
		}

		private boolean isPublicExport(ExportPackageDescription exportPackage) {
			Map<String, String> directives = exportPackage.getDeclaredDirectives();
			return !"true".equals(directives.get("x-internal"))
					&& !directives.containsKey("x-friends");
		}

		/**
		 * Queries whether a {@code bundle} is re-exported by some existing dependency
		 * that is exposed in the API. Such a bundle would not have to be added as
		 * a missing re-export.
		 * 
		 * @param bundle
		 *            an exposed bundle
		 * 
		 * @return whether it is re-exported by some other bundle that I expose
		 */
		private boolean isReexportedByExposedDependency(BundleAnalysis bundle) {
			return exposedDependencies.values().stream()
					.anyMatch(dep -> dep.isReexported(bundle.getBundleID()));
		}

		@Override
		public String toString() {
			return "API of " + bundleID;
		}

		//
		// Nested types
		//

		@SuppressWarnings("restriction")
		private final class MyCalculateUsesOperation extends org.eclipse.pde.internal.ui.search.dependencies.CalculateUsesOperation {
			MyCalculateUsesOperation(IProject project, IPluginModelBase model) {
				// This cast is safe if the model if the model is a workspace bundle project
				super(project, (org.eclipse.pde.internal.core.ibundle.IBundlePluginModelBase) model);
			}

			Map<String, ? extends Set<String>> calculate() {
				Map<String, ? extends Set<String>> result;

				Collection<String> packages = getPublicExportedPackages();
				if (packages.isEmpty()) {
					result = Collections.emptyMap();
				} else {
					result = findPackageReferences(packages, currentMonitor.split(1)); // Split doesn't matter for unknown total work
				}

				return result;
			}
		}
	}
}

Back to the top