Search in sources :

Example 16 with ProjectFilesystem

use of com.facebook.buck.io.ProjectFilesystem in project buck by facebook.

the class BuildCommand method executeDistributedBuild.

private int executeDistributedBuild(final CommandRunnerParams params, ActionAndTargetGraphs graphs, final WeightedListeningExecutorService executorService) throws IOException, InterruptedException {
    // Distributed builds serialize and send the unversioned target graph,
    // and then deserialize and version remotely.
    TargetGraphAndBuildTargets targetGraphAndBuildTargets = graphs.unversionedTargetGraph;
    ProjectFilesystem filesystem = params.getCell().getFilesystem();
    FileHashCache fileHashCache = params.getFileHashCache();
    DistBuildTypeCoercerFactory typeCoercerFactory = new DistBuildTypeCoercerFactory(params.getObjectMapper());
    ParserTargetNodeFactory<TargetNode<?, ?>> parserTargetNodeFactory = DefaultParserTargetNodeFactory.createForDistributedBuild(new ConstructorArgMarshaller(typeCoercerFactory), new TargetNodeFactory(typeCoercerFactory));
    DistBuildTargetGraphCodec targetGraphCodec = new DistBuildTargetGraphCodec(params.getObjectMapper(), parserTargetNodeFactory, new Function<TargetNode<?, ?>, Map<String, Object>>() {

        @Nullable
        @Override
        public Map<String, Object> apply(TargetNode<?, ?> input) {
            try {
                return params.getParser().getRawTargetNode(params.getBuckEventBus(), params.getCell().getCell(input.getBuildTarget()), false, /* enableProfiling */
                executorService, input);
            } catch (BuildFileParseException e) {
                throw new RuntimeException(e);
            }
        }
    }, targetGraphAndBuildTargets.getBuildTargets().stream().map(t -> t.getFullyQualifiedName()).collect(Collectors.toSet()));
    BuildJobState jobState = computeDistributedBuildJobState(targetGraphCodec, params, targetGraphAndBuildTargets, graphs.actionGraph, executorService);
    if (distributedBuildStateFile != null) {
        Path stateDumpPath = Paths.get(distributedBuildStateFile);
        BuildJobStateSerializer.serialize(jobState, filesystem.newFileOutputStream(stateDumpPath));
        return 0;
    } else {
        BuckVersion buckVersion = getBuckVersion();
        Preconditions.checkArgument(params.getInvocationInfo().isPresent());
        try (DistBuildService service = DistBuildFactory.newDistBuildService(params);
            DistBuildLogStateTracker distBuildLogStateTracker = DistBuildFactory.newDistBuildLogStateTracker(params.getInvocationInfo().get().getLogDirectoryPath(), filesystem)) {
            DistBuildClientExecutor build = new DistBuildClientExecutor(jobState, service, distBuildLogStateTracker, 1000, /* millisBetweenStatusPoll */
            buckVersion);
            int exitCode = build.executeAndPrintFailuresToEventBus(executorService, filesystem, fileHashCache, params.getBuckEventBus());
            // TODO(shivanker): Add a flag to disable building, and only fetch from the cache.
            if (exitCode == 0) {
                exitCode = executeLocalBuild(params, graphs.actionGraph, executorService);
            }
            return exitCode;
        }
    }
}
Also used : Path(java.nio.file.Path) SourcePath(com.facebook.buck.rules.SourcePath) FileHashCache(com.facebook.buck.util.cache.FileHashCache) TargetNode(com.facebook.buck.rules.TargetNode) BuildJobState(com.facebook.buck.distributed.thrift.BuildJobState) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) DistBuildService(com.facebook.buck.distributed.DistBuildService) ConstructorArgMarshaller(com.facebook.buck.rules.ConstructorArgMarshaller) BuckVersion(com.facebook.buck.distributed.thrift.BuckVersion) TargetNodeFactory(com.facebook.buck.rules.TargetNodeFactory) DefaultParserTargetNodeFactory(com.facebook.buck.parser.DefaultParserTargetNodeFactory) ParserTargetNodeFactory(com.facebook.buck.parser.ParserTargetNodeFactory) DistBuildClientExecutor(com.facebook.buck.distributed.DistBuildClientExecutor) DistBuildTargetGraphCodec(com.facebook.buck.distributed.DistBuildTargetGraphCodec) DistBuildLogStateTracker(com.facebook.buck.distributed.DistBuildLogStateTracker) DistBuildTypeCoercerFactory(com.facebook.buck.distributed.DistBuildTypeCoercerFactory) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) TargetGraphAndBuildTargets(com.facebook.buck.rules.TargetGraphAndBuildTargets) Nullable(javax.annotation.Nullable)

