Search in sources :

Example 11 with ProjectFilesystem

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

the class FineGrainedJavaDependencySuggester method extractProvidedSymbolInfoFromSourceFile.

/**
   * Extracts the features from {@code src} and updates the collections accordingly.
   */
private void extractProvidedSymbolInfoFromSourceFile(SourcePath src, JavaFileParser javaFileParser, Multimap<String, String> providedSymbolToRequiredSymbols, Map<String, PathSourcePath> providedSymbolToSrc) {
    if (!(src instanceof PathSourcePath)) {
        return;
    }
    PathSourcePath path = (PathSourcePath) src;
    ProjectFilesystem filesystem = path.getFilesystem();
    Optional<String> contents = filesystem.readFileIfItExists(path.getRelativePath());
    if (!contents.isPresent()) {
        throw new RuntimeException(String.format("Could not read file '%s'", path.getRelativePath()));
    }
    JavaFileParser.JavaFileFeatures features = javaFileParser.extractFeaturesFromJavaCode(contents.get());
    // If there are multiple provided symbols, that is because there are inner classes. Choosing
    // the shortest name will effectively select the top-level type.
    String providedSymbol = Iterables.getFirst(features.providedSymbols, /* defaultValue */
    null);
    if (providedSymbol == null) {
        console.getStdErr().printf("%s cowardly refuses to provide any types.\n", path.getRelativePath());
        return;
    }
    providedSymbolToSrc.put(providedSymbol, path);
    providedSymbolToRequiredSymbols.putAll(providedSymbol, features.requiredSymbols);
    providedSymbolToRequiredSymbols.putAll(providedSymbol, features.exportedSymbols);
}
Also used : PathSourcePath(com.facebook.buck.rules.PathSourcePath) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) JavaFileParser(com.facebook.buck.jvm.java.JavaFileParser)

Example 12 with ProjectFilesystem

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

the class AuditRulesCommand method runWithoutHelp.

@Override
public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    ProjectFilesystem projectFilesystem = params.getCell().getFilesystem();
    try (ProjectBuildFileParser parser = params.getCell().createBuildFileParser(new ConstructorArgMarshaller(new DefaultTypeCoercerFactory(params.getObjectMapper())), params.getConsole(), params.getBuckEventBus(), /* ignoreBuckAutodepsFiles */
    false)) {
        PrintStream out = params.getConsole().getStdOut();
        for (String pathToBuildFile : getArguments()) {
            if (!json) {
                // Print a comment with the path to the build file.
                out.printf("# %s\n\n", pathToBuildFile);
            }
            // Resolve the path specified by the user.
            Path path = Paths.get(pathToBuildFile);
            if (!path.isAbsolute()) {
                Path root = projectFilesystem.getRootPath();
                path = root.resolve(path);
            }
            // Parse the rules from the build file.
            List<Map<String, Object>> rawRules;
            try {
                rawRules = parser.getAll(path);
            } catch (BuildFileParseException e) {
                throw new HumanReadableException(e);
            }
            // Format and print the rules from the raw data, filtered by type.
            final ImmutableSet<String> types = getTypes();
            Predicate<String> includeType = type -> types.isEmpty() || types.contains(type);
            printRulesToStdout(params, rawRules, includeType);
        }
    } catch (BuildFileParseException e) {
        throw new HumanReadableException("Unable to create parser");
    }
    return 0;
}
Also used : Path(java.nio.file.Path) SortedSet(java.util.SortedSet) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) HashMap(java.util.HashMap) MoreStrings(com.facebook.buck.util.MoreStrings) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Lists(com.google.common.collect.Lists) Argument(org.kohsuke.args4j.Argument) ProjectBuildFileParser(com.facebook.buck.json.ProjectBuildFileParser) FluentIterable(com.google.common.collect.FluentIterable) Map(java.util.Map) DefaultTypeCoercerFactory(com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory) Escaper(com.facebook.buck.util.Escaper) BuckPyFunction(com.facebook.buck.rules.BuckPyFunction) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) Path(java.nio.file.Path) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) PrintStream(java.io.PrintStream) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Option(org.kohsuke.args4j.Option) HumanReadableException(com.facebook.buck.util.HumanReadableException) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) ConstructorArgMarshaller(com.facebook.buck.rules.ConstructorArgMarshaller) List(java.util.List) JsonFactory(com.fasterxml.jackson.core.JsonFactory) Predicate(com.google.common.base.Predicate) Paths(java.nio.file.Paths) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) PrintStream(java.io.PrintStream) ProjectBuildFileParser(com.facebook.buck.json.ProjectBuildFileParser) DefaultTypeCoercerFactory(com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) ConstructorArgMarshaller(com.facebook.buck.rules.ConstructorArgMarshaller) HumanReadableException(com.facebook.buck.util.HumanReadableException) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) HashMap(java.util.HashMap) Map(java.util.Map)

