下面列出了怎么用com.google.common.collect.ImmutableSortedSet的API类实例代码及写法,或者点击链接到github查看源代码。
public void copy(
ProjectFilesystem filesystem,
BuildCellRelativePathFactory buildCellRelativePathFactory,
ImmutableList.Builder<Step> steps,
Path destinationDir,
ImmutableSortedSet<SourcePath> toCopy,
SourcePathResolverAdapter pathResolver) {
copy(
filesystem,
buildCellRelativePathFactory,
steps,
destinationDir,
toCopy,
pathResolver,
PatternsMatcher.NONE);
}
@Test
public void testCxxBinaryAndGenruleLoadedFromCache() {
BuildTarget genruleTarget = BuildTargetFactory.newInstance("//:gen");
GenruleBuilder genruleBuilder =
GenruleBuilder.newGenruleBuilder(genruleTarget).setCmd("cmd").setOut("out");
BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:bin");
CxxBinaryBuilder binaryBuilder =
new CxxBinaryBuilder(binaryTarget)
.setHeaders(ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(genruleTarget)))
.setSrcs(
ImmutableSortedSet.of(
SourceWithFlags.of(FakeSourcePath.of("binary.cpp"), ImmutableList.of())));
ActionGraphAndBuilder result = createActionGraph(binaryBuilder, genruleBuilder);
queryTransitiveDeps(result);
ImmutableMap<BuildRule, RuleKey> ruleKeys = getRuleKeys(result);
ActionGraphAndBuilder newResult = createActionGraph(binaryBuilder, genruleBuilder);
queryTransitiveDeps(newResult);
ImmutableMap<BuildRule, RuleKey> newRuleKeys = getRuleKeys(newResult);
assertBuildRulesSame(result, newResult);
assertEquals(ruleKeys, newRuleKeys);
}
/**
* Returns the {@link Fragment}s and the {@link FragmentOptions} they require from Blaze's
* runtime.
*
* <p>These are the fragments that Blaze "knows about", not necessarily the fragments in a {@link
* BuildConfiguration}. Trimming, in particular, strips fragments out of actual configurations.
* It's safe to assume untrimmed configuration have all fragments listed here.
*/
private static ImmutableSortedMap<
Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
getFragmentDefs(ConfiguredRuleClassProvider ruleClassProvider) {
ImmutableSortedMap.Builder<
Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
fragments = ImmutableSortedMap.orderedBy((c1, c2) -> c1.getName().compareTo(c2.getName()));
for (ConfigurationFragmentFactory fragmentFactory :
ruleClassProvider.getConfigurationFragments()) {
fragments.put(
fragmentFactory.creates(),
ImmutableSortedSet.copyOf(
(c1, c2) -> c1.getName().compareTo(c2.getName()), fragmentFactory.requiredOptions()));
}
return fragments.build();
}
public boolean clearIssuesOfPersistedState(String containerHandle) {
List<IssueRegistryChangeEvent> events;
synchronized (this) {
Map<URI, ImmutableSortedSet<LSPIssue>> containerIssues = getContainerIssues(containerHandle, false);
if (containerIssues == null) {
return false;
}
events = containerIssues.entrySet().stream()
.map(e -> eventPersisted(containerHandle, e.getKey(), e.getValue(), null))
.collect(Collectors.toList());
containerIssues.keySet().forEach(persistedIssues::remove);
container2persistedIssues.remove(containerHandle);
}
notifyListeners(events);
return true;
}
@Test
public void testGeneratedSourceFromCxxGenrule() throws NoSuchBuildTargetException {
CxxGenruleBuilder srcBuilder =
new CxxGenruleBuilder(BuildTargetFactory.newInstance("//:src")).setOut("lib.rs");
RustLibraryBuilder libraryBuilder =
RustLibraryBuilder.from("//:lib")
.setSrcs(
ImmutableSortedSet.of(DefaultBuildTargetSourcePath.of(srcBuilder.getTarget())));
RustBinaryBuilder binaryBuilder =
RustBinaryBuilder.from("//:bin")
.setSrcs(ImmutableSortedSet.of(FakeSourcePath.of("main.rs")))
.setDeps(ImmutableSortedSet.of(libraryBuilder.getTarget()));
TargetGraph targetGraph =
TargetGraphFactory.newInstance(
srcBuilder.build(), libraryBuilder.build(), binaryBuilder.build());
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
graphBuilder.requireRule(binaryBuilder.getTarget());
}
/**
* Parses a set of maven repository directory trees looking for and parsing .pom files.
*/
static SdkMavenRepository create(Iterable<Path> mavenRepositories) throws IOException {
Collection<Path> pomPaths = new ArrayList<>();
for (Path mavenRepository : mavenRepositories) {
pomPaths.addAll(
FileSystemUtils.traverseTree(mavenRepository, path -> path.toString().endsWith(".pom")));
}
ImmutableSortedSet.Builder<Pom> poms =
new ImmutableSortedSet.Builder<>(Ordering.usingToString());
for (Path pomPath : pomPaths) {
try {
Pom pom = Pom.parse(pomPath);
if (pom != null) {
poms.add(pom);
}
} catch (ParserConfigurationException | SAXException e) {
throw new IOException(e);
}
}
return new SdkMavenRepository(poms.build());
}
protected static BoundingBox calculateBoundingBoxLineStrings(Iterable<LineString> lineStrings) {
ImmutableSortedSet.Builder<Float> xset =
ImmutableSortedSet.naturalOrder();
ImmutableSortedSet.Builder<Float> yset =
ImmutableSortedSet.naturalOrder();
ImmutableSortedSet.Builder<Float> zset =
ImmutableSortedSet.naturalOrder();
for (LineString ls : lineStrings) {
for (Position p : ls) {
xset.add(p.northing());
yset.add(p.easting());
if (p.hasAltitude())
zset.add(p.altitude());
}
}
return buildBoundingBox(
xset.build(),
yset.build(),
zset.build());
}
@Test
public void exportedHeaders() {
ProjectFilesystem filesystem = new AllExistingProjectFilesystem();
PrebuiltCxxLibraryBuilder libBuilder =
new PrebuiltCxxLibraryBuilder(TARGET)
.setExportedHeaders(
SourceSortedSet.ofNamedSources(
ImmutableSortedMap.of("foo.h", FakeSourcePath.of("foo.h"))));
TargetGraph targetGraph = TargetGraphFactory.newInstance(libBuilder.build());
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
PrebuiltCxxLibrary lib =
(PrebuiltCxxLibrary) libBuilder.build(graphBuilder, filesystem, targetGraph);
// Verify the preprocessable input is as expected.
CxxPreprocessorInput input = lib.getCxxPreprocessorInput(CXX_PLATFORM, graphBuilder);
assertThat(getHeaderNames(input.getIncludes()), Matchers.hasItem(filesystem.getPath("foo.h")));
assertThat(
ImmutableSortedSet.copyOf(input.getDeps(graphBuilder)),
Matchers.equalTo(graphBuilder.getAllRules(getInputRules(lib))));
}
/**
* Merges the {@link MethodInfo}s with the same method name and {@link HttpMethod} pair
* into a single {@link MethodInfo}. Note that only the {@link EndpointInfo}s are merged
* because the {@link MethodInfo}s being merged always have the same
* {@code exampleHttpHeaders} and {@code exampleRequests}.
*/
@VisibleForTesting
static Set<MethodInfo> mergeEndpoints(Iterable<MethodInfo> methodInfos) {
final Map<List<Object>, MethodInfo> methodInfoMap = new HashMap<>();
for (MethodInfo methodInfo : methodInfos) {
final List<Object> mergeKey = ImmutableList.of(methodInfo.name(), methodInfo.httpMethod());
methodInfoMap.compute(mergeKey, (key, value) -> {
if (value == null) {
return methodInfo;
} else {
final Set<EndpointInfo> endpointInfos =
Sets.union(value.endpoints(), methodInfo.endpoints());
return new MethodInfo(value.name(), value.returnTypeSignature(),
value.parameters(), value.exceptionTypeSignatures(),
endpointInfos, value.exampleHttpHeaders(),
value.exampleRequests(), value.examplePaths(), value.exampleQueries(),
value.httpMethod(), value.docString());
}
});
}
return ImmutableSortedSet
.orderedBy(comparing(MethodInfo::name).thenComparing(MethodInfo::httpMethod))
.addAll(methodInfoMap.values())
.build();
}
/**
* Constructor
*
* @param ruleContext parent NinjaGraphRule rule context
* @param outputRootPath name of output directory for Ninja actions under execroot
* @param workingDirectory relative path under execroot, the root for interpreting all paths in
* Ninja file
* @param symlinkPathToArtifact mapping of paths to artifacts for input symlinks under output_root
* @param outputRootSymlinks list of output paths for which symlink artifacts should be created,
* paths are relative to the output_root.
*/
NinjaGraphArtifactsHelper(
RuleContext ruleContext,
PathFragment outputRootPath,
PathFragment workingDirectory,
ImmutableSortedMap<PathFragment, Artifact> symlinkPathToArtifact,
ImmutableSortedSet<PathFragment> outputRootSymlinks) {
this.ruleContext = ruleContext;
this.outputRootPath = outputRootPath;
this.workingDirectory = workingDirectory;
this.symlinkPathToArtifact = symlinkPathToArtifact;
this.outputRootSymlinks = outputRootSymlinks;
Path execRoot =
Preconditions.checkNotNull(ruleContext.getConfiguration())
.getDirectories()
.getExecRoot(ruleContext.getWorkspaceName());
this.derivedOutputRoot =
ArtifactRoot.asDerivedRoot(execRoot, outputRootPath.getSegments().toArray(new String[0]));
this.sourceRoot = ruleContext.getRule().getPackage().getSourceRoot().get();
}
/** @return Path of the topmost cell's path that roots all other cells */
public AbsPath getSuperRootPath() {
AbsPath cellRoot = getRootCell().getRoot();
ImmutableSortedSet<AbsPath> allRoots = getRootCell().getKnownRootsOfAllCells();
AbsPath path = cellRoot.getRoot();
// check if supercell is a root folder, like '/' or 'C:\'
if (allRoots.contains(path)) {
return path;
}
// There is an assumption that there is exactly one cell with a path that prefixes all other
// cell paths. So just try to find the cell with the shortest common path.
for (Path next : cellRoot.getPath()) {
path = path.resolve(next);
if (allRoots.contains(path)) {
return path;
}
}
throw new IllegalStateException(
"Unreachable: at least one path should be in getKnownRoots(), including root cell '"
+ cellRoot.toString()
+ "'; known roots = ["
+ allRoots.stream().map(Objects::toString).collect(Collectors.joining(", "))
+ "]");
}
FakePreDexMerge(BuildTarget buildTarget, APKModuleGraph apkModuleGraph) {
super(
buildTarget,
new FakeProjectFilesystem(),
new BuildRuleParams(
ImmutableSortedSet::of, ImmutableSortedSet::of, ImmutableSortedSet.of()),
null,
"dx",
new DexSplitMode(
/* shouldSplitDex */ true,
DexSplitStrategy.MINIMIZE_PRIMARY_DEX_SIZE,
DexStore.JAR,
/* linearAllocHardLimit */ 4 * 1024 * 1024,
/* primaryDexPatterns */ ImmutableSet.of("List"),
Optional.of(FakeSourcePath.of("the/manifest.txt")),
/* primaryDexScenarioFile */ Optional.empty(),
/* isPrimaryDexScenarioOverflowAllowed */ false,
/* secondaryDexHeadClassesFile */ Optional.empty(),
/* secondaryDexTailClassesFile */ Optional.empty(),
/* allowRDotJavaInSecondaryDex */ false),
apkModuleGraph,
null,
MoreExecutors.newDirectExecutorService(),
XzStep.DEFAULT_COMPRESSION_LEVEL,
Optional.empty());
}
public void setIssuesOfPersistedState(String containerHandle, URI uri, Iterable<? extends LSPIssue> issues) {
ImmutableSortedSet<LSPIssue> issuesNew = ImmutableSortedSet.copyOf(issueComparator, issues);
ImmutableSortedSet<LSPIssue> issuesOld;
synchronized (this) {
Map<URI, ImmutableSortedSet<LSPIssue>> containerIssues = getContainerIssues(containerHandle, true);
persistedIssues.put(uri, issuesNew);
issuesOld = containerIssues.put(uri, issuesNew);
}
notifyListeners(eventPersisted(containerHandle, uri, issuesOld, issuesNew));
}
@Test
public void platformDeps() throws IOException {
SourcePath libASrc = FakeSourcePath.of("libA.py");
PythonLibraryBuilder libraryABuilder =
PythonLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:libA"))
.setSrcs(SourceSortedSet.ofUnnamedSources(ImmutableSortedSet.of(libASrc)));
SourcePath libBSrc = FakeSourcePath.of("libB.py");
PythonLibraryBuilder libraryBBuilder =
PythonLibraryBuilder.createBuilder(BuildTargetFactory.newInstance("//:libB"))
.setSrcs(SourceSortedSet.ofUnnamedSources(ImmutableSortedSet.of(libBSrc)));
PythonTestBuilder binaryBuilder =
PythonTestBuilder.create(BuildTargetFactory.newInstance("//:bin"))
.setPlatformDeps(
PatternMatchedCollection.<ImmutableSortedSet<BuildTarget>>builder()
.add(
Pattern.compile(
CxxPlatformUtils.DEFAULT_PLATFORM_FLAVOR.toString(), Pattern.LITERAL),
ImmutableSortedSet.of(libraryABuilder.getTarget()))
.add(
Pattern.compile("matches nothing", Pattern.LITERAL),
ImmutableSortedSet.of(libraryBBuilder.getTarget()))
.build());
TargetGraph targetGraph =
TargetGraphFactory.newInstance(
libraryABuilder.build(), libraryBBuilder.build(), binaryBuilder.build());
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
PythonTest test = (PythonTest) graphBuilder.requireRule(binaryBuilder.getTarget());
assertThat(
test.getBinary()
.getComponents()
.resolve(graphBuilder.getSourcePathResolver())
.getAllModules()
.values(),
Matchers.allOf(
Matchers.hasItem(graphBuilder.getSourcePathResolver().getAbsolutePath(libASrc)),
Matchers.not(
Matchers.hasItem(graphBuilder.getSourcePathResolver().getAbsolutePath(libBSrc)))));
}
protected AndroidBinaryNonExoInstaller(
BuildTarget buildTarget, ProjectFilesystem projectFilesystem, HasInstallableApk apk) {
super(buildTarget, projectFilesystem);
Preconditions.checkState(!apk.getApkInfo().getExopackageInfo().isPresent());
this.trigger = new InstallTrigger(projectFilesystem);
this.apk = apk;
this.depsSupplier = MoreSuppliers.memoize(() -> ImmutableSortedSet.of((BuildRule) apk));
}
/**
* List questions for the given network and analysis. Returns list of questions if successful, or
* {@code null} if network or analysis does not exist.
*/
public @Nullable SortedSet<String> listAnalysisQuestions(String network, String analysis) {
Optional<NetworkId> networkIdOpt = _idManager.getNetworkId(network);
if (!networkIdOpt.isPresent()) {
return null;
}
NetworkId networkId = networkIdOpt.get();
Optional<AnalysisId> analysisIdOpt = _idManager.getAnalysisId(analysis, networkId);
if (!analysisIdOpt.isPresent()) {
return null;
}
return ImmutableSortedSet.copyOf(_idManager.listQuestions(networkId, analysisIdOpt.get()));
}
@Test
public void testClasspath() throws IOException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "test_rule_classpath", temp);
workspace.setUp();
ProcessResult result = workspace.runBuckCommand("audit", "classpath", "//:top");
result.assertSuccess();
ImmutableSortedSet<Path> actualPaths =
FluentIterable.from(Arrays.asList(result.getStdout().split("\\s+")))
.transform(input -> temp.getRoot().relativize(Paths.get(input)))
.toSortedSet(Ordering.natural());
ImmutableSortedSet<Path> expectedPaths =
ImmutableSortedSet.of(
BuildTargetPaths.getGenPath(
workspace.getProjectFileSystem(),
BuildTargetFactory.newInstance("//:top"),
"lib__%s__output")
.resolve("top.jar"),
BuildTargetPaths.getGenPath(
workspace.getProjectFileSystem(),
BuildTargetFactory.newInstance("//:direct_dep"),
"lib__%s__output")
.resolve("direct_dep.jar"),
BuildTargetPaths.getGenPath(
workspace.getProjectFileSystem(),
BuildTargetFactory.newInstance("//:mid_test#testsjar"),
"lib__%s__output")
.resolve("mid_test#testsjar.jar"),
BuildTargetPaths.getGenPath(
workspace.getProjectFileSystem(),
BuildTargetFactory.newInstance("//:transitive_lib"),
"lib__%s__output")
.resolve("transitive_lib.jar"));
assertEquals(expectedPaths, actualPaths);
}
@Test
public void testComputeVniInterNodeEdges() {
String s1Name = "S1";
String s2Name = "S2";
int vlanId = 2;
int vni = 10002;
String vrfName = "v1";
Configuration s1 = _cb.setHostname(s1Name).build();
Configuration s2 = _cb.setHostname(s2Name).build();
Vrf v1 = _vb.setOwner(s1).setName(vrfName).build();
Vrf v2 = _vb.setOwner(s2).setName(vrfName).build();
Layer2Vni.Builder vnb =
testBuilder()
.setBumTransportIps(ImmutableSortedSet.of(Ip.FIRST_MULTICAST_IP))
.setBumTransportMethod(BumTransportMethod.MULTICAST_GROUP)
.setVlan(vlanId)
.setVni(vni);
v1.addLayer2Vni(vnb.build());
v2.addLayer2Vni(vnb.build());
String vniName = computeVniName(vni);
MutableGraph<VxlanNode> graph = GraphBuilder.undirected().allowsSelfLoops(false).build();
graph.putEdge(new VxlanNode(s1Name, vni), new VxlanNode(s2Name, vni));
VxlanTopology vxlanTopology = new VxlanTopology(graph);
Layer2Node n1 = new Layer2Node(s1Name, vniName, null);
Layer2Node n2 = new Layer2Node(s2Name, vniName, null);
assertThat(
computeVniInterNodeEdges(vxlanTopology).collect(ImmutableList.toImmutableList()),
containsInAnyOrder(new Layer2Edge(n1, n2, null), new Layer2Edge(n2, n1, null)));
}
@Test
public void resourcesAreInputs() throws Exception {
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path resource = filesystem.getPath("resource");
filesystem.touch(resource);
TargetNode<?> shTestWithResources =
new ShTestBuilder(target)
.setTest(FakeSourcePath.of(filesystem, "some_test"))
.setResources(ImmutableSortedSet.of(PathSourcePath.of(filesystem, resource)))
.build();
assertThat(
shTestWithResources.getInputs(), Matchers.hasItem(ForwardRelativePath.ofPath(resource)));
}
public void addEntry(
String structureName, String hostname, T structure, boolean assumeAllUnique) {
Map<Integer, Set<NamedStructureEquivalenceSet<T>>> sameNamedStructuresByHash =
_sameNamedStructuresByNameAndHash.computeIfAbsent(structureName, s -> new HashMap<>());
String structureJson = writeObject(structure);
int hash = structureJson.hashCode();
Set<NamedStructureEquivalenceSet<T>> eqSetsWithSameHash =
sameNamedStructuresByHash.computeIfAbsent(hash, h -> new HashSet<>());
if (assumeAllUnique || eqSetsWithSameHash.isEmpty()) {
eqSetsWithSameHash.add(new NamedStructureEquivalenceSet<>(hostname, structure));
} else {
Optional<NamedStructureEquivalenceSet<T>> potentialMatchingSet =
eqSetsWithSameHash.stream()
.filter(
s -> checkJsonStringEquals(structureJson, writeObject(s.getNamedStructure())))
.findAny();
if (potentialMatchingSet.isPresent()) {
NamedStructureEquivalenceSet<T> matchingSet = potentialMatchingSet.get();
matchingSet.setNodes(
new ImmutableSortedSet.Builder<String>(Comparator.naturalOrder())
.addAll(matchingSet.getNodes())
.add(hostname)
.build());
} else {
eqSetsWithSameHash.add(new NamedStructureEquivalenceSet<>(hostname, structure));
}
}
}
private void setup_internalNHIp_subnetNotFull_internalDstIp() {
Configuration node1 = _cb.setHostname(NODE1).build();
Vrf vrf = _vb.setOwner(node1).setName(Configuration.DEFAULT_VRF_NAME).build();
_ib.setOwner(node1).setVrf(vrf);
_ib.setName(NEXT_HOP_INTERFACE).setAddresses(NEXT_HOP_INTERFACE_NOT_FULL_ADDR).build();
// setup a loopback on NODE2 that owns NEXT_HOP_IP and DST_IP
Configuration node2 = _cb.setHostname(NODE2).build();
Vrf vrf2 = _vb.setOwner(node2).build();
_ib.setOwner(node2)
.setVrf(vrf2)
.setName(LOOPBACK_INTERFACE)
.setAddresses(
ConcreteInterfaceAddress.create(DST_IP, 32),
ConcreteInterfaceAddress.create(NEXT_HOP_IP, 32))
.build();
vrf.setStaticRoutes(
ImmutableSortedSet.of(
StaticRoute.builder()
.setNetwork(DST_IP.toPrefix())
.setNextHopInterface(NEXT_HOP_INTERFACE)
.setNextHopIp(NEXT_HOP_IP)
.setAdministrativeCost(1)
.build()));
_configs = ImmutableSortedMap.of(NODE1, node1, NODE2, node2);
}
@Test
public void unknowComparatorThrows() {
assertThrows(
SerializationException.class,
() ->
TestUtils.roundTrip(
ImmutableSortedSet.orderedBy(Comparator.comparingInt(String::length))
.add("a", "bcd", "ef")));
}
private static WorkerTool createWorkerTool(
Consumer<WorkerToolDescriptionArg.Builder> setArgs,
BiFunction<ActionGraphBuilder, BuildRule, BuildTarget> getExe) {
TargetGraph targetGraph = TargetGraph.EMPTY;
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
BuildRule shBinaryRule =
new ShBinaryBuilder(BuildTargetFactory.newInstance("//:my_exe"))
.setMain(FakeSourcePath.of("bin/exe"))
.build(graphBuilder);
BuildTarget exe = getExe.apply(graphBuilder, shBinaryRule);
Builder argsBuilder = WorkerToolDescriptionArg.builder().setName("target").setExe(exe);
setArgs.accept(argsBuilder);
WorkerToolDescription workerToolDescription = new WorkerToolDescription(BUCK_CONFIG);
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildTarget buildTarget = BuildTargetFactory.newInstance("//arbitrary:target");
BuildRuleParams params =
new BuildRuleParams(
ImmutableSortedSet::of,
() -> ImmutableSortedSet.of(graphBuilder.getRule(exe)),
ImmutableSortedSet.of());
return ((ProvidesWorkerTool)
workerToolDescription.createBuildRule(
TestBuildRuleCreationContextFactory.create(
targetGraph, graphBuilder, projectFilesystem),
buildTarget,
params,
argsBuilder.build()))
.getWorkerTool();
}
@Test
public void jarsShouldContainDirectoryEntries() throws IOException {
Path zipup = folder.newFolder("dir-zip");
Path subdir = zipup.resolve("dir/subdir");
Files.createDirectories(subdir);
Files.write(subdir.resolve("a.txt"), "cake".getBytes());
JarDirectoryStep step =
new JarDirectoryStep(
TestProjectFilesystems.createProjectFilesystem(zipup),
JarParameters.builder()
.setJarPath(Paths.get("output.jar"))
.setEntriesToJar(ImmutableSortedSet.of(zipup))
.setMergeManifests(true)
.build());
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context).getExitCode();
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
assertTrue(Files.exists(zip));
// Iterate over each of the entries, expecting to see the directory names as entries.
Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/");
try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) {
for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
expected.remove(entry.getName());
}
}
assertTrue("Didn't see entries for: " + expected, expected.isEmpty());
}
@Test
public void testThatBuildTargetSourcePathDepsAndPathsArePropagated() {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
// Create a couple of genrules to generate inputs for an archive rule.
Genrule genrule1 =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule"))
.setOut("foo/bar.o")
.build(graphBuilder);
Genrule genrule2 =
GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:genrule2"))
.setOut("foo/test.o")
.build(graphBuilder);
// Build the archive using a normal input the outputs of the genrules above.
Archive archive =
new Archive(
target,
projectFilesystem,
graphBuilder,
DEFAULT_ARCHIVER,
ImmutableList.of(),
DEFAULT_RANLIB,
ImmutableList.of(),
ArchiveContents.NORMAL,
DEFAULT_OUTPUT_FILE_NAME,
ImmutableList.of(
FakeSourcePath.of("simple.o"),
genrule1.getSourcePathToOutput(),
genrule2.getSourcePathToOutput()),
/* cacheable */ true);
// Verify that the archive dependencies include the genrules providing the
// SourcePath inputs.
assertEquals(ImmutableSortedSet.<BuildRule>of(genrule1, genrule2), archive.getBuildDeps());
}
private static void addValues(
ImmutableSortedSet.Builder<Float> xset,
ImmutableSortedSet.Builder<Float> yset,
ImmutableSortedSet.Builder<Float> zset,
Iterable<Position> positions) {
for (Position position : positions) {
xset.add(position.northing());
yset.add(position.easting());
if (position.hasAltitude())
zset.add(position.altitude());
}
}
@Test
public void platformSrcs() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
BuildTarget target = BuildTargetFactory.newInstance("//foo:lib");
SourcePath pyPlatformMatchedSource = FakeSourcePath.of("foo/a.py");
SourcePath cxxPlatformMatchedSource = FakeSourcePath.of("foo/b.py");
SourcePath unmatchedSource = FakeSourcePath.of("foo/c.py");
PythonLibraryBuilder builder =
new PythonLibraryBuilder(target)
.setPlatformSrcs(
PatternMatchedCollection.<SourceSortedSet>builder()
.add(
Pattern.compile("^" + PythonTestUtils.PYTHON_PLATFORM.getFlavor() + "$"),
SourceSortedSet.ofUnnamedSources(
ImmutableSortedSet.of(pyPlatformMatchedSource)))
.add(
Pattern.compile("^" + CxxPlatformUtils.DEFAULT_PLATFORM_FLAVOR + "$"),
SourceSortedSet.ofUnnamedSources(
ImmutableSortedSet.of(cxxPlatformMatchedSource)))
.add(
Pattern.compile("won't match anything"),
SourceSortedSet.ofUnnamedSources(ImmutableSortedSet.of(unmatchedSource)))
.build());
TargetGraph targetGraph = TargetGraphFactory.newInstance(builder.build());
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
PythonLibrary library = builder.build(graphBuilder, filesystem, targetGraph);
assertThat(
library
.getPythonModules(
PythonTestUtils.PYTHON_PLATFORM, CxxPlatformUtils.DEFAULT_PLATFORM, graphBuilder)
.map(modules -> modules.getComponents().values())
.orElseGet(ImmutableSet::of),
Matchers.contains(pyPlatformMatchedSource, cxxPlatformMatchedSource));
}
/** Creates a generated reference book with the public IPs of the network interfaces */
static void createPublicIpsRefBook(
Collection<NetworkInterface> networkInterfaces, Configuration cfgNode) {
String publicIpBookName =
GeneratedRefBookUtils.getName(cfgNode.getHostname(), BookType.PublicIps);
checkArgument(
!cfgNode.getGeneratedReferenceBooks().containsKey(publicIpBookName),
"Generated reference book for public IPs already exists for node %s",
cfgNode.getHostname());
List<AddressGroup> publicIpAddressGroups =
networkInterfaces.stream()
.map(
iface ->
new AddressGroup(
iface.getPrivateIpAddresses().stream()
.filter(privIp -> privIp.getPublicIp() != null)
.map(privIp -> privIp.getPublicIp().toString())
.collect(ImmutableSortedSet.toImmutableSortedSet(naturalOrder())),
publicIpAddressGroupName(iface)))
.filter(ag -> !ag.getAddresses().isEmpty())
.collect(ImmutableList.toImmutableList());
if (!publicIpAddressGroups.isEmpty()) {
cfgNode
.getGeneratedReferenceBooks()
.put(
publicIpBookName,
ReferenceBook.builder(publicIpBookName)
.setAddressGroups(publicIpAddressGroups)
.build());
}
}
/** Update the modules.xml file with any new modules from the given set */
private void updateModulesIndex(ImmutableSet<IjModule> modulesEdited) throws IOException {
final Set<ModuleIndexEntry> existingModules =
modulesParser.getAllModules(
projectFilesystem.newFileInputStream(getIdeaConfigDir().resolve("modules.xml")));
final Set<Path> existingModuleFilepaths =
existingModules.stream()
.map(ModuleIndexEntry::getFilePath)
.map(PathFormatter::pathWithUnixSeparators)
.map(Paths::get)
.collect(ImmutableSet.toImmutableSet());
ImmutableSet<Path> remainingModuleFilepaths =
modulesEdited.stream()
.map(projectPaths::getModuleImlFilePath)
.map(PathFormatter::pathWithUnixSeparators)
.map(Paths::get)
.filter(modulePath -> !existingModuleFilepaths.contains(modulePath))
.collect(ImmutableSet.toImmutableSet());
// Merge the existing and new modules into a single sorted set
ImmutableSortedSet.Builder<ModuleIndexEntry> finalModulesBuilder =
ImmutableSortedSet.orderedBy(Comparator.<ModuleIndexEntry>naturalOrder());
// Add the existing definitions
finalModulesBuilder.addAll(existingModules);
// Add any new module definitions that we haven't seen yet
remainingModuleFilepaths.forEach(
modulePath ->
finalModulesBuilder.add(
ModuleIndexEntry.of(
getUrl(projectPaths.getProjectQualifiedPath(modulePath)),
projectPaths.getProjectRelativePath(modulePath),
projectConfig.getModuleGroupName())));
// Write out the merged set to disk
writeModulesIndex(finalModulesBuilder.build());
}
@Test
public void sharedLibraryShouldLinkOwnRequiredLibraries() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
CxxPlatform platform = CxxPlatformUtils.DEFAULT_PLATFORM;
CxxLibraryBuilder libraryBuilder =
new CxxLibraryBuilder(
BuildTargetFactory.newInstance("//:foo")
.withFlavors(platform.getFlavor(), CxxDescriptionEnhancer.SHARED_FLAVOR));
libraryBuilder
.setLibraries(
ImmutableSortedSet.of(
FrameworkPath.ofSourceTreePath(
new SourceTreePath(
PBXReference.SourceTree.SDKROOT,
Paths.get("/usr/lib/libz.dylib"),
Optional.empty())),
FrameworkPath.ofSourcePath(FakeSourcePath.of("another/path/liba.dylib"))))
.setSrcs(ImmutableSortedSet.of(SourceWithFlags.of(FakeSourcePath.of("foo.c"))));
TargetGraph targetGraph = TargetGraphFactory.newInstance(libraryBuilder.build());
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph);
CxxLink library = (CxxLink) libraryBuilder.build(graphBuilder, filesystem, targetGraph);
assertThat(
Arg.stringify(library.getArgs(), graphBuilder.getSourcePathResolver()),
hasItems("$SDKROOT/usr/lib", "-la", "-lz"));
assertThat(
Arg.stringify(library.getArgs(), graphBuilder.getSourcePathResolver()), hasItems("-L"));
assertThat(
Arg.stringify(library.getArgs(), graphBuilder.getSourcePathResolver()),
hasItems(matchesPattern(".*another[/\\\\]path$")));
}