Skip to content

Commit

Permalink
fix disable analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
baev committed Jun 13, 2023
1 parent 1b3e98c commit d6d15d9
Show file tree
Hide file tree
Showing 9 changed files with 148 additions and 32 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
run: echo "::set-output name=version::${GITHUB_REF:10}"
- uses: actions/checkout@v3.5.3

- name: "Set up JDK 1.8"
- name: "Set up JDK"
uses: actions/setup-java@v3
with:
distribution: 'zulu'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.qameta.allure.context.JacksonContext;
import io.qameta.allure.context.MarkdownContext;
import io.qameta.allure.context.RandomUidContext;
import io.qameta.allure.context.ReportInfoContext;
import io.qameta.allure.core.AttachmentsPlugin;
import io.qameta.allure.core.Configuration;
import io.qameta.allure.core.MarkdownDescriptionsPlugin;
Expand Down Expand Up @@ -50,11 +51,17 @@
import io.qameta.allure.summary.SummaryPlugin;
import io.qameta.allure.tags.TagsPlugin;
import io.qameta.allure.timeline.TimelinePlugin;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
* Builder for {@link Configuration}.
Expand All @@ -69,12 +76,20 @@
})
public class ConfigurationBuilder {

private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationBuilder.class);

private static final String ALLURE_VERSION_TXT_PATH = "/allure-version.txt";

private final List<Extension> extensions = new ArrayList<>();

private final List<Plugin> plugins = new ArrayList<>();

