Repository: zhensherlock/intellij-platform-git-stats-plugin Branch: main Commit: 3a2c30561c54 Files: 37 Total size: 68.3 KB Directory structure: gitextract_ejg8953l/ ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── build.yml │ ├── release.yml │ └── run-ui-tests.yml ├── .gitignore ├── .run/ │ ├── Run IDE for UI Tests.run.xml │ ├── Run IDE with Plugin.run.xml │ ├── Run Plugin Tests.run.xml │ ├── Run Plugin Verification.run.xml │ └── Run Qodana.run.xml ├── CHANGELOG.md ├── README.md ├── build.gradle.kts ├── gradle/ │ ├── libs.versions.toml │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── qodana.yml ├── settings.gradle.kts └── src/ ├── main/ │ ├── kotlin/ │ │ └── com/ │ │ └── huayi/ │ │ └── intellijplatform/ │ │ └── gitstats/ │ │ ├── MyBundle.kt │ │ ├── components/ │ │ │ ├── RefreshButton.kt │ │ │ ├── SettingAction.kt │ │ │ └── SettingDialogWrapper.kt │ │ ├── listeners/ │ │ │ └── MyFrameStateListener.kt │ │ ├── models/ │ │ │ └── SettingModel.kt │ │ ├── services/ │ │ │ └── GitStatsService.kt │ │ ├── toolWindow/ │ │ │ ├── GitStatsWindowFactory.kt │ │ │ └── StatsTableModel.kt │ │ └── utils/ │ │ ├── GitUtils.kt │ │ └── Utils.kt │ └── resources/ │ ├── META-INF/ │ │ └── plugin.xml │ └── messages/ │ └── MyBundle.properties └── test/ ├── kotlin/ │ └── com/ │ └── huayi/ │ └── intellijplatform/ │ └── gitstats/ │ └── MyPluginTest.kt └── testData/ └── rename/ ├── foo.xml └── foo_after.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/dependabot.yml ================================================ # Dependabot configuration: # https://docs.github.com/en/free-pro-team@latest/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: # Maintain dependencies for Gradle dependencies - package-ecosystem: "gradle" directory: "/" target-branch: "next" schedule: interval: "daily" # Maintain dependencies for GitHub Actions - package-ecosystem: "github-actions" directory: "/" target-branch: "next" schedule: interval: "daily" ================================================ FILE: .github/workflows/build.yml ================================================ # GitHub Actions Workflow is created for testing and preparing the plugin release in the following steps: # - validate Gradle Wrapper, # - run 'test' and 'verifyPlugin' tasks, # - run Qodana inspections, # - run 'buildPlugin' task and prepare artifact for the further tests, # - run 'runPluginVerifier' task, # - create a draft release. # # Workflow is triggered on push and pull_request events. # # GitHub Actions reference: https://help.github.com/en/actions # ## JBIJPPTPL name: Build on: # Trigger the workflow on pushes to only the 'main' branch (this avoids duplicate checks being run e.g. for dependabot pull requests) push: branches: [main] # Trigger the workflow on any pull request pull_request: jobs: # Run Gradle Wrapper Validation Action to verify the wrapper's checksum # Run verifyPlugin, IntelliJ Plugin Verifier, and test Gradle tasks # Build plugin and provide the artifact for the next workflow jobs build: name: Build runs-on: ubuntu-latest outputs: version: ${{ steps.properties.outputs.version }} changelog: ${{ steps.properties.outputs.changelog }} steps: # Free GitHub Actions Environment Disk Space - name: Maximize Build Space run: | sudo rm -rf /usr/share/dotnet sudo rm -rf /usr/local/lib/android sudo rm -rf /opt/ghc # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 # Validate wrapper - name: Gradle Wrapper Validation uses: gradle/wrapper-validation-action@v3.5.0 # Setup Java 11 environment for the next steps - name: Setup Java uses: actions/setup-java@v4 with: distribution: zulu java-version: 11 # Set environment variables - name: Export Properties id: properties shell: bash run: | PROPERTIES="$(./gradlew properties --console=plain -q)" VERSION="$(echo "$PROPERTIES" | grep "^version:" | cut -f2- -d ' ')" NAME="$(echo "$PROPERTIES" | grep "^pluginName:" | cut -f2- -d ' ')" CHANGELOG="$(./gradlew getChangelog --unreleased --no-header --console=plain -q)" echo "version=$VERSION" >> $GITHUB_OUTPUT echo "name=$NAME" >> $GITHUB_OUTPUT echo "pluginVerifierHomeDir=~/.pluginVerifier" >> $GITHUB_OUTPUT echo "changelog<> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT ./gradlew listProductsReleases # prepare list of IDEs for Plugin Verifier # Run tests - name: Run Tests run: ./gradlew check # Collect Tests Result of failed tests - name: Collect Tests Result if: ${{ failure() }} uses: actions/upload-artifact@v4 with: name: tests-result path: ${{ github.workspace }}/build/reports/tests # Upload Kover report to CodeCov - name: Upload Code Coverage Report uses: codecov/codecov-action@v4 with: files: ${{ github.workspace }}/build/reports/kover/xml/report.xml # Cache Plugin Verifier IDEs - name: Setup Plugin Verifier IDEs Cache uses: actions/cache@v4 with: path: ${{ steps.properties.outputs.pluginVerifierHomeDir }}/ides key: plugin-verifier-${{ hashFiles('build/listProductsReleases.txt') }} # Run Verify Plugin task and IntelliJ Plugin Verifier tool - name: Run Plugin Verification tasks run: ./gradlew runPluginVerifier -Dplugin.verifier.home.dir=${{ steps.properties.outputs.pluginVerifierHomeDir }} # Collect Plugin Verifier Result - name: Collect Plugin Verifier Result if: ${{ always() }} uses: actions/upload-artifact@v4 with: name: pluginVerifier-result path: ${{ github.workspace }}/build/reports/pluginVerifier # Run Qodana inspections # - name: Qodana - Code Inspection # uses: JetBrains/qodana-action@v2023.3.1 # Prepare plugin archive content for creating artifact - name: Prepare Plugin Artifact id: artifact shell: bash run: | cd ${{ github.workspace }}/build/distributions FILENAME=`ls *.zip` unzip "$FILENAME" -d content echo "filename=${FILENAME:0:-4}" >> $GITHUB_OUTPUT # Store already-built plugin as an artifact for downloading - name: Upload artifact uses: actions/upload-artifact@v4 with: name: ${{ steps.artifact.outputs.filename }} path: ./build/distributions/content/*/* # Prepare a draft release for GitHub Releases page for the manual verification # If accepted and published, release workflow would be triggered releaseDraft: name: Release Draft if: github.event_name != 'pull_request' needs: build runs-on: ubuntu-latest permissions: contents: write steps: # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 # Remove old release drafts by using the curl request for the available releases with a draft flag - name: Remove Old Release Drafts env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | gh api repos/{owner}/{repo}/releases \ --jq '.[] | select(.draft == true) | .id' \ | xargs -I '{}' gh api -X DELETE repos/{owner}/{repo}/releases/{} # Create a new release draft which is not publicly visible and requires manual acceptance - name: Create Release Draft env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | gh release create v${{ needs.build.outputs.version }} \ --draft \ --title "v${{ needs.build.outputs.version }}" \ --notes "$(cat << 'EOM' ${{ needs.build.outputs.changelog }} EOM )" ================================================ FILE: .github/workflows/release.yml ================================================ # GitHub Actions Workflow created for handling the release process based on the draft release prepared with the Build workflow. # Running the publishPlugin task requires all following secrets to be provided: PUBLISH_TOKEN, PRIVATE_KEY, PRIVATE_KEY_PASSWORD, CERTIFICATE_CHAIN. # See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information. name: Release on: release: types: [prereleased, released] jobs: # Prepare and publish the plugin to the Marketplace repository release: name: Publish Plugin runs-on: ubuntu-latest permissions: contents: write pull-requests: write steps: # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 with: ref: ${{ github.event.release.tag_name }} # Setup Java 11 environment for the next steps - name: Setup Java uses: actions/setup-java@v4 with: distribution: zulu java-version: 11 # Set environment variables - name: Export Properties id: properties shell: bash run: | CHANGELOG="$(cat << 'EOM' | sed -e 's/^[[:space:]]*$//g' -e '/./,$!d' ${{ github.event.release.body }} EOM )" echo "changelog<> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT # Update Unreleased section with the current release note - name: Patch Changelog if: ${{ steps.properties.outputs.changelog != '' }} env: CHANGELOG: ${{ steps.properties.outputs.changelog }} run: | ./gradlew patchChangelog --release-note="$CHANGELOG" # Publish the plugin to the Marketplace - name: Publish Plugin env: PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.CERTIFICATE_CHAIN }} PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }} PRIVATE_KEY_PASSWORD: ${{ secrets.PRIVATE_KEY_PASSWORD }} run: ./gradlew publishPlugin # Upload artifact as a release asset - name: Upload Release Asset env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: gh release upload ${{ github.event.release.tag_name }} ./build/distributions/* # Create pull request - name: Create Pull Request if: ${{ steps.properties.outputs.changelog != '' }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | VERSION="${{ github.event.release.tag_name }}" BRANCH="changelog-update-$VERSION" LABEL="release changelog" git config user.email "action@github.com" git config user.name "GitHub Action" git checkout -b $BRANCH git commit -am "Changelog update - $VERSION" git push --set-upstream origin $BRANCH gh label create "$LABEL" \ --force \ --description "Pull requests with release changelog update" \ || true gh pr create \ --title "Changelog update - \`$VERSION\`" \ --body "Current pull request contains patched \`CHANGELOG.md\` file for the \`$VERSION\` version." \ --label "$LABEL" \ --head $BRANCH ================================================ FILE: .github/workflows/run-ui-tests.yml ================================================ # GitHub Actions Workflow for launching UI tests on Linux, Windows, and Mac in the following steps: # - prepare and launch IDE with your plugin and robot-server plugin, which is needed to interact with UI # - wait for IDE to start # - run UI tests with separate Gradle task # # Please check https://github.com/JetBrains/intellij-ui-test-robot for information about UI tests with IntelliJ Platform # # Workflow is triggered manually. name: Run UI Tests on: workflow_dispatch jobs: testUI: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: include: - os: ubuntu-latest runIde: | export DISPLAY=:99.0 Xvfb -ac :99 -screen 0 1920x1080x16 & gradle runIdeForUiTests & - os: windows-latest runIde: start gradlew.bat runIdeForUiTests - os: macos-latest runIde: ./gradlew runIdeForUiTests & steps: # Check out current repository - name: Fetch Sources uses: actions/checkout@v4 # Setup Java 11 environment for the next steps - name: Setup Java uses: actions/setup-java@v4 with: distribution: zulu java-version: 11 # Run IDEA prepared for UI testing - name: Run IDE run: ${{ matrix.runIde }} # Wait for IDEA to be started - name: Health Check uses: jtalk/url-health-check-action@v4 with: url: http://127.0.0.1:8082 max-attempts: 15 retry-delay: 30s # Run tests - name: Tests run: ./gradlew test ================================================ FILE: .gitignore ================================================ .gradle .idea .qodana build ================================================ FILE: .run/Run IDE for UI Tests.run.xml ================================================ true true false ================================================ FILE: .run/Run IDE with Plugin.run.xml ================================================ true true false ================================================ FILE: .run/Run Plugin Tests.run.xml ================================================ true true false ================================================ FILE: .run/Run Plugin Verification.run.xml ================================================ true true false ================================================ FILE: .run/Run Qodana.run.xml ================================================ true true false ================================================ FILE: CHANGELOG.md ================================================ # intellij-platform-git-stats-plugin Changelog ## [Unreleased] ## [0.6.2] - 2025-05-13 **2025.05.13** - ✨ Support 2025.1 ## [0.6.1] - 2024-11-19 **2024.11.19** - 🐛 Fixed error basePath - 🐛 Fixed label width ## [0.6.0] - 2024-11-17 **2024.11.17** - ✨ Add git exclude path - ✨ Support 2024.3 ## [0.5.0] - 2024-09-18 **2024.09.18** - ✨ Support 2024.2 ## [0.4.0] - 2024-05-29 **2024.05.29** - ✨ Support UTF-8 ## [0.0.2] - 2023-05-26 **2023.05.26** - ✨ Add advanced mode - ✨ 添加高级模式 ## [0.0.1] - 2023-05-15 ### Added - Displays the code statistics table [Unreleased]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.6.2...HEAD [0.6.2]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.6.1...v0.6.2 [0.6.1]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.6.0...v0.6.1 [0.6.0]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.5.0...v0.6.0 [0.5.0]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.0.2...v0.4.0 [0.0.2]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/compare/v0.0.1...v0.0.2 [0.0.1]: https://github.com/zhensherlock/intellij-platform-git-stats-plugin/commits/v0.0.1 [//]: # ================================================ FILE: README.md ================================================ # intellij-platform-git-stats-plugin ![Build](https://github.com/zhensherlock/intellij-platform-git-stats-plugin/workflows/Build/badge.svg) [![Version](https://img.shields.io/jetbrains/plugin/v/com.huayi.intellijplatform.gitstats.svg)](https://plugins.jetbrains.com/plugin/com.huayi.intellijplatform.gitstats) [![Downloads](https://img.shields.io/jetbrains/plugin/d/com.huayi.intellijplatform.gitstats.svg)](https://plugins.jetbrains.com/plugin/com.huayi.intellijplatform.gitstats) [//]: # (## Template ToDo list) [//]: # (- [x] Create a new [IntelliJ Platform Plugin Template][template] project.) [//]: # (- [ ] Get familiar with the [template documentation][template].) [//]: # (- [ ] Adjust the [pluginGroup](./gradle.properties), [plugin ID](./src/main/resources/META-INF/plugin.xml) and [sources package](./src/main/kotlin).) [//]: # (- [ ] Adjust the plugin description in `README` (see [Tips][docs:plugin-description])) [//]: # (- [ ] Review the [Legal Agreements](https://plugins.jetbrains.com/docs/marketplace/legal-agreements.html?from=IJPluginTemplate).) [//]: # (- [ ] [Publish a plugin manually](https://plugins.jetbrains.com/docs/intellij/publishing-plugin.html?from=IJPluginTemplate) for the first time.) [//]: # (- [ ] Set the `PLUGIN_ID` in the above README badges.) [//]: # (- [ ] Set the [Plugin Signing](https://plugins.jetbrains.com/docs/intellij/plugin-signing.html?from=IJPluginTemplate) related [secrets](https://github.com/JetBrains/intellij-platform-plugin-template#environment-variables).) [//]: # (- [ ] Set the [Deployment Token](https://plugins.jetbrains.com/docs/marketplace/plugin-upload.html?from=IJPluginTemplate).) [//]: # (- [ ] Click the Watch button on the top of the [IntelliJ Platform Plugin Template][template] to be notified about releases containing new features and fixes.) This plugin aims to help users better understand their code writing by counting the modifications of the source code in the project directory opened by the current IDE. It groups and counts the number of added lines of code, deleted lines of code, and modified files within a certain time period, and finally presents the results in a list form, allowing users to have a clear understanding of the overall code writing situation of their projects. 本插件旨在通过统计当前IDE打开的项目目录中的源代码修改情况,帮助用户更好地了解自己的代码编写情况。通过分组统计某个时间段内的添加代码行数、删除代码行数、修改文件数量,最后用列表形式展现,让用户清晰地了解自己项目的整体编写情况。 ## Installation - Using IDE built-in plugin system: Settings/Preferences > Plugins > Marketplace > Search for "intellij-platform-git-stats-plugin" > Install Plugin - Manually: Download the [latest release](https://github.com/zhensherlock/intellij-platform-git-stats-plugin/releases/latest) and install it manually using Settings/Preferences > Plugins > ⚙️ > Install plugin from disk... --- Plugin based on the [IntelliJ Platform Plugin Template][template]. [template]: https://github.com/JetBrains/intellij-platform-plugin-template [docs:plugin-description]: https://plugins.jetbrains.com/docs/intellij/plugin-user-experience.html#plugin-description-and-presentation ================================================ FILE: build.gradle.kts ================================================ import org.jetbrains.changelog.Changelog import org.jetbrains.changelog.markdownToHTML fun properties(key: String) = providers.gradleProperty(key) fun environment(key: String) = providers.environmentVariable(key) plugins { id("java") // Java support alias(libs.plugins.kotlin) // Kotlin support alias(libs.plugins.gradleIntelliJPlugin) // Gradle IntelliJ Plugin alias(libs.plugins.changelog) // Gradle Changelog Plugin alias(libs.plugins.qodana) // Gradle Qodana Plugin alias(libs.plugins.kover) // Gradle Kover Plugin } group = properties("pluginGroup").get() version = properties("pluginVersion").get() // Configure project's dependencies repositories { mavenCentral() } // Dependencies are managed with Gradle version catalog - read more: https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog dependencies { // implementation(libs.annotations) // implementation("org.swinglabs:swingx:1.6.1") // implementation("org.jfxtras:jfxtras-controls:17-r1") // implementation("org.eclipse.jgit:org.eclipse.jgit:6.5.0.202303070854-r") } // Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for 2022.2+. kotlin { jvmToolchain(11) } // Configure Gradle IntelliJ Plugin - read more: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html intellij { pluginName = properties("pluginName") version = properties("platformVersion") type = properties("platformType") // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file. plugins = properties("platformPlugins").map { it.split(',').map(String::trim).filter(String::isNotEmpty) } } // Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin changelog { groups.empty() repositoryUrl = properties("pluginRepositoryUrl") } // Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin //qodana { // cachePath = provider { file(".qodana").canonicalPath } // reportPath = provider { file("build/reports/inspections").canonicalPath } // saveReport = true // showReport = environment("QODANA_SHOW_REPORT").map { it.toBoolean() }.getOrElse(false) //} // Configure Gradle Kover Plugin - read more: https://github.com/Kotlin/kotlinx-kover#configuration //koverReport { // defaults { // xml { // onCheck = true // } // } //} tasks { wrapper { gradleVersion = properties("gradleVersion").get() } patchPluginXml { version = properties("pluginVersion") sinceBuild = properties("pluginSinceBuild") untilBuild = properties("pluginUntilBuild") // Extract the section from README.md and provide for the plugin's manifest pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { val start = "" val end = "" with (it.lines()) { if (!containsAll(listOf(start, end))) { throw GradleException("Plugin description section not found in README.md:\n$start ... $end") } subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } } val changelog = project.changelog // local variable for configuration cache compatibility // Get the latest available change notes from the changelog file changeNotes = properties("pluginVersion").map { pluginVersion -> with(changelog) { renderItem( (getOrNull(pluginVersion) ?: getUnreleased()) .withHeader(false) .withEmptySections(false), Changelog.OutputType.HTML, ) } } } // Configure UI tests plugin // Read more: https://github.com/JetBrains/intellij-ui-test-robot runIdeForUiTests { systemProperty("robot-server.port", "8082") systemProperty("ide.mac.message.dialogs.as.sheets", "false") systemProperty("jb.privacy.policy.text", "") systemProperty("jb.consents.confirmation.enabled", "false") } signPlugin { certificateChain = environment("CERTIFICATE_CHAIN") privateKey = environment("PRIVATE_KEY") password = environment("PRIVATE_KEY_PASSWORD") } publishPlugin { dependsOn("patchChangelog") token = environment("PUBLISH_TOKEN") // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel channels = properties("pluginVersion").map { listOf(it.split('-').getOrElse(1) { "default" }.split('.').first()) } } } ================================================ FILE: gradle/libs.versions.toml ================================================ [versions] # libraries annotations = "24.1.0" # plugins dokka = "1.9.20" kotlin = "2.0.10" changelog = "2.2.1" gradleIntelliJPlugin = "1.17.4" qodana = "2024.3.3" kover = "0.8.3" [libraries] annotations = { group = "org.jetbrains", name = "annotations", version.ref = "annotations" } [plugins] changelog = { id = "org.jetbrains.changelog", version.ref = "changelog" } dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } gradleIntelliJPlugin = { id = "org.jetbrains.intellij", version.ref = "gradleIntelliJPlugin" } kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" } qodana = { id = "org.jetbrains.qodana", version.ref = "qodana" } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ # IntelliJ Platform Artifacts Repositories -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html pluginGroup = com.huayi.intellijplatform.gitstats pluginName = GitStats pluginRepositoryUrl = https://github.com/zhensherlock/intellij-platform-git-stats-plugin # SemVer format -> https://semver.org pluginVersion = 0.6.2 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 221 pluginUntilBuild = 251.* # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension platformType = IC platformVersion = 2022.1.4 # Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html # Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22 platformPlugins = Git4Idea # Gradle Releases -> https://github.com/gradle/gradle/releases gradleVersion = 8.1 # Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib kotlin.stdlib.default.dependency = false # Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html org.gradle.configuration-cache = true # Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html org.gradle.caching = true # Enable Gradle Kotlin DSL Lazy Property Assignment -> https://docs.gradle.org/current/userguide/kotlin_dsl.html#kotdsl:assignment systemProp.org.gradle.unsafe.kotlin.assignment = true # Temporary workaround for Kotlin Compiler OutOfMemoryError -> https://jb.gg/intellij-platform-kotlin-oom kotlin.incremental.useClasspathSnapshot = false ================================================ FILE: gradlew ================================================ #!/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##*/} APP_HOME=$( cd "${APP_HOME:-./}" && 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 which java >/dev/null 2>&1 || 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 # 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=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=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, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. 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" "$@" ================================================ FILE: gradlew.bat ================================================ @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. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. 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 ================================================ FILE: qodana.yml ================================================ # Qodana configuration: # https://www.jetbrains.com/help/qodana/qodana-yaml.html version: 1.0 linter: jetbrains/qodana-jvm-community:latest projectJDK: "17" profile: name: qodana.recommended exclude: - name: All paths: - .qodana ================================================ FILE: settings.gradle.kts ================================================ rootProject.name = "intellij-platform-git-stats-plugin" ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/MyBundle.kt ================================================ package com.huayi.intellijplatform.gitstats import com.intellij.DynamicBundle import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey @NonNls private const val BUNDLE = "messages.MyBundle" object MyBundle : DynamicBundle(BUNDLE) { @Suppress("SpreadOperator") @JvmStatic fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getMessage(key, *params) @Suppress("SpreadOperator", "unused") @JvmStatic fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getLazyMessage(key, *params) } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/components/RefreshButton.kt ================================================ package com.huayi.intellijplatform.gitstats.components import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JButton import javax.swing.SwingWorker class RefreshButton(text: String?) : JButton(text), ActionListener { private var isLoading = false init { addActionListener(this) } override fun actionPerformed(e: ActionEvent) { isLoading = true isEnabled = false text = "Loading..." BackgroundTask().execute() } private inner class BackgroundTask : SwingWorker() { override fun doInBackground(): String { return "null" } override fun done() { isLoading = false isEnabled = true text = "Click me" } } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/components/SettingAction.kt ================================================ package com.huayi.intellijplatform.gitstats.components import com.huayi.intellijplatform.gitstats.models.SettingModel import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import org.jetbrains.annotations.Nls import java.util.function.Supplier class SettingAction(text: @Nls String, defaultSettingModel: SettingModel, private val onSettingChanged: (SettingModel) -> Unit) : DumbAwareAction(Supplier { text }, AllIcons.General.Settings) { private var settingModel: SettingModel = defaultSettingModel set(value) { field = value onSettingChanged.invoke(value) } override fun actionPerformed(e: AnActionEvent) { val dialogWrapper = SettingDialogWrapper(settingModel) dialogWrapper.showAndGet() if (dialogWrapper.isOK) { settingModel = dialogWrapper.settingModel } } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/components/SettingDialogWrapper.kt ================================================ package com.huayi.intellijplatform.gitstats.components import com.huayi.intellijplatform.gitstats.MyBundle import com.huayi.intellijplatform.gitstats.models.SettingModel import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.ui.components.JBTextField import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import java.awt.Dimension import java.awt.GridLayout import javax.swing.BoxLayout import javax.swing.JComponent class SettingDialogWrapper(defaultSettingModel: SettingModel) : DialogWrapper(true) { var settingModel: SettingModel = defaultSettingModel private lateinit var modeComboBox: ComboBox private lateinit var excludeField: JBTextField init { title = "Git Stats Setting" init() } override fun createCenterPanel(): JComponent { val dialogPanel = JBPanel>().apply { layout = GridLayout(2, 1, 0, 5) preferredSize = Dimension(260, 60) } val modeFieldPanel = JBPanel>().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) add(JBLabel(MyBundle.message("settingDialogModeLabel", "")).apply { preferredSize = Dimension(60, 30) }) modeComboBox = ComboBox().apply { addItem("Top-speed") addItem("Advanced") selectedItem = settingModel.mode } add(modeComboBox) } dialogPanel.add(modeFieldPanel) val excludeFieldPanel = JBPanel>().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) add(JBLabel(MyBundle.message("settingDialogExcludeLabel", "")).apply { preferredSize = Dimension(60, 30) }) excludeField = JBTextField().apply { text = settingModel.exclude } add(excludeField) } dialogPanel.add(excludeFieldPanel) return dialogPanel } override fun doOKAction() { settingModel.mode = modeComboBox.selectedItem as String settingModel.exclude = excludeField.text super.doOKAction() } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/listeners/MyFrameStateListener.kt ================================================ package com.huayi.intellijplatform.gitstats.listeners import com.intellij.ide.FrameStateListener import com.intellij.openapi.diagnostic.thisLogger internal class MyFrameStateListener : FrameStateListener { override fun onFrameActivated() { thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.") } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/models/SettingModel.kt ================================================ package com.huayi.intellijplatform.gitstats.models data class SettingModel ( var mode: String = "Top-speed", var exclude: String = "" ) ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/services/GitStatsService.kt ================================================ package com.huayi.intellijplatform.gitstats.services import com.huayi.intellijplatform.gitstats.models.SettingModel import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.huayi.intellijplatform.gitstats.toolWindow.StatsTableModel import com.huayi.intellijplatform.gitstats.utils.GitUtils import com.huayi.intellijplatform.gitstats.utils.Utils import java.text.SimpleDateFormat import java.util.* @Service(Service.Level.PROJECT) class GitStatsService(p: Project) { private var project: Project init { project = p // thisLogger().info(MyBundle.message("projectService", project.name)) } // fun getRandomNumber() = (1..100).random() fun getUserStats(startTime: Date, endTime: Date, settingModel: SettingModel): StatsTableModel { if (!Utils.checkDirectoryExists(project.basePath)) { return StatsTableModel(arrayOf(), arrayOf()) } val gitUtils = GitUtils(project) val userStats = gitUtils.getUserStats( SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime), SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime), settingModel ) val data = userStats.map { item -> arrayOf( item.author, item.commitCount.toString(), item.addedLines.toString(), item.deletedLines.toString(), item.modifiedFileCount.toString() ) }.toTypedArray() return StatsTableModel( data, arrayOf("Author", "CommitCount", "AddedLines", "DeletedLines", "ModifiedFileCount") ) } fun getTopSpeedUserStats(startTime: Date, endTime: Date, settingModel: SettingModel): StatsTableModel { if (!Utils.checkDirectoryExists(project.basePath)) { return StatsTableModel(arrayOf(), arrayOf()) } val gitUtils = GitUtils(project) val userStats = gitUtils.getTopSpeedUserStats( SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime), SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime), settingModel ) val data = userStats.map { item -> arrayOf( item.author, item.addedLines.toString(), item.deletedLines.toString(), item.modifiedFileCount.toString() ) }.toTypedArray() return StatsTableModel( data, arrayOf("Author", "AddedLines", "DeletedLines", "ModifiedFileCount") ) } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/toolWindow/GitStatsWindowFactory.kt ================================================ package com.huayi.intellijplatform.gitstats.toolWindow import com.huayi.intellijplatform.gitstats.MyBundle import com.huayi.intellijplatform.gitstats.components.SettingAction import com.huayi.intellijplatform.gitstats.models.SettingModel import com.huayi.intellijplatform.gitstats.services.GitStatsService import com.huayi.intellijplatform.gitstats.utils.Utils import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.components.* import com.intellij.ui.content.ContentFactory import com.intellij.ui.table.JBTable import com.michaelbaranov.microba.calendar.DatePicker import java.awt.BorderLayout import java.awt.CardLayout import java.awt.Dimension import java.awt.Font import java.util.* import javax.swing.* import kotlin.concurrent.thread class GitStatsWindowFactory : ToolWindowFactory { // init { // thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.") // } private val contentFactory = ContentFactory.SERVICE.getInstance() override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val gitStatsWindow = GitStatsWindow(toolWindow) val content = contentFactory.createContent(gitStatsWindow.getContent(toolWindow), null, false) toolWindow.contentManager.addContent(content) } override fun shouldBeAvailable(project: Project) = true class GitStatsWindow(toolWindow: ToolWindow) { private val service = toolWindow.project.service() fun getContent(toolWindow: ToolWindow) = JBPanel>(BorderLayout()).apply { var (startTime, endTime) = Utils.getThisWeekDateTimeRange() val settingModel = SettingModel().apply { mode = "Top-speed" exclude = "" } val table = JBTable().apply { font = Font("Microsoft YaHei", Font.PLAIN, 14) tableHeader.font = Font("Microsoft YaHei", Font.BOLD, 14) border = BorderFactory.createEmptyBorder(0, 0, 0, 0) columnSelectionAllowed = false rowSelectionAllowed = true rowHeight = 30 setSelectionMode(ListSelectionModel.SINGLE_SELECTION) } var refreshButton: JButton border = BorderFactory.createEmptyBorder(0, 0, 0, 0) val contentPanel = JBPanel>().apply { val tablePanel = JBScrollPane(table).apply { isFocusable = false border = BorderFactory.createEmptyBorder(0, 0, 0, 0) } add(tablePanel) val loadingPanel = JBLoadingPanel(BorderLayout(), toolWindow.project).also { it.startLoading() } add(loadingPanel) layout = CardLayout().also { it.addLayoutComponent(tablePanel, "content_table") it.addLayoutComponent(loadingPanel, "content_loading") } } val headerPanel = JBPanel>().apply { layout = BoxLayout(this, BoxLayout.X_AXIS) add(JBBox.createHorizontalStrut(10)) add(JBLabel(MyBundle.message("filterStartTimeLabel", ""))) // add(LocalDateTimePicker(LocalDateTime.now())) // datePicker.dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // add(CalendarView()) // val datePicker = JXDatePicker() // datePicker.date = Date() // add(DatePicker(Date.from(startTime.atStartOfDay(ZoneId.systemDefault()).toInstant())).apply { add(DatePicker(startTime).apply { isDropdownFocusable = false // isFieldEditable = false val size = Dimension(200, preferredSize.height) preferredSize = size maximumSize = size minimumSize = size isShowNoneButton = false isShowNumberOfWeek = true isStripTime = true components.last().preferredSize = Dimension(30, 30) addPropertyChangeListener { if (it.propertyName == "date" && it.newValue != null) { startTime = it.newValue as Date } } }) add(JBBox.createHorizontalStrut(10)) add(JBLabel(MyBundle.message("filterEndTimeLabel", ""))) add(DatePicker(endTime).apply { isDropdownFocusable = false val size = Dimension(200, preferredSize.height) preferredSize = size maximumSize = size minimumSize = size isShowNoneButton = false isShowNumberOfWeek = true isStripTime = true components.last().preferredSize = Dimension(30, 30) addPropertyChangeListener { if (it.propertyName == "date" && it.newValue != null) { val calendar = Calendar.getInstance() calendar.time = (it.newValue as Date) calendar[Calendar.HOUR_OF_DAY] = 23 calendar[Calendar.MINUTE] = 59 calendar[Calendar.SECOND] = 59 calendar[Calendar.MILLISECOND] = 999 endTime = calendar.time } } }) // add(LoadingButton(MyBundle.message("refreshButtonLabel"))) refreshButton = JButton(MyBundle.message("refreshButtonLabel"), AllIcons.Actions.Refresh).apply { addActionListener { (contentPanel.layout as CardLayout).show(contentPanel, "content_loading") isEnabled = false text = MyBundle.message("refreshButtonLoadingLabel") thread { if (settingModel.mode === "Top-speed") { table.model = service.getTopSpeedUserStats(startTime, endTime, settingModel) } else { table.model = service.getUserStats(startTime, endTime, settingModel) } SwingUtilities.invokeLater { (contentPanel.layout as CardLayout).show(contentPanel, "content_table") isEnabled = true text = MyBundle.message("refreshButtonLabel") } } } doClick() } add(refreshButton) add(Box.createHorizontalGlue()) // add(IconLabelButton(AllIcons.General.Settings) { // SettingDialogWrapper().showAndGet() // }.apply { // toolTipText = MyBundle.message("settingButtonTooltipText") // }) // add(JBBox.createHorizontalStrut(10)) } add(headerPanel, BorderLayout.NORTH) add(contentPanel, BorderLayout.CENTER) val actionList: MutableList = ArrayList() val settingAction = SettingAction(MyBundle.message("settingButtonTooltipText"), settingModel) { value -> settingModel.mode = value.mode settingModel.exclude = value.exclude refreshButton.doClick() } actionList.add(settingAction) toolWindow.setTitleActions(actionList) } } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/toolWindow/StatsTableModel.kt ================================================ package com.huayi.intellijplatform.gitstats.toolWindow import javax.swing.table.DefaultTableModel class StatsTableModel(data: Array>, columnNames: Array) : DefaultTableModel(data, columnNames) { override fun isCellEditable(row: Int, column: Int): Boolean { return false } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/utils/GitUtils.kt ================================================ package com.huayi.intellijplatform.gitstats.utils import git4idea.config.GitExecutableManager import git4idea.config.GitExecutableDetector import java.util.concurrent.TimeUnit import com.intellij.openapi.project.Project import com.huayi.intellijplatform.gitstats.models.SettingModel data class UserStats( val author: String, var addedLines: Int = 0, var deletedLines: Int = 0, var modifiedFileCount: Int = 0, var commitCount: Int = 0, var commits: MutableList = mutableListOf() ) data class CommitStats( val hash: String, val date: String, var addedLines: Int = 0, var deletedLines: Int = 0, var modifiedFileCount: Int = 0, var files: MutableList = mutableListOf() ) data class CommitFilesStats( var addedLines: Int = 0, var deletedLines: Int = 0, var fileName: String ) class GitUtils(project: Project) { private val gitExecutablePath: String = GitExecutableManager.getInstance().getExecutable(project).exePath private val basePath: String = project.basePath as String // private val basePath: String = "/Users/sunzhenxuan/work/qcc/code/qcc_pro/pro-front" private val gitBashExecutablePath: String? = GitExecutableDetector.getBashExecutablePath(gitExecutablePath) // init { // } // companion object { // fun getGitExecutablePath(project: Project): String { // return GitExecutableManager.getInstance().getExecutable(project).exePath // } // } fun getTopSpeedUserStats( startDate: String, endDate: String, settingModel: SettingModel ): Array { val timeoutAmount = 60L val timeUnit = TimeUnit.SECONDS val os = Utils.getOS() val commands = mutableListOf() val folder = if (settingModel.exclude.isEmpty()) "." else ". ':(exclude)${settingModel.exclude}'" when { os == "Windows" && gitBashExecutablePath?.isNotEmpty() ?: false -> { commands += gitBashExecutablePath!! commands += "-c" commands += "git log --format=\"%aN\" | sort -u | while read name; do echo \"\$name\"; git log --author=\\\"\$name\\\" --pretty=tformat: --since=\\\"${startDate}\\\" --until=\\\"${endDate}\\\" --numstat -- $folder | awk '{ add += \$1; subs += \$2; file++ } END { printf(\\\"added lines: %s, removed lines: %s, modified files: %s\\n\\\", add ? add : 0, subs ? subs : 0, file ? file : 0) }' -; done" } os == "Windows" && gitBashExecutablePath?.isEmpty() ?: false -> { commands += "powershell" commands += "/c" // commands += "C:\\\"Program Files\"\\Git\\cmd\\git.exe log --format='%aN' | sort -u | % { $name=$_; Write-Output $name; git log --author=$name --pretty=tformat: --since='2023-05-15 00:00:00' --until='2023-05-21 23:59:59' --numstat | ? { $_ -match '\\d' } | % { $add += [int]$_.Split()[0]; $subs += [int]$_.Split()[1]; $files++ } ; Write-Output ( 'added lines: ' + $add + ', removed lines: ' + $subs + ', modified files: ' + $files ) }" } else -> { commands += "/bin/sh" commands += "-c" commands += "$gitExecutablePath log --format=\"%aN\" | sort -u | while read name; do echo \"\$name\"; git log --author=\"\$name\" --pretty=\"tformat:\" --since=\"$startDate\" --until=\"$endDate\" --numstat -- $folder | awk '{ add += \$1; subs += \$2; file++ } END { printf \"added lines: %s, removed lines: %s, modified files: %s\\n\", add ? add : 0, subs ? subs : 0, file ? file : 0 }' -; done" } } val process = Utils.runCommand(basePath, commands, timeoutAmount, timeUnit) val regex = Regex("(.+)\\n+added lines: (\\d*), removed lines: (\\d+), modified files: (\\d+)") return regex.findAll(process!!.inputStream.bufferedReader().readText()) .map { result -> val (author, addedLines, deletedLines, modifiedFileCount) = result.destructured UserStats(author, addedLines.toInt(), deletedLines.toInt(), modifiedFileCount.toInt()) }.sortedByDescending { it.addedLines }.toList().toTypedArray() } fun getUserStats( startDate: String, endDate: String, settingModel: SettingModel ): Array { val timeoutAmount = 60L val timeUnit = TimeUnit.SECONDS val separator = "--" val os = Utils.getOS() val commands = mutableListOf() val folder = if (settingModel.exclude.isEmpty()) "." else ". ':(exclude)${settingModel.exclude}'" if (os == "Windows" && gitBashExecutablePath?.isNotEmpty() == true) { commands += gitBashExecutablePath commands += "-c" commands += "git log --numstat --pretty=\"format:${separator}%h${separator}%ad${separator}%aN\" --since=\\\"${startDate}\\\" --until=\\\"${endDate}\\\" -- $folder" } else { commands += "/bin/sh" commands += "-c" commands += "$gitExecutablePath log --numstat --pretty=\"format:${separator}%h${separator}%ad${separator}%aN\" --since=\"$startDate\" --until=\"$endDate\" -- $folder" } val process = Utils.runCommand(basePath, commands, timeoutAmount, timeUnit) val userStatsData = mutableMapOf() process!!.inputStream.bufferedReader().use { reader -> var currentUserStatsData: UserStats? = null reader.forEachLine { line -> if (line.startsWith(separator)) { val (_, hash, date, author) = line.split(separator) currentUserStatsData = userStatsData.getOrPut(author) { UserStats(author) }.apply { commitCount++ commits.add(CommitStats(hash, date)) } return@forEachLine } if (line.isNotEmpty()) { val commitFilesStatsData = line.split("\t").let { CommitFilesStats(it[0].toIntOrNull() ?: 0, it[1].toIntOrNull() ?: 0, it[2]) } currentUserStatsData!!.let { userStats -> userStats.apply { addedLines += commitFilesStatsData.addedLines deletedLines += commitFilesStatsData.deletedLines modifiedFileCount++ } userStats.commits.last().let { commitStats -> commitStats.apply { files.add(commitFilesStatsData) addedLines += commitFilesStatsData.addedLines deletedLines += commitFilesStatsData.deletedLines modifiedFileCount++ } } } } } } return userStatsData.values.toTypedArray() } } ================================================ FILE: src/main/kotlin/com/huayi/intellijplatform/gitstats/utils/Utils.kt ================================================ package com.huayi.intellijplatform.gitstats.utils import com.intellij.openapi.diagnostic.thisLogger import java.io.File import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.TemporalAdjusters import java.util.* import java.util.concurrent.TimeUnit object Utils { fun checkDirectoryExists(directoryPath: String?): Boolean { if (directoryPath.isNullOrEmpty()) { return false } val directory = File(directoryPath) return directory.exists() && directory.isDirectory } fun getOS(): String { val os = System.getProperty("os.name").lowercase(Locale.getDefault()) return if (os.contains("win")) { "Windows" } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) { "Unix" } else if (os.contains("mac")) { "OSX" } else { "Unknown" } } fun runCommand( repoPath: String, cmd: List, timeoutAmount: Long = 60L, timeUnit: TimeUnit = TimeUnit.SECONDS ): Process? { return runCatching { ProcessBuilder(cmd) .directory(File(repoPath)) .redirectErrorStream(true) .redirectOutput(ProcessBuilder.Redirect.PIPE) .start().also { it.waitFor(timeoutAmount, timeUnit) } }.onFailure { thisLogger().info(it.printStackTrace().toString()) }.getOrNull() } fun runCommand(repoPath: String, vararg cmd: String): Process? = runCommand(repoPath, listOf(*cmd)) fun getThisWeekDateRange(): Pair { val now = LocalDate.now() val startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) val endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)) return Pair(startOfWeek, endOfWeek) } fun getThisWeekDateTimeRange(): Pair { val calendar = Calendar.getInstance() val today = calendar.time calendar.firstDayOfWeek = Calendar.MONDAY calendar.time = today calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY) calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY)) calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE)) calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND)) calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND)) val startOfWeek = calendar.time calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY) calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY)) calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE)) calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND)) calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND)) val endOfWeek = calendar.time return Pair(startOfWeek, endOfWeek) } } ================================================ FILE: src/main/resources/META-INF/plugin.xml ================================================ com.huayi.intellijplatform.gitstats GitStats huayi com.intellij.modules.platform com.intellij.modules.vcs Git4Idea messages.MyBundle ================================================ FILE: src/main/resources/messages/MyBundle.properties ================================================ name=GitStats projectService=Project service: {0} randomLabel=The random number is: {0} shuffle=Shuffle filterStartTimeLabel=StartTime: {0} filterEndTimeLabel=EndTime: {0} refreshButtonLabel=Refresh refreshButtonLoadingLabel=Loading settingButtonTooltipText=Show Setting settingDialogModeLabel=Mode: settingDialogExcludeLabel=Exclude: ================================================ FILE: src/test/kotlin/com/huayi/intellijplatform/gitstats/MyPluginTest.kt ================================================ package com.huayi.intellijplatform.gitstats import com.intellij.ide.highlighter.XmlFileType //import com.intellij.openapi.components.service import com.intellij.psi.xml.XmlFile import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.PsiErrorElementUtil //import com.huayi.intellijplatform.gitstats.services.GitStatsService @TestDataPath("\$CONTENT_ROOT/src/test/testData") class MyPluginTest : BasePlatformTestCase() { fun testXMLFile() { val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "bar") val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java) assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile)) assertNotNull(xmlFile.rootTag) xmlFile.rootTag?.let { assertEquals("foo", it.name) assertEquals("bar", it.value.text) } } fun testRename() { myFixture.testRename("foo.xml", "foo_after.xml", "a2") } // fun testProjectService() { // val projectService = project.service() // // assertNotSame(projectService.getRandomNumber(), projectService.getRandomNumber()) // } override fun getTestDataPath() = "src/test/testData/rename" } ================================================ FILE: src/test/testData/rename/foo.xml ================================================ 1>Foo ================================================ FILE: src/test/testData/rename/foo_after.xml ================================================ Foo