Example 13 with ProjectFilesystem

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

the class BuckQueryEnvironment method getBuildFiles.

@Override
public ImmutableSet<QueryTarget> getBuildFiles(Set<QueryTarget> targets) throws QueryException {
    final ProjectFilesystem cellFilesystem = rootCell.getFilesystem();
    final Path rootPath = cellFilesystem.getRootPath();
    Preconditions.checkState(rootPath.isAbsolute());
    ImmutableSet.Builder<QueryTarget> builder = ImmutableSet.builder();
    for (QueryTarget target : targets) {
        Preconditions.checkState(target instanceof QueryBuildTarget);
        BuildTarget buildTarget = ((QueryBuildTarget) target).getBuildTarget();
        Cell cell = rootCell.getCell(buildTarget);
        if (!buildFileTrees.containsKey(cell)) {
            LOG.info("Creating a new filesystem-backed build file tree for %s", cell.getRoot());
            buildFileTrees.put(cell, new FilesystemBackedBuildFileTree(cell.getFilesystem(), cell.getBuildFileName()));
        }
        BuildFileTree buildFileTree = Preconditions.checkNotNull(buildFileTrees.get(cell));
        Optional<Path> path = buildFileTree.getBasePathOfAncestorTarget(buildTarget.getBasePath());
        Preconditions.checkState(path.isPresent());
        Path buildFilePath = MorePaths.relativize(rootPath, cell.getFilesystem().resolve(path.get()).resolve(cell.getBuildFileName()));
        Preconditions.checkState(cellFilesystem.exists(buildFilePath));
        builder.add(QueryFileTarget.of(buildFilePath));
    }
    return builder.build();
}
Also used : Path(java.nio.file.Path) QueryTarget(com.facebook.buck.query.QueryTarget) FilesystemBackedBuildFileTree(com.facebook.buck.model.FilesystemBackedBuildFileTree) ImmutableSet(com.google.common.collect.ImmutableSet) QueryBuildTarget(com.facebook.buck.query.QueryBuildTarget) BuildTarget(com.facebook.buck.model.BuildTarget) BuildFileTree(com.facebook.buck.model.BuildFileTree) FilesystemBackedBuildFileTree(com.facebook.buck.model.FilesystemBackedBuildFileTree) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Cell(com.facebook.buck.rules.Cell) QueryBuildTarget(com.facebook.buck.query.QueryBuildTarget)

Example 14 with ProjectFilesystem

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

the class ArtifactCaches method createHttpArtifactCache.

private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
    // Setup the default client to use.
    OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
    storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
    int timeoutSeconds = cacheDescription.getTimeoutSeconds();
    setTimeouts(storeClientBuilder, timeoutSeconds);
    storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
    (int) config.getThreadPoolSize(), /* keepAliveDurationMs */
    config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
    // The artifact cache effectively only connects to a single host at a time. We should allow as
    // many concurrent connections to that host as we allow threads.
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
    storeClientBuilder.dispatcher(dispatcher);
    final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
    final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
    // If write headers are specified, add them to every default client request.
    if (!writeHeaders.isEmpty()) {
        storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
    }
    OkHttpClient storeClient = storeClientBuilder.build();
    // For fetches, use a client with a read timeout.
    OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
    setTimeouts(fetchClientBuilder, timeoutSeconds);
    // If read headers are specified, add them to every read client request.
    if (!readHeaders.isEmpty()) {
        fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
    }
    fetchClientBuilder.networkInterceptors().add((chain -> {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
    }));
    OkHttpClient fetchClient = fetchClientBuilder.build();
    HttpService fetchService;
    HttpService storeService;
    switch(config.getLoadBalancingType()) {
        case CLIENT_SLB:
            HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
            fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
            storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
            break;
        case SINGLE_SERVER:
            URI url = cacheDescription.getUrl();
            fetchService = new SingleUriService(url, fetchClient);
            storeService = new SingleUriService(url, storeClient);
            break;
        default:
            throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
    }
    String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
    boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
    return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