public ConfigurationBuilder useDefault() {
final String allureVersion = getVersionFromFile()
.orElse(getVersionFromManifest().orElse("Undefined"));

fromExtensions(Arrays.asList(
new ReportInfoContext(allureVersion),
new JacksonContext(),
new MarkdownContext(),
new FreemarkerContext(),
Expand Down Expand Up @@ -131,4 +146,22 @@ public Configuration build() {
Collections.unmodifiableList(plugins)
);
}

private static Optional<String> getVersionFromFile() {
try {
return Optional.of(IOUtils.resourceToString(ALLURE_VERSION_TXT_PATH, StandardCharsets.UTF_8))
.map(String::trim)
.filter(v -> !v.isEmpty())
.filter(v -> !"#project.version#".equals(v));
} catch (IOException e) {
LOGGER.debug("Could not read {} resource", ALLURE_VERSION_TXT_PATH, e);
return Optional.empty();
}
}

private static Optional<String> getVersionFromManifest() {
return Optional.of(ConfigurationBuilder.class)
.map(Class::getPackage)
.map(Package::getImplementationVersion);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import io.qameta.allure.Constants;
import io.qameta.allure.PluginConfiguration;
import io.qameta.allure.ReportGenerationException;
import io.qameta.allure.ReportInfo;
import io.qameta.allure.context.FreemarkerContext;
import io.qameta.allure.context.ReportInfoContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -36,6 +38,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -70,6 +73,7 @@ protected void writePluginsStatic(final Configuration configuration,
protected void writeIndexHtml(final Configuration configuration,
final Path outputDirectory) throws IOException {
final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
final ReportInfo reportInfo = configuration.requireContext(ReportInfoContext.class).getValue();
final Path indexHtml = outputDirectory.resolve("index.html");
final List<PluginConfiguration> pluginConfigurations = configuration.getPlugins().stream()
.map(Plugin::getConfig)
Expand All @@ -79,9 +83,15 @@ protected void writeIndexHtml(final Configuration configuration,
final Template template = context.getValue().getTemplate("index.html.ftl");
final Map<String, Object> dataModel = new HashMap<>();
dataModel.put(Constants.PLUGINS_DIR, pluginConfigurations);
final Boolean noAnalytics = Optional.ofNullable(System.getenv(Constants.NO_ANALYTICS))
.map(Boolean::parseBoolean)
.orElse(false);
dataModel.put(Constants.NO_ANALYTICS, noAnalytics);
dataModel.put("reportUuid", reportInfo.getReportUuid());
dataModel.put("allureVersion", reportInfo.getAllureVersion());
template.process(dataModel, writer);
} catch (TemplateException e) {
LOGGER.error("Could't write index file", e);
LOGGER.error("Couldn't write index file", e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
@Accessors(chain = true)
public class GaParameters {

private String reportUuid;

private String allureVersion;

private String executorType;
Expand Down
47 changes: 17 additions & 30 deletions allure-generator/src/main/java/io/qameta/allure/ga/GaPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@

import com.fasterxml.jackson.databind.json.JsonMapper;
import io.qameta.allure.Aggregator;
import io.qameta.allure.ReportInfo;
import io.qameta.allure.context.ReportInfoContext;
import io.qameta.allure.core.Configuration;
import io.qameta.allure.core.LaunchResults;
import io.qameta.allure.entity.ExecutorInfo;
import io.qameta.allure.entity.Label;
import io.qameta.allure.entity.LabelName;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
Expand All @@ -50,6 +51,7 @@
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import static io.qameta.allure.Constants.NO_ANALYTICS;
import static io.qameta.allure.executor.ExecutorPlugin.EXECUTORS_BLOCK_NAME;

/**
Expand All @@ -62,30 +64,29 @@ public class GaPlugin implements Aggregator {

private static final String LOCAL = "local";

private static final String UNDEFINED = "Undefined";

private static final String GA_DISABLE = "ALLURE_NO_ANALYTICS";

private static final String GA_ENDPOINT_FORMAT
= "https://www.google-analytics.com/mp/collect?measurement_id=%s&api_secret=%s";

private static final String MEASUREMENT_ID = "G-FVWC4GKEYS";
private static final String GA_SECRET = "rboZz0HySdmCVIvtydmSTQ";

private static final String ALLURE_VERSION_TXT_PATH = "/allure-version.txt";
private static final String GA_EVENT_NAME = "report_generated";

@Override
public void aggregate(final Configuration configuration,
final List<LaunchResults> launchesResults,
final Path outputDirectory) {
if (Objects.nonNull(System.getenv(GA_DISABLE))) {
if (Objects.nonNull(System.getenv(NO_ANALYTICS))) {
LOGGER.debug("analytics is disabled");
return;
}
final ReportInfoContext reportInfoContext = configuration.requireContext(ReportInfoContext.class);
final ReportInfo reportInfo = reportInfoContext.getValue();

LOGGER.debug("send analytics");
final GaParameters parameters = new GaParameters()
.setAllureVersion(getAllureVersion())
.setReportUuid(reportInfo.getReportUuid())
.setAllureVersion(reportInfo.getAllureVersion())
.setExecutorType(getExecutorType(launchesResults))
.setResultsCount(getTestResultsCount(launchesResults))
.setResultsFormat(getLabelValuesAsString(launchesResults, LabelName.RESULT_FORMAT))
Expand Down Expand Up @@ -138,35 +139,21 @@ private static String getClientId(final List<LaunchResults> launchesResults) {
.map(Optional::get)
.findFirst()
.map(ExecutorInfo::getBuildUrl)
.map(URI::create)
.map(URI::getHost);
.flatMap(GaPlugin::getHostSafe);

return executorHostName.map(DigestUtils::sha256Hex)
.orElse(getLocalHostName().map(DigestUtils::sha256Hex)
.orElse(UUID.randomUUID().toString()));
}

private static String getAllureVersion() {
return getVersionFromFile()
.orElse(getVersionFromManifest().orElse(UNDEFINED));
}

private static Optional<String> getVersionFromFile() {
private static Optional<String> getHostSafe(final String url) {
try {
return Optional.of(IOUtils.resourceToString(ALLURE_VERSION_TXT_PATH, StandardCharsets.UTF_8))
.map(String::trim)
.filter(v -> !v.isEmpty())
.filter(v -> !"#project.version#".equals(v));
} catch (IOException e) {
LOGGER.debug("Could not read {} resource", ALLURE_VERSION_TXT_PATH, e);
return Optional.empty();
return Optional.of(URI.create(url))
.map(URI::getHost);
} catch (Exception e) {
LOGGER.debug("invalid build url", e);
}
}

private static Optional<String> getVersionFromManifest() {
return Optional.of(GaPlugin.class)
.map(Class::getPackage)
.map(Package::getImplementationVersion);
return Optional.empty();
}

private static String getExecutorType(final List<LaunchResults> launchesResults) {
Expand Down Expand Up @@ -199,7 +186,7 @@ private static String getLabelValuesAsString(final List<LaunchResults> launchesR
.sorted()
.collect(Collectors.joining(" "))
.toLowerCase();
return values.isEmpty() ? UNDEFINED : values;
return values.isEmpty() ? "Undefined" : values;
}

private static Optional<String> getLocalHostName() {
Expand Down
4 changes: 4 additions & 0 deletions allure-generator/src/main/resources/tpl/index.html.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@
<script src="plugins/${plugin.id}/${jsFile}"></script>
</#list>
</#list>
<#if ALLURE_NO_ANALYTICS == false>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-FVWC4GKEYS"></script>
</#if>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-FVWC4GKEYS');
gtag('allureVersion', '${allureVersion}')
gtag('reportUuid', '${reportUuid}')
</script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ public final class Constants {
*/
public static final String HISTORY_DIR = "history";

/**
* The name of environment variable that disables analytics.
*/
public static final String NO_ANALYTICS = "ALLURE_NO_ANALYTICS";

private Constants() {
throw new IllegalStateException("Do not instance");
}
Expand Down
35 changes: 35 additions & 0 deletions allure-plugin-api/src/main/java/io/qameta/allure/ReportInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2016-2023 Qameta Software OÜ
*
* 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
*
* http://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 io.qameta.allure;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
* @author charlie (Dmitry Baev).
*/
@Data
@Accessors(chain = true)
public class ReportInfo implements Serializable {

private static final long serialVersionUID = 1L;

private String allureVersion;
private String reportUuid;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2016-2023 Qameta Software OÜ
*
* 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
*
* http://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 io.qameta.allure.context;

import io.qameta.allure.Context;
import io.qameta.allure.ReportInfo;

import java.util.UUID;

/**
* @author charlie (Dmitry Baev).
*/
public class ReportInfoContext implements Context<ReportInfo> {

private final ReportInfo reportInfo;

public ReportInfoContext(final String allureVersion) {
this.reportInfo = new ReportInfo()
.setAllureVersion(allureVersion)
.setReportUuid(UUID.randomUUID().toString());
}

@Override
public ReportInfo getValue() {
return reportInfo;
}
}

0 comments on commit d6d15d9

Please sign in to comment.