Example 17 with ProjectFilesystem

use of com.facebook.buck.io.ProjectFilesystem in project buck by facebook.

the class CleanCommand method runWithoutHelp.

@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException {
    // Ideally, we would like the implementation of this method to be as simple as:
    //
    // getProjectFilesystem().deleteRecursivelyIfExists(BuckConstant.BUCK_OUTPUT_DIRECTORY);
    //
    // However, we want to avoid blowing away directories that IntelliJ indexes, because that tends
    // to make it angry. Currently, those directories are:
    //
    // Project.ANDROID_GEN_DIR
    // BuckConstant.ANNOTATION_DIR
    //
    // However, Buck itself also uses BuckConstant.ANNOTATION_DIR. We need to fix things so that
    // IntelliJ does its default thing to generate code from annotations, and manages/indexes those
    // directories itself so we can blow away BuckConstant.ANNOTATION_DIR as part of `buck clean`.
    // This will also reduce how long `buck project` takes.
    //
    ProjectFilesystem projectFilesystem = params.getCell().getFilesystem();
    if (isCleanBuckProjectFiles()) {
        // Delete directories that were created for the purpose of `buck project`.
        // TODO(bolinfest): Unify these two directories under a single buck-ide directory,
        // which is distinct from the buck-out directory.
        projectFilesystem.deleteRecursivelyIfExists(Project.getAndroidGenPath(projectFilesystem));
        projectFilesystem.deleteRecursivelyIfExists(projectFilesystem.getBuckPaths().getAnnotationDir());
    } else {
        // On Windows, you have to close all files that will be deleted.
        // Because buck clean will delete build.log, you must close it first.
        JavaUtilsLoggingBuildListener.closeLogFile();
        projectFilesystem.deleteRecursivelyIfExists(projectFilesystem.getBuckPaths().getScratchDir());
        projectFilesystem.deleteRecursivelyIfExists(projectFilesystem.getBuckPaths().getGenDir());
        projectFilesystem.deleteRecursivelyIfExists(projectFilesystem.getBuckPaths().getTrashDir());
    }
    return 0;
}
Also used : ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem)

Example 18 with ProjectFilesystem

use of com.facebook.buck.io.ProjectFilesystem in project buck by facebook.

the class CellProvider method createForLocalBuild.

/**
   * Create a cell provider at a given root.
   */