Also used : ConnectionPool(okhttp3.ConnectionPool) BuckEventBus(com.facebook.buck.event.BuckEventBus) Okio(okio.Okio) Source(okio.Source) BytesReceivedEvent(com.facebook.buck.event.NetworkEvent.BytesReceivedEvent) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) Dispatcher(okhttp3.Dispatcher) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) CommonGroups(com.facebook.buck.randomizedtrial.CommonGroups) BuckConfig(com.facebook.buck.cli.BuckConfig) ImmutableList(com.google.common.collect.ImmutableList) DefaultClock(com.facebook.buck.timing.DefaultClock) Map(java.util.Map) ForwardingSource(okio.ForwardingSource) Response(okhttp3.Response) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer) URI(java.net.URI) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) Path(java.nio.file.Path) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) HttpService(com.facebook.buck.slb.HttpService) Logger(com.facebook.buck.log.Logger) Request(okhttp3.Request) Buffer(okio.Buffer) SingleUriService(com.facebook.buck.slb.SingleUriService) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CharMatcher(com.google.common.base.CharMatcher) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) TimeUnit(java.util.concurrent.TimeUnit) BufferedSource(okio.BufferedSource) OkHttpClient(okhttp3.OkHttpClient) Optional(java.util.Optional) ConnectionPool(okhttp3.ConnectionPool) AsyncCloseable(com.facebook.buck.util.AsyncCloseable) RandomizedTrial(com.facebook.buck.randomizedtrial.RandomizedTrial) DirCacheExperimentEvent(com.facebook.buck.event.DirCacheExperimentEvent) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) OkHttpClient(okhttp3.OkHttpClient) CommandThreadFactory(com.facebook.buck.log.CommandThreadFactory) Dispatcher(okhttp3.Dispatcher) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) URI(java.net.URI) Response(okhttp3.Response) RetryingHttpService(com.facebook.buck.slb.RetryingHttpService) HttpService(com.facebook.buck.slb.HttpService) DefaultClock(com.facebook.buck.timing.DefaultClock) LoadBalancedService(com.facebook.buck.slb.LoadBalancedService) SingleUriService(com.facebook.buck.slb.SingleUriService) HttpLoadBalancer(com.facebook.buck.slb.HttpLoadBalancer)

Example 15 with ProjectFilesystem

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

the class BuildCommand method processSuccessfulBuild.

private int processSuccessfulBuild(CommandRunnerParams params, ActionAndTargetGraphs graphs) throws IOException {
    if (showOutput || showFullOutput || showRuleKey) {
        showOutputs(params, graphs.actionGraph);
    }
    if (outputPathForSingleBuildTarget != null) {
        BuildTarget loneTarget = Iterables.getOnlyElement(graphs.getTargetGraphForLocalBuild().getBuildTargets());
        BuildRule rule = graphs.actionGraph.getResolver().getRule(loneTarget);
        if (!rule.outputFileCanBeCopied()) {
            params.getConsole().printErrorText(String.format("%s does not have an output that is compatible with `buck build --out`", loneTarget));
            return 1;
        } else {
            SourcePath output = Preconditions.checkNotNull(rule.getSourcePathToOutput(), "%s specified a build target that does not have an output file: %s", OUT_LONG_ARG, loneTarget);
            ProjectFilesystem projectFilesystem = rule.getProjectFilesystem();
            SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(graphs.actionGraph.getResolver()));
            projectFilesystem.copyFile(pathResolver.getAbsolutePath(output), outputPathForSingleBuildTarget);
        }
    }
    return 0;
}
Also used : SourcePath(com.facebook.buck.rules.SourcePath) BuildTarget(com.facebook.buck.model.BuildTarget) BuildRule(com.facebook.buck.rules.BuildRule) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder)

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