Search in sources :

Example 26 with Optional

use of java.util.Optional in project buck by facebook.

the class GoTestDescription method createBuildRule.

@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params, final BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {
    GoPlatform platform = goBuckConfig.getPlatformFlavorDomain().getValue(params.getBuildTarget()).orElse(goBuckConfig.getDefaultPlatform());
    if (params.getBuildTarget().getFlavors().contains(TEST_LIBRARY_FLAVOR)) {
        return createTestLibrary(params, resolver, args, platform);
    }
    GoBinary testMain = createTestMainRule(params, resolver, args, platform);
    resolver.addToIndex(testMain);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    return new GoTest(params.copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.of(testMain)), Suppliers.ofInstance(ImmutableSortedSet.of())), ruleFinder, testMain, args.labels, args.contacts, args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.runTestSeparately.orElse(false), args.resources);
}
Also used : Optional(java.util.Optional) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder)

Example 27 with Optional

use of java.util.Optional in project buck by facebook.

the class JUnitStep method getTimeoutHandler.

@Override
protected Optional<Consumer<Process>> getTimeoutHandler(final ExecutionContext context) {
    return Optional.of(process -> {
        Optional<Long> pid = Optional.empty();
        Platform platform = context.getPlatform();
        try {
            switch(platform) {
                case LINUX:
                case FREEBSD:
                case MACOS:
                    {
                        Field field = process.getClass().getDeclaredField("pid");
                        field.setAccessible(true);
                        try {
                            pid = Optional.of((long) field.getInt(process));
                        } catch (IllegalAccessException e) {
                            LOG.error(e, "Failed to access `pid`.");
                        }
                        break;
                    }
                case WINDOWS:
                    {
                        Field field = process.getClass().getDeclaredField("handle");
                        field.setAccessible(true);
                        try {
                            pid = Optional.of(field.getLong(process));
                        } catch (IllegalAccessException e) {
                            LOG.error(e, "Failed to access `handle`.");
                        }
                        break;
                    }
                case UNKNOWN:
                    LOG.info("Unknown platform; unable to obtain the process id!");
                    break;
            }
        } catch (NoSuchFieldException e) {
            LOG.error(e);
        }
        Optional<Path> jstack = new ExecutableFinder(context.getPlatform()).getOptionalExecutable(Paths.get("jstack"), context.getEnvironment());
        if (!pid.isPresent() || !jstack.isPresent()) {
            LOG.info("Unable to print a stack trace for timed out test!");
            return;
        }
        context.getStdErr().println("Test has timed out!  Here is a trace of what it is currently doing:");
        try {
            context.getProcessExecutor().launchAndExecute(ProcessExecutorParams.builder().addCommand(jstack.get().toString(), "-l", pid.get().toString()).setEnvironment(context.getEnvironment()).build(), ImmutableSet.<ProcessExecutor.Option>builder().add(ProcessExecutor.Option.PRINT_STD_OUT).add(ProcessExecutor.Option.PRINT_STD_ERR).build(), Optional.empty(), Optional.of(TimeUnit.SECONDS.toMillis(30)), Optional.of(input -> {
                context.getStdErr().print("Printing the stack took longer than 30 seconds. No longer trying.");
            }));
        } catch (Exception e) {
            LOG.error(e);
        }
    });
}
Also used : Path(java.nio.file.Path) Logger(com.facebook.buck.log.Logger) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Platform(com.facebook.buck.util.environment.Platform) ExecutableFinder(com.facebook.buck.io.ExecutableFinder) ProcessExecutorParams(com.facebook.buck.util.ProcessExecutorParams) Field(java.lang.reflect.Field) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) ExecutionContext(com.facebook.buck.step.ExecutionContext) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ImmutableList(com.google.common.collect.ImmutableList) ProcessExecutor(com.facebook.buck.util.ProcessExecutor) Paths(java.nio.file.Paths) Map(java.util.Map) Optional(java.util.Optional) ShellStep(com.facebook.buck.shell.ShellStep) Path(java.nio.file.Path) Field(java.lang.reflect.Field) ExecutableFinder(com.facebook.buck.io.ExecutableFinder) Platform(com.facebook.buck.util.environment.Platform)

Example 28 with Optional

use of java.util.Optional in project buck by facebook.

the class ScalaTestDescription method createBuildRule.