public static CellProvider createForLocalBuild(ProjectFilesystem rootFilesystem, Watchman watchman, BuckConfig rootConfig, CellConfig rootCellConfigOverrides, KnownBuildRuleTypesFactory knownBuildRuleTypesFactory) throws IOException {
    DefaultCellPathResolver rootCellCellPathResolver = new DefaultCellPathResolver(rootFilesystem.getRootPath(), rootConfig.getConfig());
    ImmutableMap<RelativeCellName, Path> transitiveCellPathMapping = rootCellCellPathResolver.getTransitivePathMapping();
    ImmutableMap<Path, RawConfig> pathToConfigOverrides;
    try {
        pathToConfigOverrides = rootCellConfigOverrides.getOverridesByPath(transitiveCellPathMapping);
    } catch (CellConfig.MalformedOverridesException e) {
        throw new HumanReadableException(e.getMessage());
    }
    ImmutableSet<Path> allRoots = ImmutableSet.copyOf(transitiveCellPathMapping.values());
    return new CellProvider(cellProvider -> new CacheLoader<Path, Cell>() {

        @Override
        public Cell load(Path cellPath) throws IOException, InterruptedException {
            Path normalizedCellPath = cellPath.toRealPath().normalize();
            Preconditions.checkState(allRoots.contains(normalizedCellPath), "Cell %s outside of transitive closure of root cell (%s).", normalizedCellPath, allRoots);
            RawConfig configOverrides = Optional.ofNullable(pathToConfigOverrides.get(normalizedCellPath)).orElse(RawConfig.of(ImmutableMap.of()));
            Config config = Configs.createDefaultConfig(normalizedCellPath, configOverrides);
            DefaultCellPathResolver cellPathResolver = new DefaultCellPathResolver(normalizedCellPath, config);
            cellPathResolver.getCellPaths().forEach((name, path) -> {
                Path pathInRootResolver = rootCellCellPathResolver.getCellPaths().get(name);
                if (pathInRootResolver == null) {
                    throw new HumanReadableException("In the config of %s:  %s.%s must exist in the root cell's cell mappings.", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name);
                } else if (!pathInRootResolver.equals(path)) {
                    throw new HumanReadableException("In the config of %s:  %s.%s must point to the same directory as the root " + "cell's cell mapping: (root) %s != (current) %s", cellPath.toString(), DefaultCellPathResolver.REPOSITORIES_SECTION, name, pathInRootResolver, path);
                }
            });
            ProjectFilesystem cellFilesystem = new ProjectFilesystem(normalizedCellPath, config);
            BuckConfig buckConfig = new BuckConfig(config, cellFilesystem, rootConfig.getArchitecture(), rootConfig.getPlatform(), rootConfig.getEnvironment(), cellPathResolver);
            return new Cell(cellPathResolver.getKnownRoots(), cellFilesystem, watchman, buckConfig, knownBuildRuleTypesFactory, cellProvider);
        }
    }, cellProvider -> {
        try {
            return new Cell(rootCellCellPathResolver.getKnownRoots(), rootFilesystem, watchman, rootConfig, knownBuildRuleTypesFactory, cellProvider);
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while loading root cell", e);
        } catch (IOException e) {
            throw new HumanReadableException("Failed to load root cell", e);
        }
    });
}
Also used : Path(java.nio.file.Path) LoadingCache(com.google.common.cache.LoadingCache) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Config(com.facebook.buck.config.Config) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) Configs(com.facebook.buck.config.Configs) HumanReadableException(com.facebook.buck.util.HumanReadableException) Watchman(com.facebook.buck.io.Watchman) Function(java.util.function.Function) RawConfig(com.facebook.buck.config.RawConfig) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) CacheLoader(com.google.common.cache.CacheLoader) ExecutionException(java.util.concurrent.ExecutionException) BuckConfig(com.facebook.buck.cli.BuckConfig) CellConfig(com.facebook.buck.config.CellConfig) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) CacheBuilder(com.google.common.cache.CacheBuilder) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) Config(com.facebook.buck.config.Config) RawConfig(com.facebook.buck.config.RawConfig) BuckConfig(com.facebook.buck.cli.BuckConfig) CellConfig(com.facebook.buck.config.CellConfig) IOException(java.io.IOException) RawConfig(com.facebook.buck.config.RawConfig) BuckConfig(com.facebook.buck.cli.BuckConfig) HumanReadableException(com.facebook.buck.util.HumanReadableException) CellConfig(com.facebook.buck.config.CellConfig) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem)

Example 19 with ProjectFilesystem

use of com.facebook.buck.io.ProjectFilesystem in project buck by facebook.

the class SwiftCompile method makeCompileStep.

