diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..e0d6f867 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,20 @@ + +## Description + + + +### Checklist +- [ ] New tests and/or benchmarks are included. +- [ ] Documentation is changed or added. +- [ ] Changelog is updated accordingly. +- [ ] I have signed the MongoDB Contributor License Agreement (https://www.mongodb.com/legal/contributor-agreement). + +## Open Questions + \ No newline at end of file diff --git a/.github/workflows/draft-release.yaml b/.github/workflows/draft-release.yaml new file mode 100644 index 00000000..bffb2142 --- /dev/null +++ b/.github/workflows/draft-release.yaml @@ -0,0 +1,121 @@ +name: Draft release + +on: + workflow_dispatch: + inputs: + versionBump: + description: 'Version bump' + type: choice + required: true + default: 'patch' + options: + - patch + - minor + - major + - exact-version + + exactVersion: + description: 'Exact version: (Only effective selecting "exact-version" as version bump)' + required: false + +permissions: + contents: write + +jobs: + prepare-release: + name: "Prepare Release" + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Determine Next Version + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -e + + VERSION_BUMP=${{ github.event.inputs.versionBump }} + + if [[ "$VERSION_BUMP" == "major" || "$VERSION_BUMP" == "minor" || "$VERSION_BUMP" == "patch" ]]; then + ./gradlew --quiet --console=plain versionBump -Pmode="$VERSION_BUMP" + else + ./gradlew --quiet --console=plain versionBump -PexactVersion="${{ github.event.inputs.exactVersion }}" + fi + + NEXT_VERSION=$(./gradlew --quiet --console=plain getVersion) + echo "RELEASE_TAG=v${NEXT_VERSION}" >> "$GITHUB_ENV" + + - name: Validate release tag + shell: bash + run: | + if [ -z "${RELEASE_TAG}" ]; then + echo "RELEASE_TAG is not set or is empty" + exit 1 + fi + + if git rev-parse "$RELEASE_TAG" >/dev/null 2>&1; then + echo "Error: Tag $RELEASE_TAG already existing" + echo "If you are trying to re-create a draft release with this version, please delete the release and the tag first." + echo "If this version has already been release consider using a different one." + exit 1 + fi + + - name: Run All Tests + run: | + ./gradlew "unitTest" ":packages:jetbrains-plugin:test" + + - name: Patch Plugin XML + run: | + ./gradlew ":packages:jetbrains-plugin:patchPluginXml" + + - name: Verify Plugin + run: | + ./gradlew ":packages:jetbrains-plugin:verifyPlugin" + + - name: Patch Changelog + run: | + ./gradlew ":packages:jetbrains-plugin:patchChangelog" + + - name: Sign and Publish Plugin in Beta + env: + JB_PUBLISH_CHANNEL: "beta" + run: | + ./gradlew ":packages:jetbrains-plugin:publishPlugin" + + - name: Create Draft Release + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.SVC_DEVTOOLSBOT_TOKEN }} + run: | + set -e + echo Creating draft release for: "${RELEASE_TAG}" + + git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" + git config --local user.name "github-actions[bot]" + + git add . + git commit --no-verify -m "Release ${RELEASE_TAG}" + git tag ${RELEASE_TAG} + git push origin ${RELEASE_TAG} + + GIT_REF=$(git rev-parse ${RELEASE_TAG}) + ls packages/jetbrains-plugin/build/distributions/jetbrains-plugin.zip + + CHANGELOG=$(./gradlew --quiet --console=plain :packages:jetbrains-plugin:getChangelog) + + gh release create "${RELEASE_TAG}" \ + --title "${RELEASE_TAG}" \ + --notes "${CHANGELOG}" \ + --target "${GIT_REF}" \ + --draft \ + packages/jetbrains-plugin/build/distributions/jetbrains-plugin.zip + diff --git a/.github/workflows/publish-release.yaml b/.github/workflows/publish-release.yaml new file mode 100644 index 00000000..25107d9f --- /dev/null +++ b/.github/workflows/publish-release.yaml @@ -0,0 +1,42 @@ +name: Publish Release + +on: + release: + types: [published] + +jobs: + prepare-release: + name: "Prepare Release" + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.ref_name }} + fetch-depth: 0 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + + - uses: robinraju/release-downloader@v1.10 + with: + tag: ${{ github.ref_name }} + fileName: 'jetbrains-plugin.zip' + out-file-path: 'packages/jetbrains-plugin/build/distributions/' + - name: Publish Plugin In General Availability + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.SVC_DEVTOOLSBOT_TOKEN }} + JB_PUBLISH_CHANNEL: "ga" + run: | + set -e + + ./gradlew ":packages:jetbrains-plugin:publishPlugin" $(./gradlew ":packages:jetbrains-plugin:publishPlugin" --dry-run | awk '/^:/ { print "-x" $1 }' | sed '$ d') + + git checkout main + git merge ${{ github.ref_name }} + git push origin main + diff --git a/.github/workflows/quality-check.yaml b/.github/workflows/quality-check.yaml new file mode 100644 index 00000000..fcbb6a41 --- /dev/null +++ b/.github/workflows/quality-check.yaml @@ -0,0 +1,240 @@ +name: Quality Check +on: + push: + branches: + - main + pull_request: + branches: + - main + +permissions: + contents: write + pull-requests: write + checks: write + +jobs: + changelog-check: + name: 'Changelog Check' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: remove label not matching title - fix + if: | + startsWith(github.event.pull_request.title, 'fix:') || + startsWith(github.event.pull_request.title, 'fix(') + uses: actions-ecosystem/action-remove-labels@v1 + with: + labels: feat + + - name: remove label not matching title - feat + if: | + startsWith(github.event.pull_request.title, 'feat:') || + startsWith(github.event.pull_request.title, 'feat(') + uses: actions-ecosystem/action-remove-labels@v1 + with: + labels: fix + + - name: add label based on title - fix + if: | + startsWith(github.event.pull_request.title, 'fix:') || + startsWith(github.event.pull_request.title, 'fix(') + uses: actions-ecosystem/action-add-labels@v1 + with: + labels: fix + + - name: add label based on title - feat + if: | + startsWith(github.event.pull_request.title, 'feat:') || + startsWith(github.event.pull_request.title, 'feat(') + uses: actions-ecosystem/action-add-labels@v1 + with: + labels: feature + + - name: add label based on title - chore + if: | + startsWith(github.event.pull_request.title, 'chore:') || + startsWith(github.event.pull_request.title, 'chore(') + uses: actions-ecosystem/action-add-labels@v1 + with: + labels: no release notes + - name: Verify Changed files + uses: tj-actions/verify-changed-files@v20 + id: verify-changelog-files + with: + files: | + CHANGELOG.md + - uses: mheap/github-action-required-labels@v1 + if: steps.verify-changed-files.outputs.files_changed == 'false' + with: + mode: minimum + count: 1 + labels: "no release notes" + catalog-check: + name: 'Catalog Updates Check' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Run Dependency Updates + run: | + ./gradlew --quiet --console=plain dependencyUpdates + + style-check: + name: 'Style Check' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Run Linter + run: | + ./gradlew --quiet --console=plain spotlessApply + + unit-tests: + name: 'Unit Tests' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Run Test Suite + run: | + ./gradlew --quiet --console=plain "clean" "cleanTest" "unitTest" + - name: Publish Test Report + uses: mikepenz/action-junit-report@v4 + if: success() || failure() # always run even if the previous step fails + with: + report_paths: '**/build/test-results/test/TEST-*.xml' + - name: Generate Coverage Report + run: | + ./gradlew --quiet --console=plain "jacocoTestReport" + - uses: actions/upload-artifact@v4 + name: Upload Unit Test Coverage + with: + name: unit-test-coverage + path: "**/build/reports/jacoco/test/jacocoTestReport.xml" + + functional-tests: + name: 'Functional & UI Tests' + runs-on: ubuntu-latest + needs: + - catalog-check + - style-check + - unit-tests + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Functional Tests + run: | + ./gradlew --quiet --console=plain "clean" ":packages:jetbrains-plugin:cleanTest" ":packages:jetbrains-plugin:test" + - name: Publish Test Report + uses: mikepenz/action-junit-report@v4 + if: success() || failure() # always run even if the previous step fails + with: + report_paths: '**/build/test-results/test/TEST-*.xml' + - name: Generate Coverage Report + run: | + ./gradlew --quiet --console=plain "jacocoTestReport" + - uses: actions/upload-artifact@v4 + name: Upload Functional Test Coverage + with: + name: functional-test-coverage + path: "**/build/reports/jacoco/test/jacocoTestReport.xml" + + test-coverage: + name: 'Test Coverage' + runs-on: ubuntu-latest + needs: + - unit-tests + - functional-tests + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - uses: actions/download-artifact@v4 + with: + merge-multiple: true + - uses: madrapps/jacoco-report@v1.6.1 + with: + paths: "**/build/reports/jacoco/test/jacocoTestReport.xml" + token: ${{ secrets.GITHUB_TOKEN }} + min-coverage-overall: 70 + min-coverage-changed-files: 85 + title: "Coverage Report" + update-comment: true + continue-on-error: true + pass-emoji: "✅" + fail-emoji: "🚫" + debug-mode: true + + fitness-check: + name: "Fitness Check" + runs-on: ubuntu-latest + needs: + - unit-tests + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Performance Tests + run: | + ./gradlew --quiet --console=plain ":packages:jetbrains-plugin:jmh" + - name: JMH Benchmark Action + uses: kitlangton/jmh-benchmark-action@main + with: + jmh-output-path: build/reports/jmh/results.json + github-token: ${{ secrets.GITHUB_TOKEN }} + fail-on-regression: true + failure-threshold: -5 + + verify-plugin: + name: "Verify Plugin" + runs-on: ubuntu-latest + needs: + - fitness-check + - test-coverage + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup JDK + uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '17' + cache: 'gradle' + - name: Verify Plugin + run: | + ./gradlew ":packages:jetbrains-plugin:verifyPlugin" diff --git a/.gitignore b/.gitignore index 524f0963..015d78e7 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,8 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* replay_pid* + +/.gradle +/build +/.idea +/**/build \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..7e105f53 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +MongoDB plugin for IntelliJ IDEA. + +## [Unreleased] + +### Added + +### Changed + +### Deprecated + +### Removed + +### Fixed + +### Security \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..1a6c2c87 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at compass@mongodb.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..b422787d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,80 @@ +# Contributing +## Getting Started + +You'll need at least the JDK 17 to work locally on the plugin. While the plugin should +work on any JDK distribution, it is recommended to download the latest JDK version from +[Adoptium](https://adoptium.net/). + +After installing the JDK, and ensuring it is accessible on the system, run the following +Gradle task, that will set up the required git hooks for this project: + +```sh +./gradlew gitHooks +``` + +Also, ensure unit tests are working by running the following command: + +```sh +./gradlew unitTest +``` + +It will take a few moments, and you are ready to go. + +## Submitting Changes + +MongoDB welcomes community contributions! If you’re interested in making a contribution to MongoDB's plugin for IntelliJ, +please follow the steps below before you start writing any code: + +- Sign the contributor's agreement. This will allow us to review and accept contributions. +- Fork the repository on GitHub. +- Create a branch with a name that briefly describes your feature. +- Implement your feature or bug fix. +- Add new cases to cover the new functionality. +- Add comments around your new code that explain what's happening. +- Add the changes to the [Changelog](CHANGELOG.md) +- Commit and push your changes to your branch and submit a pull request. + +## Submitting Bugs + +You can report new bugs by creating a new issue either in [JIRA](https://jira.mongodb.org/projects/INTELLIJ/issues/) or +[GitHub](https://github.com/mongodb-js/intellij/issues). Please include as much information as possible about your environment +and include any relevant logs. + +## Starting the plugin locally + +Starting the plugin locally requires a working local environment, so before running the +plugin, please revisit the `Getting Started` section. + +Once the environment works, run the following Gradle task to start an IntelliJ instance +with the plugin: + +```sh +./gradlew :packages:jetbrains-plugin:runIde +``` + +## Managing third-party dependencies + +We try to avoid third-party dependencies as much as possible, and only use the MongoDB driver, +the JetBrains plugin ecosystem and the Kotlin standard library. However, sometimes, it can be +convenient to add a new third-party dependency to solve a really specific issue. In that case, to +add a new dependency: + +* Go to [the dependency catalogue](https://github.com/mongodb-js/intellij/blob/main/gradle/libs.versions.toml) +* Add the version of the dependency to the `[versions]` section. +* Add the dependency to the `[dependencies]` section. +* Add the dependency reference to the specific package that will use the dependency. + +## Releasing + +We don't have an automatic cadence of releases. We plan new releases, implement the +features and then release when we are done. To release a new plugin version, is as follows: + +* Go to [GitHub Actions](https://github.com/mongodb-js/intellij/actions) and run the `Release Draft` workflow. + * Choose the type of release that you want to publish, it can be either patch, minor and major. Following semver. +* Wait until the workflow is done. + * It will validate that all the tests work and will publish a nightly version in the Marketplace. +* Go to the [GitHub Releases](https://github.com/mongodb-js/intellij/releases) page and you'll find a new draft release. +* Publish the release as a normal GitHub Release, by editing it and publishing. +* This will run a workflow _[you can check in GHA](https://github.com/mongodb-js/intellij/actions)_. + * When done it will update the main branch with the updated changelog and plugin version. + * And also will publish the package to the JetBrains Marketplace. \ No newline at end of file diff --git a/README.md b/README.md index 6bf7523a..05a1038f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,11 @@ -# intellij -MongoDB for IntelliJ +# mongodb-jetbrains-plugin +[![Quality Check](https://github.com/mongodb-js/intellij/actions/workflows/quality-check.yaml/badge.svg)](https://github.com/mongodb-js/intellij/actions/workflows/quality-check.yaml) +![GitHub Release](https://img.shields.io/github/v/release/mongodb-js/intellij?sort=semver&display_name=release&logo=github) +![GitHub Release](https://img.shields.io/github/v/release/mongodb-js/intellij?sort=semver&display_name=release&logo=jetbrains) + + +> [!CAUTION] +> :warning: This is a work in progress and not yet released. :warning: + + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..fbdb2379 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,150 @@ +import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask +import org.gradle.api.tasks.testing.logging.TestLogEvent +import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension + +group = "com.mongodb" +// This should be bumped when releasing a new version using the versionBump task: +// ./gradlew versionBump -Pmode={major,minor,patch} +version="0.0.1" + +plugins { + alias(libs.plugins.versions) + id("jacoco") +} + +buildscript { + repositories { + maven("https://plugins.gradle.org/m2/") + } + + dependencies { + classpath(libs.buildScript.plugin.kotlin) + classpath(libs.buildScript.plugin.versions) + classpath(libs.buildScript.plugin.spotless) + } +} + +subprojects { + apply(plugin = "java") + apply(plugin = "org.jetbrains.kotlin.jvm") + apply(plugin = "com.github.ben-manes.versions") + apply(plugin = "com.diffplug.spotless") + apply(plugin = "jacoco") + + repositories { + mavenCentral() + } + + dependencies { + val testImplementation by configurations + val compileOnly by configurations + + compileOnly(rootProject.libs.kotlin.stdlib) + testImplementation(rootProject.libs.testing.jupiter.engine) + testImplementation(rootProject.libs.testing.jupiter.vintage.engine) + testImplementation(rootProject.libs.testing.mockito.core) + testImplementation(rootProject.libs.testing.mockito.kotlin) + } + + tasks { + withType { + sourceCompatibility = "17" + targetCompatibility = "17" + } + + withType { + kotlinOptions.jvmTarget = "17" + } + + withType { + useJUnitPlatform() + + extensions.configure(JacocoTaskExtension::class) { + isJmx = true + includes = listOf("com.mongodb.*") + isIncludeNoLocationClasses = true + } + + jacoco { + toolVersion = "0.8.12" + isScanForTestClasses = true + } + + jvmArgs(listOf( + "--add-opens=java.base/java.lang=ALL-UNNAMED" + )) + } + + withType { + reports { + xml.required = true + csv.required = false + html.outputLocation = layout.buildDirectory.dir("reports/jacocoHtml") + } + } + } + + configure { + kotlin { + diktat() + .configFile(rootProject.layout.projectDirectory.file("gradle/diktat.yml").asFile.absolutePath) + } + } +} + +tasks.named("dependencyUpdates").configure { + checkForGradleUpdate = true + outputFormatter = "json" + outputDir = "build/reports" + reportfileName = "dependencyUpdates" +} + +tasks { + register("unitTest") { + dependsOn( + subprojects.filter { + it.project.name != "jetbrains-plugin" && + it.project.name != "packages" + }.map { + it.tasks["test"] + } + ) + } + + register("versionBump") { + group = "versioning" + description = "Increments the version of the plugin." + + fun generateVersion(): String { + val updateMode = rootProject.findProperty("mode") ?: "patch" + val (oldMajor, oldMinor, oldPatch) = rootProject.version.toString().split(".").map(String::toInt) + var (newMajor, newMinor, newPatch) = arrayOf(oldMajor, oldMinor, 0) + + when (updateMode) { + "major" -> newMajor = (oldMajor + 1).also { newMinor = 0 } + "minor" -> newMinor = (oldMinor + 1) + else -> newPatch = oldPatch + 1 + } + return "$newMajor.$newMinor.$newPatch" + } + doLast { + val newVersion = rootProject.findProperty("exactVersion") ?: generateVersion() + val oldContent = buildFile.readText() + val newContent = oldContent.replace("""="$version"""", """="$newVersion"""") + buildFile.writeText(newContent) + } + } + + register("gitHooks") { + exec { + rootProject.file(".git/hooks").mkdirs() + commandLine("cp", "./gradle/pre-commit", "./.git/hooks") + } + } + + register("getVersion") { + doLast { + println(rootProject.version) + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..017d50a6 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib +kotlin.stdlib.default.dependency=false +# TODO temporary workaround for Kotlin 1.8.20+ (https://jb.gg/intellij-platform-kotlin-oom) +kotlin.incremental.useClasspathSnapshot=false +# Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html +org.gradle.configuration-cache=false +# Disable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html +org.gradle.caching=false +# Enable Gradle task scheduling in parallel +org.gradle.parallel=true +# Disable daemon (not very useful most of the time) +org.gradle.daemon=false +# Use official code style for kotlin +kotlin.code.style=official +# Memory Optimisation +org.gradle.jvmargs=-Xmx2048M diff --git a/gradle/diktat.yml b/gradle/diktat.yml new file mode 100644 index 00000000..7eacfa7e --- /dev/null +++ b/gradle/diktat.yml @@ -0,0 +1,10 @@ +- name: MISSING_KDOC_CLASS_ELEMENTS + enabled: false +- name: MISSING_KDOC_ON_FUNCTION + enabled: false +- name: GENERIC_VARIABLE_WRONG_DECLARATION + enabled: false +- name: TOO_MANY_PARAMETERS + enabled: true + configuration: + maxParameterListSize: '10' \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..4ccd1d1f --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,65 @@ +[versions] +# IntelliJ platform dependencies +intellij-min="2023.1.5" +intellij-type="IU" +intellij-remoteRobot="0.11.22" +intellij-plugin="1.17.3" +intellij-testBuild="241.14494.241" +intellij-changelog-plugin="2.2.0" +# Other plugin dependencies +versions-plugin="0.51.0" +spotless-plugin="6.25.0" +jmh-plugin="0.7.2" +diktat-plugin="1.0.1" +jmhreport-plugin="0.9.0" + +# Library dependencies +bson="5.0.0" +mongodb-driver="4.11.0" +kotlin-stdlib="1.9.22" +kotlinx-coroutines="1.8.0-RC2" +jupiter="5.10.2" +mockito="5.11.0" +mockito-kotlin="5.3.1" +okHttp="4.12.0" +retrofit="2.11.0" +jmh="1.37" +segment="3.5.1" + +[plugins] +intellij={ id="org.jetbrains.intellij", version.ref="intellij-plugin" } +jmh={ id="me.champeau.jmh", version.ref="jmh-plugin" } +versions={ id="com.github.ben-manes.versions", version.ref="versions-plugin" } +spotless={ id="com.diffplug.spotless", version.ref="spotless-plugin" } +changelog={ id="org.jetbrains.changelog", version.ref="intellij-changelog-plugin" } +jmhreport={ id="io.morethan.jmhreport", version.ref="jmhreport-plugin" } + +[libraries] +mongodb-bson={ group="org.mongodb", name="bson", version.ref="bson" } +mongodb-driver={ group="org.mongodb", name="mongodb-driver-kotlin-coroutine", version.ref="mongodb-driver" } + +kotlin-stdlib={ group="org.jetbrains.kotlin", name="kotlin-stdlib", version.ref="kotlin-stdlib" } +kotlin-coroutines-core={ group="org.jetbrains.kotlinx", name="kotlinx-coroutines-core", version.ref="kotlinx-coroutines" } +kotlin-coroutines-swing={ group="org.jetbrains.kotlinx", name="kotlinx-coroutines-swing", version.ref="kotlinx-coroutines" } + +segment={ group="com.segment.analytics.java", name="analytics", version.ref="segment" } + +testing-jupiter-engine={ group="org.junit.jupiter", name="junit-jupiter-engine", version.ref="jupiter" } +testing-jupiter-vintage-engine={ group="org.junit.vintage", name="junit-vintage-engine", version.ref="jupiter" } + +testing-mockito-core={ group="org.mockito", name="mockito-core", version.ref="mockito" } +testing-mockito-kotlin={ group="org.mockito.kotlin", name="mockito-kotlin", version.ref="mockito-kotlin" } +testing-remoteRobot={ group="com.intellij.remoterobot", name="remote-robot", version.ref="intellij-remoteRobot"} +testing-remoteRobotDeps-remoteFixtures={ group="com.intellij.remoterobot", name="remote-fixtures", version.ref="intellij-remoteRobot"} +testing-remoteRobotDeps-okHttp={ group="com.squareup.okhttp3", name="okhttp", version.ref="okHttp" } +testing-intellij-ideImpl={ group="com.jetbrains.intellij.platform", name="ide-impl", version.ref="intellij-testBuild" } +testing-intellij-coreUi={ group="com.jetbrains.intellij.platform", name="core-ui", version.ref="intellij-testBuild" } +testing-remoteRobotDeps-retrofit={ group="com.squareup.retrofit2", name="retrofit", version.ref="retrofit" } +testing-remoteRobotDeps-retrofitGson={ group="com.squareup.retrofit2", name="converter-gson", version.ref="retrofit" } +testing-jmh-core={ group="org.openjdk.jmh", name="jmh-core", version.ref="jmh" } +testing-jmh-annotationProcessor={ group="org.openjdk.jmh", name="jmh-generator-annprocess", version.ref="jmh" } +testing-jmh-generatorByteCode={ group="org.openjdk.jmh", name="jmh-generator-bytecode", version.ref="jmh" } + +buildScript-plugin-kotlin={ group="org.jetbrains.kotlin", name="kotlin-gradle-plugin", version="1.9.23" } +buildScript-plugin-versions={ group="com.github.ben-manes", name="gradle-versions-plugin", version.ref="versions-plugin" } +buildScript-plugin-spotless={ group="com.diffplug.spotless", name="spotless-plugin-gradle", version="6.25.0" } diff --git a/gradle/pre-commit b/gradle/pre-commit new file mode 100755 index 00000000..27860633 --- /dev/null +++ b/gradle/pre-commit @@ -0,0 +1,33 @@ +#!/bin/bash +echo "*********************************************************" +echo "Running git pre-commit hook. Running Spotless Apply... " +echo "*********************************************************" + +# Gather the staged files - to make sure changes are saved only for these files. +stagedFiles=$(git diff --staged --name-only) + +# run spotless apply +./gradlew --quiet spotlessApply + +status=$? + +if [ "$status" = 0 ] ; then + echo "Static analysis found no problems." + # Add staged file changes to git + for file in $stagedFiles; do + if test -f "$file"; then + git add "$file" + fi + done + #Exit + exit 0 +else + echo "*********************************************************" + echo " ******************************************** " + echo 1>&2 "Spotless Apply found violations it could not fix." + echo "Run spotless apply in your terminal and fix the issues before trying to commit again." + echo " ******************************************** " + echo "*********************************************************" + #Exit + exit 1 +fi \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..e6441136 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..b82aa23a --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..7101f8e4 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/jetbrains-plugin/build.gradle.kts b/packages/jetbrains-plugin/build.gradle.kts new file mode 100644 index 00000000..f3252833 --- /dev/null +++ b/packages/jetbrains-plugin/build.gradle.kts @@ -0,0 +1,135 @@ +import org.jetbrains.changelog.Changelog +import org.jetbrains.changelog.date +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +repositories { + maven("https://www.jetbrains.com/intellij-repository/releases/") + maven("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") +} + +plugins { + alias(libs.plugins.intellij) + alias(libs.plugins.jmh) + alias(libs.plugins.jmhreport) + alias(libs.plugins.changelog) +} + +intellij { + version.set(libs.versions.intellij.min) // Target IDE Version + type.set(libs.versions.intellij.type) // Target IDE Platform + + plugins.set(listOf("com.intellij.java", "com.intellij.database")) +} + +dependencies { + implementation(project(":packages:mongodb-access-adapter")) + implementation(project(":packages:mongodb-autocomplete-engine")) + implementation(project(":packages:mongodb-dialects")) + implementation(project(":packages:mongodb-linting-engine")) + implementation(project(":packages:mongodb-mql-model")) + + implementation(libs.segment) + + jmh(libs.kotlin.stdlib) + jmh(libs.testing.jmh.core) + jmh(libs.testing.jmh.annotationProcessor) + jmh(libs.testing.jmh.generatorByteCode) + + testCompileOnly(libs.testing.intellij.ideImpl) + testCompileOnly(libs.testing.intellij.coreUi) + + testImplementation(libs.testing.remoteRobot) + testImplementation(libs.testing.remoteRobotDeps.remoteFixtures) + testImplementation(libs.testing.remoteRobotDeps.okHttp) + testImplementation(libs.testing.remoteRobotDeps.retrofit) + testImplementation(libs.testing.remoteRobotDeps.retrofitGson) +} + +jmh { + benchmarkMode.set(listOf("thrpt")) + iterations.set(10) + timeOnIteration.set("6s") + timeUnit.set("s") + + warmup.set("1s") + warmupIterations.set(3) + warmupMode.set("INDI") + fork.set(1) + threads.set(1) + failOnError.set(false) + forceGC.set(true) + + humanOutputFile.set(rootProject.layout.buildDirectory.file("reports/jmh/human.txt")) + resultsFile.set(rootProject.layout.buildDirectory.file("reports/jmh/results.json")) + resultFormat.set("json") + profilers.set(listOf("gc")) + + zip64.set(true) +} + +jmhReport { + jmhResultPath = rootProject.layout.buildDirectory.file("reports/jmh/results.json").get().asFile.absolutePath + jmhReportOutput = rootProject.layout.buildDirectory.dir("reports/jmh/").get().asFile.absolutePath +} + +tasks { + register("buildProperties", WriteProperties::class) { + destinationFile.set(project.layout.buildDirectory.file("classes/kotlin/main/build.properties")) + property("pluginVersion", rootProject.version) + property("driverVersion", rootProject.libs.versions.mongodb.driver.get()) + property("segmentApiKey", System.getenv("BUILD_SEGMENT_API_KEY") ?: "") + } + + withType { + dependsOn("buildProperties") + } + + patchPluginXml { + sinceBuild.set("231") + untilBuild.set("241.*") + version.set(rootProject.version.toString()) + + changeNotes.set(provider { + changelog.renderItem( + changelog + .getUnreleased() + .withHeader(false) + .withEmptySections(false), + Changelog.OutputType.HTML + ) + }) + } + + signPlugin { + certificateChain.set(System.getenv("JB_CERTIFICATE_CHAIN")) + privateKey.set(System.getenv("JB_PRIVATE_KEY")) + password.set(System.getenv("JB_PRIVATE_KEY_PASSWORD")) + } + + publishPlugin { + channels = when (System.getenv("JB_PUBLISH_CHANNEL")) { + "ga" -> listOf() + "beta" -> listOf("beta") + else -> listOf("eap") + } + token.set(System.getenv("JB_PUBLISH_TOKEN")) + } +} + +changelog { + version.set(rootProject.version.toString()) + path.set(rootProject.file("CHANGELOG.md").canonicalPath) + header.set(provider { "[${version.get()}] - ${date()}" }) + headerParserRegex.set("""(\d+\.\d+.\d+)""".toRegex()) + introduction.set( + """ + MongoDB plugin for IntelliJ IDEA. + """.trimIndent() + ) + itemPrefix.set("-") + keepUnreleasedSection.set(true) + unreleasedTerm.set("[Unreleased]") + groups.set(listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security")) + lineSeparator.set("\n") + combinePreReleases.set(true) +} \ No newline at end of file diff --git a/packages/jetbrains-plugin/src/jmh/kotlin/com/mongodb/jbplugin/jmh/SampleBenchmark.kt b/packages/jetbrains-plugin/src/jmh/kotlin/com/mongodb/jbplugin/jmh/SampleBenchmark.kt new file mode 100644 index 00000000..e62c4ef0 --- /dev/null +++ b/packages/jetbrains-plugin/src/jmh/kotlin/com/mongodb/jbplugin/jmh/SampleBenchmark.kt @@ -0,0 +1,15 @@ +package com.mongodb.jbplugin.jmh + +import org.openjdk.jmh.annotations.Benchmark +import org.openjdk.jmh.infra.Blackhole + +/** + * Sample benchmark, does not do anything useful. + */ +open class SampleBenchmark { + @Benchmark + fun init(bh: Blackhole) { + bh.consume(1) + // Do nothing + } +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/SayHiListener.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/SayHiListener.kt new file mode 100644 index 00000000..e791d5b4 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/SayHiListener.kt @@ -0,0 +1,25 @@ +package com.mongodb.jbplugin + +import com.intellij.openapi.application.EDT +import com.intellij.openapi.project.DumbAware +import com.intellij.openapi.project.Project +import com.intellij.openapi.startup.StartupActivity +import com.intellij.openapi.ui.Messages +import com.mongodb.jbplugin.meta.BuildInformation +import com.mongodb.jbplugin.observability.probe.PluginActivatedProbe +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking + +/** + * Example listener, we will get rid of this. + */ +class SayHiListener : StartupActivity, DumbAware { + override fun runActivity(project: Project) { + val pluginActivated = project.getService(PluginActivatedProbe::class.java) + + runBlocking(Dispatchers.EDT) { + pluginActivated.pluginActivated() + Messages.showInfoMessage(project, "${BuildInformation.driverVersion}", "Build Info") + } + } +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/meta/BuildInformation.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/meta/BuildInformation.kt new file mode 100644 index 00000000..246bf078 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/meta/BuildInformation.kt @@ -0,0 +1,22 @@ +package com.mongodb.jbplugin.meta + +import java.util.Properties + +/** + * This provides access to the build information generated at build time in Gradle. + * To add new fields to this object, do the following: + * 1. Go to packages/jetbrains-plugin/build.gradle.kts + * 2. Go to the task "buildProperties" + * 3. Add the new property there. Use an existing one as a sample. + * 4. Add the new property here. Use an existing one as a sample. + * 5. Add a fake value into packages/jetbrains-plugin/src/test/resources/build.properties + * 6. Add the new property to the test in BuildInformationTest.kt + */ +object BuildInformation { + private val properties: Properties = Properties().also { + it.load(BuildInformation::class.java.getResourceAsStream("/build.properties")) + } + val pluginVersion = properties["pluginVersion"]!!.toString() + val driverVersion = properties["driverVersion"]!!.toString() + val segmentApiKey = properties["segmentApiKey"]!!.toString() +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/LogMessage.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/LogMessage.kt new file mode 100644 index 00000000..5eb13e73 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/LogMessage.kt @@ -0,0 +1,66 @@ +/** + * This file defines the set of classes that will be used to build a log message. + * These classes are marked as internal because they shouldn't be used outside + * this module. + * + * Ideally, you are injecting the LogMessage service into your probe, and when + * sending an event, we would also send a relevant log message. + * + */ + +package com.mongodb.jbplugin.observability + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project + +/** + * @param gson + * @param message + */ +internal class LogMessageBuilder(private val gson: Gson, message: String) { + private val properties: MutableMap = mutableMapOf("message" to message) + + fun put(key: String, value: Any): LogMessageBuilder { + properties[key] = value + return this + } + + fun build(): String = gson.toJson(properties) +} + +/** + * This class will be injected in probes to build log messages. Usually like: + * ```kt + * @Service(Service.Level.PROJECT) + * class MyProbe(private val project: Project) { + * ... + * fun somethingProbed() { + * val logMessage = project.getService(LogMessage::class.java) + * log.info(logMessage.message("My message").put("someOtherProp", 25).build()) + * } + * ... + * } + * ``` + * + * @param project + */ +@Service(Service.Level.PROJECT) +internal class LogMessage(private val project: Project) { + private val gson = GsonBuilder().generateNonExecutableJson().disableJdkUnsafe().create() + + fun message(key: String): LogMessageBuilder { + val runtimeInformationService = project.getService(RuntimeInformationService::class.java) + val runtimeInformation = runtimeInformationService.get() + + return LogMessageBuilder(gson, key) + .put("userId", runtimeInformation.userId) + .put("os", runtimeInformation.osName) + .put("arch", runtimeInformation.arch) + .put("jvmVendor", runtimeInformation.jvmVendor) + .put("jvmVersion", runtimeInformation.jvmVersion) + .put("buildVersion", runtimeInformation.buildVersion) + .put("ide", runtimeInformation.applicationName) + } +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationService.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationService.kt new file mode 100644 index 00000000..c8d7ed1d --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationService.kt @@ -0,0 +1,70 @@ +/** + * Contains all runtime information relevant for observability. + */ + +package com.mongodb.jbplugin.observability + +import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.application.PermanentInstallationID +import com.intellij.openapi.components.Service +import com.intellij.openapi.util.SystemInfo + +/** + * Represents all the gathered information from the host machine. + * + * @property userId + * @property osName + * @property arch + * @property jvmVendor + * @property jvmVersion + * @property buildVersion + * @property applicationName + */ +data class RuntimeInformation( + val userId: String, + val osName: String, + val arch: String, + val jvmVendor: String, + val jvmVersion: String, + val buildVersion: String, + val applicationName: String, +) + +/** + * Computes, if possible, the current runtime information. It provides a method that + * returns a RuntimeInformation object. + * + * Do not use RuntimeInformation for feature toggling. + * + * @see RuntimeInformation + */ +@Service +class RuntimeInformationService { + private val userId = getOrDefault("") { PermanentInstallationID.get() } + private val osName = getOrDefault("") { SystemInfo.getOsNameAndVersion() } + private val arch = getOrDefault("") { SystemInfo.OS_ARCH } + private val jvmVendor = getOrDefault("") { SystemInfo.JAVA_VENDOR } + private val jvmVersion = getOrDefault("") { SystemInfo.JAVA_VERSION } + private val buildVersion = getOrDefault("") { ApplicationInfo.getInstance().fullVersion } + private val applicationName = getOrDefault("") { + ApplicationInfo.getInstance().fullApplicationName + } + + fun get(): RuntimeInformation = RuntimeInformation( + userId, + osName, + arch, + jvmVendor, + jvmVersion, + buildVersion, + applicationName + ) + + private fun getOrDefault(default: T, supplier: () -> T?): T { + return try { + supplier() ?: default + } catch (ex: Throwable) { + return default + } + } +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryEvent.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryEvent.kt new file mode 100644 index 00000000..cd078699 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryEvent.kt @@ -0,0 +1,80 @@ +/** + * This file defines all the properties and events that can be sent to + * Segment. New properties (or fields) will be added in the TelemetryProperty + * enum class. New events will be added inside the TelemetryEvent sealed class. + */ + +package com.mongodb.jbplugin.observability + +/** + * Represents a field in Segment. New fields will be added here, where the + * publicName is how it will look like in Segment. + * + * @property publicName Name of the field in Segment. + */ +internal enum class TelemetryProperty(val publicName: String) { + IS_ATLAS("is_atlas"), + IS_LOCALHOST("is_localhost"), + IS_ENTERPRISE("is_enterprise"), + IS_GENUINE("is_genuine"), + NON_GENUINE_SERVER_NAME("non_genuine_server_name"), + SERVER_OS_FAMILY("server_os_family"), + VERSION("version"), + ; +} + +/** + * Represents an event that will be sent to Segment. Essentially, all + * events will be sent as Track events to Segment but PluginActivated, + * that will be sent as an identify event. This logic is in the + * TelemetryService. + * + * @property name Name of the event + * @property properties Map of fields sent to Segment. + * @see TelemetryService + */ +internal sealed class TelemetryEvent( + internal val name: String, + internal val properties: Map +) { + /** + * Represents the event that is emitted when the plugin is started. + */ + internal data object PluginActivated : TelemetryEvent( + name = "plugin-activated", + properties = emptyMap() + ) + + /** + * Represents the event that is emitted when the plugin connects + * to a cluster. + * + * @param isAtlas + * @param isLocalhost + * @param isEnterprise + * @param isGenuine + * @param nonGenuineServerName + * @param serverOsFamily + * @param version + */ + internal class NewConnection( + isAtlas: Boolean, + isLocalhost: Boolean, + isEnterprise: Boolean, + isGenuine: Boolean, + nonGenuineServerName: String?, + serverOsFamily: String?, + version: String? + ) : TelemetryEvent( + name = "new-connection", + properties = mapOf( + TelemetryProperty.IS_ATLAS to isAtlas, + TelemetryProperty.IS_LOCALHOST to isLocalhost, + TelemetryProperty.IS_ENTERPRISE to isEnterprise, + TelemetryProperty.IS_GENUINE to isGenuine, + TelemetryProperty.NON_GENUINE_SERVER_NAME to (nonGenuineServerName ?: ""), + TelemetryProperty.SERVER_OS_FAMILY to (serverOsFamily ?: ""), + TelemetryProperty.VERSION to (version ?: "") + ) + ) +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryService.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryService.kt new file mode 100644 index 00000000..186b246d --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/TelemetryService.kt @@ -0,0 +1,35 @@ +package com.mongodb.jbplugin.observability + +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project +import com.segment.analytics.Analytics +import com.segment.analytics.messages.IdentifyMessage +import com.segment.analytics.messages.TrackMessage + +/** + * This telemetry service is used to send events to Segment. Should be used within + * probes, no directly. That is why it's marked as internal. + * + * @param project + */ +@Service(Service.Level.PROJECT) +internal class TelemetryService(private val project: Project) { + internal var analytics: Analytics = Analytics.builder("KEY").build() + + fun sendEvent(event: TelemetryEvent) { + val runtimeInformationService = project.getService(RuntimeInformationService::class.java) + val runtimeInfo = runtimeInformationService.get() + + val message = when (event) { + is TelemetryEvent.PluginActivated -> IdentifyMessage.builder().userId(runtimeInfo.userId) + else -> + TrackMessage.builder(event.name).userId(runtimeInfo.userId) + .properties(event.properties.entries.associate { + it.key.publicName to it.value + }) + + } + + analytics.enqueue(message) + } +} diff --git a/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbe.kt b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbe.kt new file mode 100644 index 00000000..cc1672b7 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbe.kt @@ -0,0 +1,31 @@ +package com.mongodb.jbplugin.observability.probe + +import com.intellij.openapi.components.Service +import com.intellij.openapi.diagnostic.Logger +import com.intellij.openapi.diagnostic.logger +import com.intellij.openapi.project.Project +import com.mongodb.jbplugin.observability.LogMessage +import com.mongodb.jbplugin.observability.TelemetryEvent +import com.mongodb.jbplugin.observability.TelemetryService + +private val logger: Logger = logger() + +/** + * This probe is emitted when the plugin is activated (started). + * + * @param project Project where the plugin is set up + */ +@Service(Service.Level.PROJECT) +class PluginActivatedProbe(private val project: Project) { + fun pluginActivated() { + val telemetry = project.getService(TelemetryService::class.java) + val logMessage = project.getService(LogMessage::class.java) + + telemetry.sendEvent(TelemetryEvent.PluginActivated) + + logger.info( + logMessage.message("Plugin activated.") + .build() + ) + } +} diff --git a/packages/jetbrains-plugin/src/main/resources/META-INF/plugin.xml b/packages/jetbrains-plugin/src/main/resources/META-INF/plugin.xml new file mode 100644 index 00000000..0f527d95 --- /dev/null +++ b/packages/jetbrains-plugin/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,17 @@ + + com.mongodb.jbplugin + MongoDB Integration + MongoDB, Inc. + + ]]> + com.intellij.modules.platform + com.intellij.java + com.intellij.database + + + + + + + \ No newline at end of file diff --git a/packages/jetbrains-plugin/src/main/resources/META-INF/pluginIcon.svg b/packages/jetbrains-plugin/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 00000000..80736ccb --- /dev/null +++ b/packages/jetbrains-plugin/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/ProjectExtensions.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/ProjectExtensions.kt new file mode 100644 index 00000000..180210d2 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/ProjectExtensions.kt @@ -0,0 +1,102 @@ +/** + * Functions to simplify testing that depends on a project. + */ + +package com.mongodb.jbplugin + +import com.google.gson.Gson +import com.intellij.openapi.project.Project +import com.mongodb.jbplugin.observability.LogMessage +import com.mongodb.jbplugin.observability.LogMessageBuilder +import com.mongodb.jbplugin.observability.RuntimeInformation +import com.mongodb.jbplugin.observability.RuntimeInformationService +import com.mongodb.jbplugin.observability.TelemetryService +import com.mongodb.jbplugin.observability.probe.PluginActivatedProbe +import org.mockito.Mockito.`when` +import org.mockito.kotlin.any +import org.mockito.kotlin.mock + +/** + * Creates a mock project with dependencies injected. + * + * All parameters are optional, so you can pass a custom mock to any of them to + * verify. + * + * @param telemetryService + * @param pluginActivatedProbe + * @param logMessage + * @param runtimeInformationService + * @return A mock project to be used in dependency injection. + */ +internal fun mockProject( + telemetryService: TelemetryService = mock(), + runtimeInformationService: RuntimeInformationService = mockRuntimeInformationService(), + pluginActivatedProbe: PluginActivatedProbe = mock(), + logMessage: LogMessage = mockLogMessage(), +): Project { + val project = mock() + `when`(project.getService(TelemetryService::class.java)).thenReturn(telemetryService) + `when`(project.getService(RuntimeInformationService::class.java)).thenReturn(runtimeInformationService) + `when`(project.getService(PluginActivatedProbe::class.java)).thenReturn(pluginActivatedProbe) + `when`(project.getService(LogMessage::class.java)).thenReturn(logMessage) + + return project +} + +/** + * Generates a mock runtime information service, useful for testing. If you need + * to create your own. You'll likely will build first an information service and + * then inject it into a mock project, something like this: + * + * ```kt + * val myInfoService = mockRuntimeInformationService(userId = "hey") + * val myProject = mockProject(runtimeInformationService = myInfoService) + * ``` + * + * @param userId + * @param osName + * @param arch + * @param jvmVendor + * @param jvmVersion + * @param buildVersion + * @param applicationName + * @return A new mocked RuntimeInformationService + */ +internal fun mockRuntimeInformationService( + userId: String = "123456", + osName: String = "Winux OSX", + arch: String = "x128", + jvmVendor: String = "Obelisk", + jvmVersion: String = "42", + buildVersion: String = "2024.2", + applicationName: String = "Cool IDE" +): RuntimeInformationService = mock().also { service -> + `when`(service.get()).thenReturn( + RuntimeInformation( + userId = userId, + osName = osName, + arch = arch, + jvmVendor = jvmVendor, + jvmVersion = jvmVersion, + buildVersion = buildVersion, + applicationName = applicationName + )) +} + +/** + * Generates a mock log message service. + * You'll likely will build first a log message service and + * then inject it into a mock project, something like this: + * + * ```kt + * val myLogMessage = mockLogMessage() + * val myProject = mockProject(logMessage = myLogMessage) + * ``` + * + * @return A new mocked LogMessage + */ +internal fun mockLogMessage(): LogMessage = mock().also { logMessage -> + `when`(logMessage.message(any())).then { message -> + LogMessageBuilder(Gson(), message.arguments[0].toString()) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/meta/BuildInformationTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/meta/BuildInformationTest.kt new file mode 100644 index 00000000..d91caa9b --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/meta/BuildInformationTest.kt @@ -0,0 +1,13 @@ +package com.mongodb.jbplugin.meta + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class BuildInformationTest { + @Test + fun `loads all build information from the resource file`() { + assertEquals("0.0.2-madeUp", BuildInformation.pluginVersion) + assertEquals("4.0.0-madeUp", BuildInformation.driverVersion) + assertEquals("madeUp", BuildInformation.segmentApiKey) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/LogMessageTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/LogMessageTest.kt new file mode 100644 index 00000000..e1d51ed8 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/LogMessageTest.kt @@ -0,0 +1,31 @@ +package com.mongodb.jbplugin.observability + +import com.google.gson.Gson +import com.mongodb.jbplugin.mockProject +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +open class LogMessageTest { + private val gson: Gson = Gson() + + @Test + fun `should serialize a log message to json`() { + val message = LogMessage(mockProject()).message("My Message").build() + val parsedMessage = gson.fromJson>(message, Map::class.java) + + assertEquals("My Message", parsedMessage["message"]) + } + + @Test + fun `should serialize a log message to json with additional fields`() { + val message = LogMessage(mockProject()) + .message("My Message") + .put("jetbrainsId", "someId") + .build() + + val parsedMessage = gson.fromJson>(message, Map::class.java) + + assertEquals("My Message", parsedMessage["message"]) + assertEquals("someId", parsedMessage["jetbrainsId"]) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationServiceTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationServiceTest.kt new file mode 100644 index 00000000..88548ec7 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/RuntimeInformationServiceTest.kt @@ -0,0 +1,77 @@ +package com.mongodb.jbplugin.observability + +import com.intellij.openapi.application.ApplicationInfo +import com.intellij.openapi.application.PermanentInstallationID +import com.intellij.openapi.util.SystemInfo +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.MockedStatic +import org.mockito.Mockito.`when` +import org.mockito.Mockito.mock +import org.mockito.Mockito.mockStatic + +class RuntimeInformationServiceTest { + private lateinit var permanentInstallationId: MockedStatic + private lateinit var applicationInfo: MockedStatic + private lateinit var systemInfo: MockedStatic + + @BeforeEach + fun setUp() { + permanentInstallationId = mockStatic(PermanentInstallationID::class.java) + applicationInfo = mockStatic(ApplicationInfo::class.java) + systemInfo = mockStatic(SystemInfo::class.java) + } + + @AfterEach + fun tearDown() { + permanentInstallationId.closeOnDemand() + applicationInfo.closeOnDemand() + systemInfo.closeOnDemand() + } + + @Test + fun `loads all information from runtime`() { + permanentInstallationId.`when` { + PermanentInstallationID.get() + }.thenReturn("123456") + + val appInfoInstance = mock().apply { + `when`(this.fullApplicationName).thenReturn("Test Application") + `when`(this.fullVersion).thenReturn("1984.1.1") + } + + applicationInfo.`when` { + ApplicationInfo.getInstance() + }.thenReturn(appInfoInstance) + + systemInfo.`when` { + SystemInfo.getOsNameAndVersion() + }.thenReturn("Test OS 2708") + + val service = RuntimeInformationService() + + val runtimeInfo = service.get() + assertEquals("123456", runtimeInfo.userId) + assertEquals("Test OS 2708", runtimeInfo.osName) + assertNotNull(runtimeInfo.arch) + assertNotNull(runtimeInfo.jvmVendor) + assertNotNull(runtimeInfo.jvmVersion) + assertEquals("Test Application", runtimeInfo.applicationName) + assertEquals("1984.1.1", runtimeInfo.buildVersion) + } + + @Test + fun `loads the default value on exception`() { + permanentInstallationId.`when` { + PermanentInstallationID.get() + }.thenThrow(RuntimeException("Oops, I did it again.")) + + val service = RuntimeInformationService() + + val runtimeInfo = service.get() + assertEquals("", runtimeInfo.userId) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryEventTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryEventTest.kt new file mode 100644 index 00000000..122a6c82 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryEventTest.kt @@ -0,0 +1,13 @@ +package com.mongodb.jbplugin.observability + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +internal class TelemetryEventTest { + @Test + fun `PluginActivated is mapped correctly`() { + val pluginActivated = TelemetryEvent.PluginActivated + assertEquals(mapOf(), pluginActivated.properties) + assertEquals("plugin-activated", pluginActivated.name) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryServiceTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryServiceTest.kt new file mode 100644 index 00000000..cc491ead --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/TelemetryServiceTest.kt @@ -0,0 +1,61 @@ +package com.mongodb.jbplugin.observability + +import com.mongodb.jbplugin.mockProject +import com.mongodb.jbplugin.mockRuntimeInformationService +import com.segment.analytics.Analytics +import org.junit.jupiter.api.Test +import org.mockito.kotlin.argThat +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify + +internal class TelemetryServiceTest { + @Test + fun `sends an identify event when a PluginActivated event is sent`() { + val mockRuntimeInfo = mockRuntimeInformationService(userId = "654321") + val service = TelemetryService(mockProject( + runtimeInformationService = mockRuntimeInfo + )).apply { + analytics = mock() + } + + service.sendEvent(TelemetryEvent.PluginActivated) + + verify(service.analytics).enqueue( + argThat { + build().let { + it.userId() == "654321" && + it.type().name == "identify" + } + } + ) + } + + @Test + fun `sends a new connection event as a tracking event`() { + val mockRuntimeInfo = mockRuntimeInformationService(userId = "654321") + val service = TelemetryService(mockProject( + runtimeInformationService = mockRuntimeInfo + )).apply { + analytics = mock() + } + + service.sendEvent(TelemetryEvent.NewConnection( + isAtlas = true, + isLocalhost = false, + isEnterprise = true, + isGenuine = true, + nonGenuineServerName = null, + serverOsFamily = null, + version = "8.0" + )) + + verify(service.analytics).enqueue( + argThat { + build().let { + it.userId() == "654321" && + it.type().name == "track" + } + } + ) + } +} diff --git a/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbeTest.kt b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbeTest.kt new file mode 100644 index 00000000..d8ffec48 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/kotlin/com/mongodb/jbplugin/observability/probe/PluginActivatedProbeTest.kt @@ -0,0 +1,19 @@ +package com.mongodb.jbplugin.observability.probe + +import com.mongodb.jbplugin.mockProject +import com.mongodb.jbplugin.observability.TelemetryEvent +import com.mongodb.jbplugin.observability.TelemetryService +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify + +internal class PluginActivatedProbeTest { + @Test + fun `should send a PluginActivated event`() { + val telemetryService = mock() + val probe = PluginActivatedProbe(mockProject(telemetryService = telemetryService)) + + probe.pluginActivated() + verify(telemetryService).sendEvent(TelemetryEvent.PluginActivated) + } +} diff --git a/packages/jetbrains-plugin/src/test/resources/build.properties b/packages/jetbrains-plugin/src/test/resources/build.properties new file mode 100644 index 00000000..2b65ea63 --- /dev/null +++ b/packages/jetbrains-plugin/src/test/resources/build.properties @@ -0,0 +1,3 @@ +pluginVersion=0.0.2-madeUp +driverVersion=4.0.0-madeUp +segmentApiKey=madeUp diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..447a5f0a --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +rootProject.name = "mongodb-jetbrains-plugin" + +pluginManagement { + repositories { + maven("https://oss.sonatype.org/content/repositories/snapshots/") + mavenCentral() + gradlePluginPortal() + } +} + +include( + "packages:mongodb-mql-model", + "packages:mongodb-dialects", + "packages:mongodb-autocomplete-engine", + "packages:mongodb-linting-engine", + "packages:mongodb-access-adapter", + "packages:jetbrains-plugin", +) \ No newline at end of file