@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, final BuildRuleParams rawParams, final BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    if (CalculateAbi.isAbiTarget(rawParams.getBuildTarget())) {
        BuildTarget testTarget = CalculateAbi.getLibraryTarget(rawParams.getBuildTarget());
        BuildRule testRule = resolver.requireRule(testTarget);
        return CalculateAbi.of(rawParams.getBuildTarget(), ruleFinder, rawParams, Preconditions.checkNotNull(testRule.getSourcePathToOutput()));
    }
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    final BuildRule scalaLibrary = resolver.getRule(config.getScalaLibraryTarget());
    BuildRuleParams params = rawParams.copyReplacingDeclaredAndExtraDeps(() -> ImmutableSortedSet.<BuildRule>naturalOrder().addAll(rawParams.getDeclaredDeps().get()).add(scalaLibrary).build(), rawParams.getExtraDeps());
    JavaTestDescription.CxxLibraryEnhancement cxxLibraryEnhancement = new JavaTestDescription.CxxLibraryEnhancement(params, args.useCxxLibraries, args.cxxLibraryWhitelist, resolver, ruleFinder, cxxPlatform);
    params = cxxLibraryEnhancement.updatedParams;
    Tool scalac = config.getScalac(resolver);
    BuildRuleParams javaLibraryParams = params.copyAppendingExtraDeps(Iterables.concat(BuildRules.getExportedRules(Iterables.concat(params.getDeclaredDeps().get(), resolver.getAllRules(args.providedDeps))), scalac.getDeps(ruleFinder))).withAppendedFlavor(JavaTest.COMPILED_TESTS_LIBRARY_FLAVOR);
    JavaLibrary testsLibrary = resolver.addToIndex(new DefaultJavaLibrary(javaLibraryParams, pathResolver, ruleFinder, args.srcs, ResourceValidator.validateResources(pathResolver, params.getProjectFilesystem(), args.resources), /* generatedSourceFolderName */
    Optional.empty(), /* proguardConfig */
    Optional.empty(), /* postprocessClassesCommands */
    ImmutableList.of(), /* exportDeps */
    ImmutableSortedSet.of(), /* providedDeps */
    ImmutableSortedSet.of(), JavaLibraryRules.getAbiInputs(resolver, javaLibraryParams.getDeps()), /* trackClassUsage */
    false, /* additionalClasspathEntries */
    ImmutableSet.of(), new ScalacToJarStepFactory(scalac, config.getCompilerFlags(), args.extraArguments, ImmutableSet.of()), args.resourcesRoot, args.manifestFile, args.mavenCoords, /* tests */
    ImmutableSortedSet.of(), /* classesToRemoveFromJar */
    ImmutableSet.of()));
    return new JavaTest(params.copyReplacingDeclaredAndExtraDeps(Suppliers.ofInstance(ImmutableSortedSet.of(testsLibrary)), Suppliers.ofInstance(ImmutableSortedSet.of())), pathResolver, testsLibrary, /* additionalClasspathEntries */
    ImmutableSet.of(), args.labels, args.contacts, args.testType.orElse(TestType.JUNIT), javaOptions.getJavaRuntimeLauncher(), args.vmArgs, cxxLibraryEnhancement.nativeLibsEnvironment, args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.testCaseTimeoutMs, args.env, args.runTestSeparately.orElse(false), args.forkMode.orElse(ForkMode.NONE), args.stdOutLogLevel, args.stdErrLogLevel);
}
Also used : Optional(java.util.Optional) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) DefaultJavaLibrary(com.facebook.buck.jvm.java.DefaultJavaLibrary) BuildRuleParams(com.facebook.buck.rules.BuildRuleParams) JavaLibrary(com.facebook.buck.jvm.java.JavaLibrary) DefaultJavaLibrary(com.facebook.buck.jvm.java.DefaultJavaLibrary) BuildTarget(com.facebook.buck.model.BuildTarget) JavaTestDescription(com.facebook.buck.jvm.java.JavaTestDescription) JavaTest(com.facebook.buck.jvm.java.JavaTest) BuildRule(com.facebook.buck.rules.BuildRule) Tool(com.facebook.buck.rules.Tool)

Example 29 with Optional

use of java.util.Optional in project buck by facebook.