private SwiftCompileStep makeCompileStep(SourcePathResolver resolver) {
    ImmutableList.Builder<String> compilerCommand = ImmutableList.builder();
    compilerCommand.addAll(swiftCompiler.getCommandPrefix(resolver));
    if (bridgingHeader.isPresent()) {
        compilerCommand.add("-import-objc-header", resolver.getRelativePath(bridgingHeader.get()).toString());
    }
    final Function<FrameworkPath, Path> frameworkPathToSearchPath = CxxDescriptionEnhancer.frameworkPathToSearchPath(cxxPlatform, resolver);
    compilerCommand.addAll(frameworks.stream().map(frameworkPathToSearchPath::apply).flatMap(searchPath -> ImmutableSet.of("-F", searchPath.toString()).stream()).iterator());
    compilerCommand.addAll(MoreIterables.zipAndConcat(Iterables.cycle("-Xcc"), getSwiftIncludeArgs(resolver)));
    compilerCommand.addAll(MoreIterables.zipAndConcat(Iterables.cycle(INCLUDE_FLAG), getDeps().stream().filter(SwiftCompile.class::isInstance).map(BuildRule::getSourcePathToOutput).map(input -> resolver.getAbsolutePath(input).toString()).collect(MoreCollectors.toImmutableSet())));
    Optional<Iterable<String>> configFlags = swiftBuckConfig.getFlags();
    if (configFlags.isPresent()) {
        compilerCommand.addAll(configFlags.get());
    }
    boolean hasMainEntry = srcs.stream().map(input -> resolver.getAbsolutePath(input).getFileName().toString()).anyMatch(SwiftDescriptions.SWIFT_MAIN_FILENAME::equalsIgnoreCase);
    compilerCommand.add("-c", enableObjcInterop ? "-enable-objc-interop" : "", hasMainEntry ? "" : "-parse-as-library", "-module-name", moduleName, "-emit-module", "-emit-module-path", modulePath.toString(), "-o", objectPath.toString(), "-emit-objc-header-path", headerPath.toString());
    compilerCommand.addAll(compilerFlags);
    for (SourcePath sourcePath : srcs) {
        compilerCommand.add(resolver.getRelativePath(sourcePath).toString());
    }
    ProjectFilesystem projectFilesystem = getProjectFilesystem();
    return new SwiftCompileStep(projectFilesystem.getRootPath(), ImmutableMap.of(), compilerCommand.build());
}
Also used : FrameworkPath(com.facebook.buck.rules.coercer.FrameworkPath) SourcePath(com.facebook.buck.rules.SourcePath) Path(java.nio.file.Path) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) Iterables(com.google.common.collect.Iterables) Step(com.facebook.buck.step.Step) SourcePathArg(com.facebook.buck.rules.args.SourcePathArg) FrameworkPath(com.facebook.buck.rules.coercer.FrameworkPath) SourcePath(com.facebook.buck.rules.SourcePath) CxxHeaders(com.facebook.buck.cxx.CxxHeaders) MkdirStep(com.facebook.buck.step.fs.MkdirStep) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) BuildRule(com.facebook.buck.rules.BuildRule) Tool(com.facebook.buck.rules.Tool) ImmutableList(com.google.common.collect.ImmutableList) CxxPreprocessables(com.facebook.buck.cxx.CxxPreprocessables) NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) StringArg(com.facebook.buck.rules.args.StringArg) BuildRuleParams(com.facebook.buck.rules.BuildRuleParams) Path(java.nio.file.Path) CxxDescriptionEnhancer(com.facebook.buck.cxx.CxxDescriptionEnhancer) LinkedHashSet(java.util.LinkedHashSet) MoreCollectors(com.facebook.buck.util.MoreCollectors) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) FileListableLinkerInputArg(com.facebook.buck.rules.args.FileListableLinkerInputArg) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) AddToRuleKey(com.facebook.buck.rules.AddToRuleKey) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) ImmutableMap(com.google.common.collect.ImmutableMap) BuildableContext(com.facebook.buck.rules.BuildableContext) CxxPlatform(com.facebook.buck.cxx.CxxPlatform) BuildTarget(com.facebook.buck.model.BuildTarget) HeaderVisibility(com.facebook.buck.cxx.HeaderVisibility) AbstractBuildRule(com.facebook.buck.rules.AbstractBuildRule) LinkerMapMode(com.facebook.buck.cxx.LinkerMapMode) Arg(com.facebook.buck.rules.args.Arg) CxxPreprocessorInput(com.facebook.buck.cxx.CxxPreprocessorInput) BuildContext(com.facebook.buck.rules.BuildContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MoreIterables(com.facebook.buck.util.MoreIterables) ImmutableList(com.google.common.collect.ImmutableList) FrameworkPath(com.facebook.buck.rules.coercer.FrameworkPath) SourcePath(com.facebook.buck.rules.SourcePath) ExplicitBuildTargetSourcePath(com.facebook.buck.rules.ExplicitBuildTargetSourcePath) BuildRule(com.facebook.buck.rules.BuildRule) AbstractBuildRule(com.facebook.buck.rules.AbstractBuildRule) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem)

