下面列出了com.google.common.collect.ImmutableMap#entrySet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public ImmutableSet<CxxInferCapture> requireInferCaptureBuildRules(
ImmutableMap<String, CxxSource> sources, InferBuckConfig inferConfig) {
ImmutableSet.Builder<CxxInferCapture> objects = ImmutableSet.builder();
CxxInferSourceFilter sourceFilter = new CxxInferSourceFilter(inferConfig);
for (Map.Entry<String, CxxSource> entry : sources.entrySet()) {
String name = entry.getKey();
CxxSource source = entry.getValue();
if (sourceFilter.isBlacklisted(source)) {
continue;
}
Preconditions.checkState(
CxxSourceTypes.isPreprocessableType(source.getType()),
"Only preprocessable source types are currently supported");
CxxInferCapture rule = requireInferCaptureBuildRule(name, source, inferConfig);
objects.add(rule);
}
return objects.build();
}
/**
* Build a replacer using the given map of paths to replacement paths, using {@code charset} to
* convert to underlying byte arrays. If the replacement paths are not long enough, use the given
* path separator to fill.
*/
public static ByteBufferReplacer fromPaths(
ImmutableMap<Path, Path> paths, char separator, Charset charset) {
ImmutableMap.Builder<byte[], byte[]> replacements = ImmutableMap.builder();
for (Map.Entry<Path, Path> entry : paths.entrySet()) {
String original = entry.getKey().toString();
String replacement = entry.getValue().toString();
// If the replacement string is too small, keep adding the path separator until it's long
// enough.
while (getBytes(original, charset).length > getBytes(replacement, charset).length) {
replacement += separator;
}
// Depending on what was passed in, or the character encoding, we can end up with a
// replacement string that is too long, which we can't recover from.
Preconditions.checkArgument(
getBytes(original, charset).length == getBytes(replacement, charset).length);
replacements.put(getBytes(original, charset), getBytes(replacement, charset));
}
return new ByteBufferReplacer(replacements.build());
}
public static ImmutableMap<String, IntBoundingBox> getBoxesWithinChunk(int chunkX, int chunkZ, ImmutableMap<String, SelectionBox> subRegions)
{
ImmutableMap.Builder<String, IntBoundingBox> builder = new ImmutableMap.Builder<>();
for (Map.Entry<String, SelectionBox> entry : subRegions.entrySet())
{
SelectionBox box = entry.getValue();
IntBoundingBox bb = box != null ? getBoundsWithinChunkForBox(box, chunkX, chunkZ) : null;
if (bb != null)
{
builder.put(entry.getKey(), bb);
}
}
return builder.build();
}
private ImplicitlyLoadedExtension loadImplicitExtension(Path basePath, Label containingLabel)
throws IOException, InterruptedException {
Optional<ImplicitInclude> implicitInclude =
packageImplicitIncludeFinder.findIncludeForBuildFile(basePath);
if (!implicitInclude.isPresent()) {
return ImplicitlyLoadedExtension.empty();
}
// Only export requested symbols, and ensure that all requsted symbols are present.
ExtensionData data =
loadExtension(ImmutableLoadImport.of(containingLabel, implicitInclude.get().getLoadPath()));
ImmutableMap<String, Object> symbols = data.getExtension().getBindings();
ImmutableMap<String, String> expectedSymbols = implicitInclude.get().getSymbols();
Builder<String, Object> loaded = ImmutableMap.builderWithExpectedSize(expectedSymbols.size());
for (Entry<String, String> kvp : expectedSymbols.entrySet()) {
Object symbol = symbols.get(kvp.getValue());
if (symbol == null) {
throw BuildFileParseException.createForUnknownParseError(
String.format(
"Could not find symbol '%s' in implicitly loaded extension '%s'",
kvp.getValue(), implicitInclude.get().getLoadPath().getImportString()));
}
loaded.put(kvp.getKey(), symbol);
}
return ImmutableImplicitlyLoadedExtension.of(data, loaded.build());
}
private static IJobUpdate buildJobUpdate(
int instanceCount,
ITaskConfig newConfig,
ImmutableMap<ITaskConfig, ImmutableSet<Range>> oldConfigMap,
JobUpdateSettings jobUpdateSettings) {
ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder();
for (Map.Entry<ITaskConfig, ImmutableSet<Range>> entry : oldConfigMap.entrySet()) {
builder.add(new InstanceTaskConfig(entry.getKey().newBuilder(), entry.getValue()));
}
return IJobUpdate.build(new JobUpdate()
.setSummary(new JobUpdateSummary()
.setKey(UPDATE_KEY.newBuilder())
.setUser(IDENTITY.getUser())
.setMetadata(METADATA))
.setInstructions(new JobUpdateInstructions()
.setSettings(jobUpdateSettings)
.setDesiredState(new InstanceTaskConfig()
.setTask(newConfig.newBuilder())
.setInstances(ImmutableSet.of(new Range(0, instanceCount - 1))))
.setInitialState(builder.build())));
}
/**
* Helper method to find out if the only included fieldmapping metadata is typed NULL, which means
* that type and index exist, but the field did not
*/
private boolean isFieldMappingMissingField(ImmutableMap<String, ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>>> mappingsByIndex) throws IOException {
if (mappingsByIndex.size() != 1) {
return false;
}
for (ImmutableMap<String, ImmutableMap<String, FieldMappingMetaData>> value : mappingsByIndex.values()) {
for (ImmutableMap<String, FieldMappingMetaData> fieldValue : value.values()) {
for (Map.Entry<String, FieldMappingMetaData> fieldMappingMetaDataEntry : fieldValue.entrySet()) {
if (fieldMappingMetaDataEntry.getValue().isNull()) {
return true;
}
}
}
}
return false;
}
public static VersionedTargetGraph newInstance(ImmutableMap<BuildTarget, TargetNode<?>> index) {
VersionedTargetGraph.Builder builder = VersionedTargetGraph.builder();
for (Map.Entry<BuildTarget, TargetNode<?>> ent : index.entrySet()) {
builder.addNode(ent.getKey(), ent.getValue());
for (BuildTarget dep : ent.getValue().getBuildDeps()) {
builder.addEdge(ent.getValue(), Objects.requireNonNull(index.get(dep), dep::toString));
}
}
return builder.build();
}
@Test
@junitparams.Parameters(method = "getToolCommandMap")
@TestCaseName("{method}_{0}")
public void test_commandMap_namesAreDerivedFromClassNames(
String toolName, ImmutableMap<String, Class<? extends Command>> commandMap) {
for (Map.Entry<String, ? extends Class<? extends Command>> commandEntry :
commandMap.entrySet()) {
String className = commandEntry.getValue().getSimpleName();
expect.that(commandEntry.getKey())
// JCommander names should match the class name, up to "Command" and case formatting.
.isEqualTo(UPPER_CAMEL.to(LOWER_UNDERSCORE, className.replaceFirst("Command$", "")));
}
}
/**
* Returns a list of values and their associated {@link Path} instances by transforming the given
* {@link SourcePath} instances into {@link Path} instances.
*/
public <T> ImmutableMap<T, Path> getMappedPaths(Map<T, SourcePath> sourcePathMap) {
ImmutableMap<T, ImmutableSortedSet<Path>> mappedPaths = resolver.getMappedPaths(sourcePathMap);
ImmutableMap.Builder<T, Path> builder = new ImmutableMap.Builder<>();
for (Map.Entry<T, ImmutableSortedSet<Path>> entry : mappedPaths.entrySet()) {
builder.put(entry.getKey(), Iterables.getOnlyElement(entry.getValue()));
}
return builder.build();
}
private void doMultiCheck(ImmutableMap<RuleKey, ClaimedFetchRequest> ruleKeyToRequest) {
try {
ImmutableMap<RuleKey, CacheResult> ruleKeyToResult =
multiContainsImpl(ruleKeyToRequest.keySet()).getCacheResults();
for (Map.Entry<RuleKey, CacheResult> result : ruleKeyToResult.entrySet()) {
CacheResult cacheResult = result.getValue();
ClaimedFetchRequest claimedFetchRequest = ruleKeyToRequest.get(result.getKey());
if (claimedFetchRequest == null) {
LOG.verbose("Recived cache result for not requested rule key.");
continue;
}
if (!cacheResult.getType().isSuccess()) {
// If rule key is not present in the cache, there is no point in trying to download
// it.
claimedFetchRequest.setResult(cacheResult);
} else {
// Otherwise reschedule it. It will be added to the fetch queue and it will be picked
// by fetching thread.
claimedFetchRequest.reschedule();
}
}
} catch (IOException e) {
String msg =
String.format(
"multicheck(<%s>): %s: %s",
Joiner.on(", ").join(ruleKeyToRequest.keySet()),
e.getClass().getName(),
e.getMessage());
// Some of these might already be fulfilled. That's fine, this set() call will just be
// ignored.
for (ClaimedFetchRequest request : ruleKeyToRequest.values()) {
request.setResult(CacheResult.error(name, mode, msg));
}
}
}
/**
* Resolve the map of name to {@link SourcePath} to a map of full header name to {@link
* SourcePath}.
*/
public static ImmutableMap<Path, SourcePath> resolveHeaderMap(
Path basePath, ImmutableMap<String, SourcePath> headers) {
ImmutableMap.Builder<Path, SourcePath> headerMap = ImmutableMap.builder();
// Resolve the "names" of the headers to actual paths by prepending the base path
// specified by the build target.
for (ImmutableMap.Entry<String, SourcePath> ent : headers.entrySet()) {
Path path = basePath.resolve(ent.getKey());
headerMap.put(path, ent.getValue());
}
return headerMap.build();
}
private static boolean traceToPlacementBox(SchematicPlacement placement, Vec3d start, Vec3d end)
{
ImmutableMap<String, SelectionBox> boxes = placement.getSubRegionBoxes(RequiredEnabled.PLACEMENT_ENABLED);
boolean hitSomething = false;
for (Map.Entry<String, SelectionBox> entry : boxes.entrySet())
{
String boxName = entry.getKey();
SelectionBox box = entry.getValue();
if (box.getPos1() != null && box.getPos2() != null)
{
AxisAlignedBB bb = PositionUtils.createEnclosingAABB(box.getPos1(), box.getPos2());
RayTraceResult trace = bb.calculateIntercept(start, end);
if (trace != null)
{
double dist = trace.hitVec.distanceTo(start);
if (closestBoxDistance < 0 || dist < closestBoxDistance)
{
closestBoxDistance = dist;
closestBox = new RayTraceWrapper(placement, trace.hitVec, boxName);
hitSomething = true;
}
}
}
}
return hitSomething;
}
private CurrencyParameterSensitivities sensiModFn(ImmutableRatesProvider provider) {
CurrencyParameterSensitivities sensi = CurrencyParameterSensitivities.empty();
// Index
ImmutableMap<Index, Curve> mapIndex = provider.getIndexCurves();
for (Entry<Index, Curve> entry : mapIndex.entrySet()) {
if (entry.getKey() instanceof IborIndex) {
InterpolatedNodalCurve curveInt = checkInterpolated(entry.getValue());
double sumSqrt = sumMod(provider);
sensi = sensi.combinedWith(CurrencyParameterSensitivity.of(curveInt.getName(), USD,
DoubleArray.of(curveInt.getParameterCount(), i -> 2d * sumSqrt * curveInt.getXValues().get(i))));
}
}
return sensi;
}
private Cells getDefaultCell(
ProjectFilesystem rootFileSystem, ImmutableMap<String, Path> otherCells) {
ImmutableMap.Builder<String, String> repositories = ImmutableMap.builder();
for (Map.Entry<String, Path> entry : otherCells.entrySet()) {
repositories.put(entry.getKey(), entry.getValue().toString());
}
BuckConfig cellConfig =
FakeBuckConfig.builder()
.setFilesystem(rootFileSystem)
.setSections(ImmutableMap.of("repositories", repositories.build()))
.build();
return new TestCellBuilder().setBuckConfig(cellConfig).setFilesystem(rootFileSystem).build();
}
ImmutableList<SourcePath> generateMLNativeCompilation(
ImmutableMap<Path, ImmutableList<Path>> mlSources) {
ImmutableList.Builder<SourcePath> cmxFiles = ImmutableList.builder();
Map<Path, ImmutableSortedSet<BuildRule>> sourceToRule = new HashMap<>();
for (ImmutableMap.Entry<Path, ImmutableList<Path>> mlSource : mlSources.entrySet()) {
generateSingleMLNativeCompilation(
sourceToRule, cmxFiles, mlSource.getKey(), mlSources, ImmutableList.of());
}
return cmxFiles.build();
}
private SkylarkDict<String, Set<Artifact>> getNamedOutputs(
ActionRegistry actionRegistry, BasicRuleDescriptionArg args) {
if (!args.getNamedOuts().isPresent()) {
return SkylarkDict.empty();
}
ImmutableMap<String, ImmutableSet<String>> namedOuts = args.getNamedOuts().get();
SkylarkDict<String, Set<Artifact>> dict;
try (Mutability mutability = Mutability.create("test")) {
Environment env =
Environment.builder(mutability)
.setGlobals(BazelLibrary.GLOBALS)
.setSemantics(BuckStarlark.BUCK_STARLARK_SEMANTICS)
.build();
dict = SkylarkDict.of(env);
for (Map.Entry<String, ImmutableSet<String>> labelsToNamedOutnames : namedOuts.entrySet()) {
try {
dict.put(
labelsToNamedOutnames.getKey(),
declareArtifacts(actionRegistry, labelsToNamedOutnames.getValue()),
Location.BUILTIN,
mutability);
} catch (EvalException e) {
throw new HumanReadableException("Invalid name %s", labelsToNamedOutnames.getKey());
}
}
}
return dict;
}
private ImmutableMap<ShardId, ShardSnapshotStatus> processWaitingShards(ImmutableMap<ShardId, ShardSnapshotStatus> snapshotShards, RoutingTable routingTable) {
boolean snapshotChanged = false;
ImmutableMap.Builder<ShardId, ShardSnapshotStatus> shards = ImmutableMap.builder();
for (ImmutableMap.Entry<ShardId, ShardSnapshotStatus> shardEntry : snapshotShards.entrySet()) {
ShardSnapshotStatus shardStatus = shardEntry.getValue();
if (shardStatus.state() == State.WAITING) {
ShardId shardId = shardEntry.getKey();
IndexRoutingTable indexShardRoutingTable = routingTable.index(shardId.getIndex());
if (indexShardRoutingTable != null) {
IndexShardRoutingTable shardRouting = indexShardRoutingTable.shard(shardId.id());
if (shardRouting != null && shardRouting.primaryShard() != null) {
if (shardRouting.primaryShard().started()) {
// Shard that we were waiting for has started on a node, let's process it
snapshotChanged = true;
logger.trace("starting shard that we were waiting for [{}] on node [{}]", shardEntry.getKey(), shardStatus.nodeId());
shards.put(shardEntry.getKey(), new ShardSnapshotStatus(shardRouting.primaryShard().currentNodeId()));
continue;
} else if (shardRouting.primaryShard().initializing() || shardRouting.primaryShard().relocating()) {
// Shard that we were waiting for hasn't started yet or still relocating - will continue to wait
shards.put(shardEntry);
continue;
}
}
}
// Shard that we were waiting for went into unassigned state or disappeared - giving up
snapshotChanged = true;
logger.warn("failing snapshot of shard [{}] on unassigned shard [{}]", shardEntry.getKey(), shardStatus.nodeId());
shards.put(shardEntry.getKey(), new ShardSnapshotStatus(shardStatus.nodeId(), State.FAILED, "shard is unassigned"));
} else {
shards.put(shardEntry);
}
}
if (snapshotChanged) {
return shards.build();
} else {
return null;
}
}
/**
* Desugar the classes that are generated on the fly when we are desugaring the classes in the
* specified inputs.
*/
private void desugarAndWriteDumpedLambdaClassesToOutput(
OutputFileProvider outputFileProvider,
ClassLoader loader,
@Nullable ClassReaderFactory classpathReader,
DependencyCollector depsCollector,
ClassReaderFactory bootclasspathReader,
@Nullable CoreLibrarySupport coreLibrarySupport,
ClassVsInterface interfaceCache,
ImmutableSet<String> interfaceLambdaMethods,
@Nullable ClassReaderFactory bridgeMethodReader,
InvocationSiteTransformationRecordBuilder callSiteTransCollector,
BootClassPathDigest bootClassPathDigest,
ClassAttributeRecord classAttributeRecord,
ImmutableSet.Builder<ClassName> requiredRuntimeSupportTypes,
ClassMemberRetargetConfig classMemberRetargetConfig)
throws IOException {
checkState(
!allowDefaultMethods || interfaceLambdaMethods.isEmpty(),
"Desugaring with default methods enabled moved interface lambdas");
// Write out the lambda classes we generated along the way
ImmutableMap<Path, LambdaInfo> lambdaClasses = lambdas.drain();
checkState(
!options.onlyDesugarJavac9ForLint || lambdaClasses.isEmpty(),
"There should be no lambda classes generated: %s",
lambdaClasses.keySet());
for (Map.Entry<Path, LambdaInfo> lambdaClass : lambdaClasses.entrySet()) {
try (InputStream bytecode = Files.newInputStream(lambdaClass.getKey())) {
ClassReader reader = rewriter.reader(bytecode);
InvokeDynamicLambdaMethodCollector collector = new InvokeDynamicLambdaMethodCollector();
reader.accept(
collector, customAttributes, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
ImmutableSet<MethodInfo> lambdaMethods = collector.getLambdaMethodsUsedInInvokeDynamics();
checkState(
lambdaMethods.isEmpty(),
"Didn't expect to find lambda methods but found %s",
lambdaMethods);
UnprefixingClassWriter writer =
rewriter.writer(ClassWriter.COMPUTE_MAXS /*for invoking bridges*/);
ClassVisitor visitor =
createClassVisitorsForDumpedLambdaClasses(
loader,
classpathReader,
depsCollector,
bootclasspathReader,
coreLibrarySupport,
interfaceCache,
interfaceLambdaMethods,
bridgeMethodReader,
lambdaClass.getValue(),
writer,
reader,
callSiteTransCollector,
bootClassPathDigest,
classAttributeRecord,
requiredRuntimeSupportTypes,
classMemberRetargetConfig);
reader.accept(visitor, customAttributes, ClassReader.EXPAND_FRAMES);
checkState(
(options.coreLibrary && coreLibrarySupport != null)
|| rewriter
.unprefix(lambdaClass.getValue().desiredInternalName())
.equals(writer.getClassName()));
outputFileProvider.write(writer.getClassName() + ".class", writer.toByteArray());
}
}
}
/**
* Translates the 'cell name'->override map into a 'Path'->override map.
*
* @param pathMapping a map containing paths to all of the cells we want to query.
* @return 'Path'->override map
*/
public ImmutableMap<AbsPath, RawConfig> getOverridesByPath(
ImmutableMap<CellName, AbsPath> pathMapping) throws InvalidCellOverrideException {
ImmutableSet<CellName> relativeNamesOfCellsWithOverrides =
FluentIterable.from(getValues().keySet())
.filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals))
.toSet();
ImmutableSet.Builder<AbsPath> pathsWithOverrides = ImmutableSet.builder();
for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
if (!pathMapping.containsKey(cellWithOverride)) {
throw new InvalidCellOverrideException(
String.format("Trying to override settings for unknown cell %s", cellWithOverride));
}
pathsWithOverrides.add(pathMapping.get(cellWithOverride));
}
ImmutableMultimap<AbsPath, CellName> pathToRelativeName =
Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping));
for (AbsPath pathWithOverrides : pathsWithOverrides.build()) {
ImmutableList<CellName> namesForPath =
RichStream.from(pathToRelativeName.get(pathWithOverrides))
.filter(name -> name.getLegacyName().isPresent())
.toImmutableList();
if (namesForPath.size() > 1) {
throw new InvalidCellOverrideException(
String.format(
"Configuration override is ambiguous: cell rooted at %s is reachable "
+ "as [%s]. Please override the config by placing a .buckconfig.local file in the "
+ "cell's root folder.",
pathWithOverrides, Joiner.on(',').join(namesForPath)));
}
}
Map<AbsPath, RawConfig> overridesByPath = new HashMap<>();
for (Map.Entry<CellName, AbsPath> entry : pathMapping.entrySet()) {
CellName cellRelativeName = entry.getKey();
AbsPath cellPath = entry.getValue();
RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
RawConfig config = getForCell(cellRelativeName);
if (configFromOtherRelativeName != null) {
// Merge configs
RawConfig mergedConfig =
RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config).build();
overridesByPath.put(cellPath, mergedConfig);
} else {
overridesByPath.put(cellPath, config);
}
}
return ImmutableMap.copyOf(overridesByPath);
}
private ImmutableMap<Flavor, RuleKey> constructLinkRuleKeys(
ImmutableMap<Flavor, AppleCxxPlatform> cxxPlatforms) throws NoSuchBuildTargetException {
ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
DefaultRuleKeyFactory ruleKeyFactory =
new TestDefaultRuleKeyFactory(
FakeFileHashCache.createFromStrings(
ImmutableMap.<String, String>builder()
.put("input.o", Strings.repeat("a", 40))
.build()),
graphBuilder);
BuildTarget target = BuildTargetFactory.newInstance("//:target");
ImmutableMap.Builder<Flavor, RuleKey> ruleKeys = ImmutableMap.builder();
for (Map.Entry<Flavor, AppleCxxPlatform> entry : cxxPlatforms.entrySet()) {
BuildRule rule =
CxxLinkableEnhancer.createCxxLinkableBuildRule(
CxxPlatformUtils.DEFAULT_CONFIG,
entry.getValue().getCxxPlatform(),
new FakeProjectFilesystem(),
graphBuilder,
target,
Linker.LinkType.EXECUTABLE,
Optional.empty(),
projectFilesystem.getPath("output"),
ImmutableList.of(),
Linker.LinkableDepType.SHARED,
Optional.empty(),
CxxLinkOptions.of(),
ImmutableList.of(),
Optional.empty(),
Optional.empty(),
ImmutableSet.of(),
ImmutableSet.of(),
NativeLinkableInput.builder()
.setArgs(SourcePathArg.from(FakeSourcePath.of("input.o")))
.build(),
Optional.empty(),
TestCellPathResolver.get(projectFilesystem));
ruleKeys.put(entry.getKey(), ruleKeyFactory.build(rule));
}
return ruleKeys.build();
}