<commit_before>/**
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.gms.oss.licenses.plugin

import groovy.json.JsonBuilder
import groovy.json.JsonException
import groovy.json.JsonSlurper
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.ResolveException
import org.gradle.api.artifacts.ResolvedArtifact
import org.gradle.api.artifacts.ResolvedDependency
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.component.AmbiguousVariantSelectionException
import org.slf4j.LoggerFactory

/**
 * This task does the following:
 * First it finds all dependencies that meet all the requirements below:
 * 1. Can be resolved.
 * 2. Not test compile.
 * Then it finds all the artifacts associated with the dependencies.
 * Finally it generates a json file that contains the information about these
 * artifacts.
 */
class DependencyTask extends DefaultTask {
    protected Set<String> artifactSet = []
    protected Set<ArtifactInfo> artifactInfos = []
    protected static final String LOCAL_LIBRARY_VERSION = "unspecified"
    private static final String TEST_PREFIX = "test"
    private static final String ANDROID_TEST_PREFIX = "androidTest"
    private static final Set<String> TEST_COMPILE = ["testCompile",
                                                     "androidTestCompile"]

    private static final Set<String> PACKAGED_DEPENDENCIES_PREFIXES = ["compile",
                                                                       "implementation",
                                                                       "api"]

    private static final logger = LoggerFactory.getLogger(DependencyTask.class)

    @Input
    public ConfigurationContainer configurations

    @OutputDirectory
    public File outputDir

    @OutputFile
    public File outputFile

    @TaskAction
    void action() {
        initOutput()
        updateDependencyArtifacts()

        if (outputFile.exists() && checkArtifactSet(outputFile)) {
            return
        }

        outputFile.newWriter()
        outputFile.write(new JsonBuilder(artifactInfos).toPrettyString())
    }

    /**
     * Checks if current artifact set is the same as the artifact set in the
     * json file
     * @param file
     * @return true if artifactSet is the same as the json file,
     * false otherwise
     */
    protected boolean checkArtifactSet(File file) {
        try {
            def previousArtifacts = new JsonSlurper().parse(file)
            for (entry in previousArtifacts) {
                String key = "${entry.fileLocation}"
                if (artifactSet.contains(key)) {
                    artifactSet.remove(key)
                } else {
                    return false
                }
            }
            return artifactSet.isEmpty()
        } catch (JsonException exception) {
            return false
        }
    }

    protected void updateDependencyArtifacts() {
        for (Configuration configuration : configurations) {
            Set<ResolvedArtifact> artifacts = getResolvedArtifacts(
                    configuration)
            if (artifacts == null) {
                continue
            }

            addArtifacts(artifacts)
        }
    }

    protected addArtifacts(Set<ResolvedArtifact> artifacts) {
        for (ResolvedArtifact artifact : artifacts) {
            String group = artifact.moduleVersion.id.group
            String artifact_key = artifact.file.getAbsolutePath()

            if (artifactSet.contains(artifact_key)) {
                continue
            }

            artifactSet.add(artifact_key)
            artifactInfos.add(new ArtifactInfo(group, artifact.name,
                    artifact.file.getAbsolutePath(),
                    artifact.moduleVersion.id.version))
        }<commit_msg>Avoid modifying class state during check operation.<commit_after>/**
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.gms.oss.licenses.plugin

import groovy.json.JsonBuilder
import groovy.json.JsonException
import groovy.json.JsonSlurper
import org.gradle.api.DefaultTask
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.artifacts.ResolveException
import org.gradle.api.artifacts.ResolvedArtifact
import org.gradle.api.artifacts.ResolvedDependency
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.internal.component.AmbiguousVariantSelectionException
import org.slf4j.LoggerFactory

/**
 * This task does the following:
 * First it finds all dependencies that meet all the requirements below:
 * 1. Can be resolved.
 * 2. Not test compile.
 * Then it finds all the artifacts associated with the dependencies.
 * Finally it generates a json file that contains the information about these
 * artifacts.
 */
class DependencyTask extends DefaultTask {
    protected Set<String> artifactSet = []
    protected Set<ArtifactInfo> artifactInfos = []
    protected static final String LOCAL_LIBRARY_VERSION = "unspecified"
    private static final String TEST_PREFIX = "test"
    private static final String ANDROID_TEST_PREFIX = "androidTest"
    private static final Set<String> TEST_COMPILE = ["testCompile",
                                                     "androidTestCompile"]

    private static final Set<String> PACKAGED_DEPENDENCIES_PREFIXES = ["compile",
                                                                       "implementation",
                                                                       "api"]

    private static final logger = LoggerFactory.getLogger(DependencyTask.class)

    @Input
    public ConfigurationContainer configurations

    @OutputDirectory
    public File outputDir

    @OutputFile
    public File outputFile

    @TaskAction
    void action() {
        initOutput()
        updateDependencyArtifacts()

        if (outputFile.exists() && checkArtifactSet(outputFile)) {
            return
        }

        outputFile.newWriter()
        outputFile.write(new JsonBuilder(artifactInfos).toPrettyString())
    }

    /**
     * Checks if current artifact set is the same as the artifact set in the
     * json file
     * @param file
     * @return true if artifactSet is the same as the json file,
     * false otherwise
     */
    protected boolean checkArtifactSet(File file) {
        Set<String> artifacts = new HashSet<>(artifactSet)
        try {
            def previousArtifacts = new JsonSlurper().parse(file)
            for (entry in previousArtifacts) {
                String key = "${entry.fileLocation}"
                if (artifacts.contains(key)) {
                    artifacts.remove(key)
                } else {
                    return false
                }
            }
            return artifacts.isEmpty()
        } catch (JsonException exception) {
            return false
        }
    }

    protected void updateDependencyArtifacts() {
        for (Configuration configuration : configurations) {
            Set<ResolvedArtifact> artifacts = getResolvedArtifacts(
                    configuration)
            if (artifacts == null) {
                continue
            }

            addArtifacts(artifacts)
        }
    }

    protected addArtifacts(Set<ResolvedArtifact> artifacts) {
        for (ResolvedArtifact artifact : artifacts) {
            String group = artifact.moduleVersion.id.group
            String artifact_key = artifact.file.getAbsolutePath()

            if (artifactSet.contains(artifact_key)) {
                continue
            }

            artifactSet.add(artifact_key)
            artifactInfos.add(new ArtifactInfo(group, artifact.name,
                    artifact.file.getAbsolutePath(),
                    artifact.moduleVersion.id.version))
        }
{'fraction_non_alphanumeric': 0.07159127888057273, 'fraction_numerical': 0.0023863759626857575, 'mean_word_length': 2.351508542348237, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1924564', 'n_tokens_mistral': 2323, 'n_tokens_neox': 2165, 'n_words': 674}