Example 20 with ProjectFilesystem

use of com.facebook.buck.io.ProjectFilesystem in project buck by facebook.

the class DefaultFileHashCache method createOsRootDirectoriesCaches.

public static ImmutableList<? extends ProjectFileHashCache> createOsRootDirectoriesCaches() {
    ImmutableList.Builder<ProjectFileHashCache> allCaches = ImmutableList.builder();
    for (Path root : FileSystems.getDefault().getRootDirectories()) {
        if (!root.toFile().exists()) {
            // as a cacheable location.
            continue;
        }
        ProjectFilesystem projectFilesystem = ProjectFilesystem.createNewOrThrowHumanReadableException(root);
        // A cache which caches hashes of absolute paths which my be accessed by certain
        // rules (e.g. /usr/bin/gcc), and only serves to prevent rehashing the same file
        // multiple times in a single run.
        allCaches.add(DefaultFileHashCache.createDefaultFileHashCache(projectFilesystem));
    }
    return allCaches.build();
}
Also used : ArchiveMemberPath(com.facebook.buck.io.ArchiveMemberPath) Path(java.nio.file.Path) ImmutableList(com.google.common.collect.ImmutableList) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem)

Aggregations

ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)654 Test (org.junit.Test)542 FakeProjectFilesystem (com.facebook.buck.testutil.FakeProjectFilesystem)401 Path (java.nio.file.Path)324 BuildRuleResolver (com.facebook.buck.rules.BuildRuleResolver)207 DefaultTargetNodeToBuildRuleTransformer (com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer)204 BuildTarget (com.facebook.buck.model.BuildTarget)203 SourcePathRuleFinder (com.facebook.buck.rules.SourcePathRuleFinder)126 SourcePathResolver (com.facebook.buck.rules.SourcePathResolver)121 TargetGraph (com.facebook.buck.rules.TargetGraph)119 PathSourcePath (com.facebook.buck.rules.PathSourcePath)96 FakeSourcePath (com.facebook.buck.rules.FakeSourcePath)92 ProjectWorkspace (com.facebook.buck.testutil.integration.ProjectWorkspace)90 SourcePath (com.facebook.buck.rules.SourcePath)79 ExecutionContext (com.facebook.buck.step.ExecutionContext)67 AllExistingProjectFilesystem (com.facebook.buck.testutil.AllExistingProjectFilesystem)67 TestExecutionContext (com.facebook.buck.step.TestExecutionContext)63 BuildRule (com.facebook.buck.rules.BuildRule)56 RuleKey (com.facebook.buck.rules.RuleKey)43 ArchiveMemberPath (com.facebook.buck.io.ArchiveMemberPath)42