the class LuaStandaloneBinary method getBuildSteps.

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    buildableContext.recordArtifact(output);
    // Make sure the parent directory exists.
    steps.add(new MkdirStep(getProjectFilesystem(), output.getParent()));
    // Delete any other pex that was there (when switching between pex styles).
    steps.add(new RmStep(getProjectFilesystem(), output, RmStep.Mode.RECURSIVE));
    SourcePathResolver resolver = context.getSourcePathResolver();
    steps.add(new ShellStep(getProjectFilesystem().getRootPath()) {

        @Override
        protected Optional<String> getStdin(ExecutionContext context) {
            try {
                return Optional.of(context.getObjectMapper().writeValueAsString(ImmutableMap.of("modules", Maps.transformValues(components.getModules(), Functions.compose(Object::toString, resolver::getAbsolutePath)), "pythonModules", Maps.transformValues(components.getPythonModules(), Functions.compose(Object::toString, resolver::getAbsolutePath)), "nativeLibraries", Maps.transformValues(components.getNativeLibraries(), Functions.compose(Object::toString, resolver::getAbsolutePath)))));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
            ImmutableList.Builder<String> command = ImmutableList.builder();
            command.addAll(builder.getCommandPrefix(resolver));
            command.addAll(builderArgs);
            command.add("--entry-point", mainModule);
            command.add("--interpreter");
            if (starter.isPresent()) {
                command.add(resolver.getAbsolutePath(starter.get()).toString());
            } else {
                command.add(lua.getCommandPrefix(resolver).get(0));
            }
            command.add(getProjectFilesystem().resolve(output).toString());
            return command.build();
        }

        @Override
        public String getShortName() {
            return "lua_package";
        }
    });
    return steps.build();
}
Also used : Optional(java.util.Optional) ImmutableList(com.google.common.collect.ImmutableList) MkdirStep(com.facebook.buck.step.fs.MkdirStep) RmStep(com.facebook.buck.step.fs.RmStep) Step(com.facebook.buck.step.Step) MkdirStep(com.facebook.buck.step.fs.MkdirStep) ShellStep(com.facebook.buck.shell.ShellStep) IOException(java.io.IOException) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) RmStep(com.facebook.buck.step.fs.RmStep) ExecutionContext(com.facebook.buck.step.ExecutionContext) ShellStep(com.facebook.buck.shell.ShellStep)

Example 30 with Optional

use of java.util.Optional in project buck by facebook.

the class ShTestDescription method createBuildRule.

@Override
public <A extends Arg> ShTest createBuildRule(TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    Function<String, com.facebook.buck.rules.args.Arg> toArg = MacroArg.toMacroArgFunction(MACRO_HANDLER, params.getBuildTarget(), params.getCellRoots(), resolver);
    final ImmutableList<com.facebook.buck.rules.args.Arg> testArgs = args.args.stream().map(toArg::apply).collect(MoreCollectors.toImmutableList());
    final ImmutableMap<String, com.facebook.buck.rules.args.Arg> testEnv = ImmutableMap.copyOf(Maps.transformValues(args.env, toArg));
    return new ShTest(params.copyAppendingExtraDeps(() -> FluentIterable.from(testArgs).append(testEnv.values()).transformAndConcat(arg -> arg.getDeps(ruleFinder))), ruleFinder, args.test, testArgs, testEnv, FluentIterable.from(args.resources).transform(p -> new PathSourcePath(params.getProjectFilesystem(), p)).toSortedSet(Ordering.natural()), args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.runTestSeparately.orElse(false), args.labels, args.contacts);
}
Also used : Optional(java.util.Optional) MacroArg(com.facebook.buck.rules.args.MacroArg) AbstractDescriptionArg(com.facebook.buck.rules.AbstractDescriptionArg) PathSourcePath(com.facebook.buck.rules.PathSourcePath) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder)

Aggregations

Optional (java.util.Optional)3042 List (java.util.List)1831 Map (java.util.Map)1086 ArrayList (java.util.ArrayList)1032 Collectors (java.util.stream.Collectors)971 Set (java.util.Set)768 IOException (java.io.IOException)742 HashMap (java.util.HashMap)644 Test (org.junit.Test)526 Collections (java.util.Collections)506 Arrays (java.util.Arrays)454 Collection (java.util.Collection)442 Logger (org.slf4j.Logger)432 LoggerFactory (org.slf4j.LoggerFactory)425 HashSet (java.util.HashSet)386 Objects (java.util.Objects)324 ImmutableList (com.google.common.collect.ImmutableList)290 Stream (java.util.stream.Stream)282 ImmutableMap (com.google.common.collect.ImmutableMap)243 Function (java.util.function.Function)226