├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle.kts ├── detekt-config.yml ├── doc ├── gutter.png ├── install-plugin.png ├── intellij-k6-plugin-cloud-token.png ├── intellij-k6-plugin-file-option.png ├── intellij-k6-plugin-run-output.png ├── intellij-k6-plugin-search-commands.png ├── intellij-k6-plugin-shortcuts.png ├── run-from-context-menu.png ├── thresholds-as-tests.gif ├── thresholds-as-tests.png └── typescript-before.png ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main ├── kotlin └── io │ └── k6 │ └── ide │ └── plugin │ ├── K6ProjectListener.kt │ ├── actions │ └── RunK6Action.kt │ ├── icons.kt │ ├── run │ ├── K6ConfigurableEditor.form │ ├── config.kt │ ├── produce.kt │ ├── state.kt │ └── ui.kt │ └── settings │ └── settings.kt └── resources ├── META-INF ├── plugin-js.xml ├── plugin.xml └── pluginIcon.svg ├── icons └── k6_16x16.png └── wrapper.js /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | out 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # k6 IntelliJ Plugin Changelog 4 | 5 | ## [0.3.0] 6 | ### Added 7 | - Support relative script path (issue #3) 8 | 9 | ## [0.2.3] 10 | ### Added 11 | - 2021.3 Platform version supported 12 | 13 | ## [0.2.2] 14 | ### Added 15 | - 2021.2 Platform version supported 16 | 17 | ## [0.2.1] 18 | ### Fixed 19 | - Unable to start a run configuration on Mac OS 20 | 21 | ## [0.2.0] 22 | ### Added 23 | - 'Show thresholds as tests' option in run configuration 24 | 25 | ## [0.1.0] 26 | ### Added 27 | - k6 Run configuration 28 | - create run configuration from file or function 29 | - show pass/failed run in the test console 30 | - console output with colors 31 | ### Fixed 32 | - default shortcut for the "run file locally" action was changed from 'shift+K' to 'ctrl+shift+K' so as not conflicting when typing a capital 'K' in the editor 33 | ## [0.0.1] 34 | ### Added 35 | - Run script locally / in the cloud 36 | - Detection of k6 installation 37 | - Could token setting 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | IntelliJ-based Plugin to run [k6 tests](https://k6.io/) locally or in the [k6 Cloud](https://k6.io/cloud) from your IntelliJ IDE. 4 | 5 | - Run a k6 test as a Run configuration (a common way to run something withing IntelliJ platform) 6 | - Run a k6 test using keyboard shortcuts. 7 | - Run a k6 test from the search Menu. 8 | - Run a k6 test from the popup file menu. 9 | - Visualize the k6 results in the Run tool window. 10 | 11 | 12 | 13 | 14 | ## How it works 15 | 16 | This plugin allows running a k6 test in the 4 different ways: 17 | 18 | ### Run the test as a Run configuration. 19 | 20 | A k6 run configuration can be created in several ways: 21 | * By clicking on a green run gutter near the `default function` in the editor: ![img.png](doc/gutter.png) 22 | * Via the context menu of a k6 test file 23 | * Using the `Run/Debug Configurations` dialog window 24 | 25 | Once a run configuration is created, it can be used multiple times to execute the test. 26 | 27 | Beside the test path itself, a run configuration can define some other properties to be used to execute the test: 28 | * `Local`/`Cloud` run type selection 29 | * Additional CLI parameters, like `--vus 10` 30 | * Additional environmental variables 31 | * Define whether to show each threshold as a separate test in the test console by selecting the `Show thresholds as tests` checkbox 32 | 33 | Default values for each of the properties can be defined via a `Run configuration template`. 34 | 35 | ### Run the test from the popup file menu. 36 | 37 | Select the test file, open the file options and click on `k6: run current file` or `k6: run current file in k6 cloud`. 38 | 39 | ![k6 Cloud File Options](doc/intellij-k6-plugin-file-option.png) 40 | 41 | ### Run the test from the Search Menu. 42 | 43 | From the main menu, select Navigate | Search Everywhere or press `Shift` twice to open the search window. Search for `k6` and trigger `k6: run current file` or `k6: run current file in k6 cloud`. 44 | 45 | ![k6 Search Commands](doc/intellij-k6-plugin-search-commands.png) 46 | 47 | ### Run the test using keyboard shortcuts. 48 | 49 | By default, `Alt+K` for running local tests, and `Alt+Shift+K` for cloud tests. 50 | 51 | ![k6 Shortcuts](doc/intellij-k6-plugin-shortcuts.png) 52 | 53 | 54 | When IntelliJ IDEA runs a k6 test, the [Run tool window](https://www.jetbrains.com/help/idea/run-tool-window.html) will display the test results generated by k6. 55 | 56 | ![k6 Output](doc/intellij-k6-plugin-run-output.png) 57 | 58 | For running cloud tests, set your [k6 Cloud Token](https://app.k6.io/account/token) in `Settings/Preferences/Tools/k6`. 59 | 60 | ![k6 Cloud Token](doc/intellij-k6-plugin-cloud-token.png) 61 | 62 | 63 | ## Run a test written in TypeScript 64 | 65 | k6 does not support running a typescript test directly. To execute both build task and run test actions **in one click** you can define a `Run configuration` 66 | to run your *compiled js test* and to execute a npm build script before launch: 67 | 68 | ![img.png](doc/typescript-before.png) 69 | 70 | ## Show thresholds as tests 71 | When `Show thresholds as tests` checkbox is selected in a run configuration, the plugin will display each configured threshold as a passed or failed test inside the test console tree view: 72 | 73 | ![thresholds as tests](doc/thresholds-as-tests.gif) 74 | Each of the threshold entry is clickable and navigates to the threshold source element by double click (or key shortcut). 75 | Under the hood, the plugin utilises `handleSummary` callback to collect the test execution results, so it has to wrap original script and proxy the calls. 76 | 77 | ## Installation 78 | 79 | - In the Settings/Preferences dialog, select Plugins. 80 | - Use the Marketplace tab to find the k6 plugin. 81 | - Click install. 82 | - Enjoy! 83 | 84 | ### Build plugin from the sources 85 | 86 | ```bash 87 | ./gradlew buildPlugin 88 | ```` 89 | Install plugin from local file system via the following menu item: 90 | ![img.png](doc/install-plugin.png) 91 | 92 | ### Start IDE bundled with plugin via gradle: 93 | 94 | ```bash 95 | ./gradlew runIde 96 | ``` 97 | 98 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.changelog.markdownToHTML 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | fun properties(key: String) = project.findProperty(key).toString() 5 | 6 | plugins { 7 | // Java support 8 | id("java") 9 | // Kotlin support 10 | id("org.jetbrains.kotlin.jvm") version "1.5.30" 11 | // Gradle IntelliJ Plugin 12 | id("org.jetbrains.intellij") version "1.1.6" 13 | // Gradle Changelog Plugin 14 | id("org.jetbrains.changelog") version "1.3.0" 15 | // Gradle Qodana Plugin 16 | id("org.jetbrains.qodana") version "0.1.12" 17 | } 18 | 19 | group = properties("pluginGroup") 20 | version = properties("pluginVersion") 21 | 22 | // Configure project's dependencies 23 | repositories { 24 | mavenCentral() 25 | } 26 | 27 | // Configure Gradle IntelliJ Plugin - read more: https://github.com/JetBrains/gradle-intellij-plugin 28 | intellij { 29 | pluginName.set(properties("pluginName")) 30 | version.set(properties("platformVersion")) 31 | type.set(properties("platformType")) 32 | downloadSources.set(properties("platformDownloadSources").toBoolean()) 33 | updateSinceUntilBuild.set(false) 34 | 35 | // Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file. 36 | plugins.set(properties("platformPlugins").split(',').map(String::trim).filter(String::isNotEmpty)) 37 | } 38 | 39 | // Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin 40 | changelog { 41 | version.set(properties("pluginVersion")) 42 | groups.set(emptyList()) 43 | } 44 | 45 | // Configure Gradle Qodana Plugin - read more: https://github.com/JetBrains/gradle-qodana-plugin 46 | qodana { 47 | cachePath.set(projectDir.resolve(".qodana").canonicalPath) 48 | reportPath.set(projectDir.resolve("build/reports/inspections").canonicalPath) 49 | saveReport.set(true) 50 | showReport.set((System.getenv("QODANA_SHOW_REPORT") ?: "false").toBoolean()) 51 | } 52 | 53 | tasks { 54 | // Set the JVM compatibility versions 55 | properties("javaVersion").let { 56 | withType { 57 | sourceCompatibility = it 58 | targetCompatibility = it 59 | } 60 | withType { 61 | kotlinOptions.jvmTarget = it 62 | } 63 | } 64 | 65 | wrapper { 66 | gradleVersion = properties("gradleVersion") 67 | } 68 | 69 | patchPluginXml { 70 | version.set(properties("pluginVersion")) 71 | sinceBuild.set(properties("pluginSinceBuild")) 72 | // untilBuild.set(properties("pluginUntilBuild")) 73 | 74 | // Extract the section from README.md and provide for the plugin's manifest 75 | pluginDescription.set( 76 | projectDir.resolve("README.md").readText().lines().run { 77 | val start = "" 78 | val end = "" 79 | 80 | if (!containsAll(listOf(start, end))) { 81 | throw GradleException("Plugin description section not found in README.md:\n$start ... $end") 82 | } 83 | subList(indexOf(start) + 1, indexOf(end)) 84 | }.joinToString("\n").run { markdownToHTML(this) } 85 | ) 86 | 87 | // Get the latest available change notes from the changelog file 88 | changeNotes.set( 89 | provider { 90 | changelog.run { 91 | getOrNull(properties("pluginVersion")) ?: getLatest() 92 | }.toHTML() 93 | } 94 | ) 95 | } 96 | 97 | runPluginVerifier { 98 | ideVersions.set(properties("pluginVerifierIdeVersions").split(',').map(String::trim).filter(String::isNotEmpty)) 99 | } 100 | 101 | // Configure UI tests plugin 102 | // Read more: https://github.com/JetBrains/intellij-ui-test-robot 103 | runIdeForUiTests { 104 | systemProperty("robot-server.port", "8082") 105 | systemProperty("ide.mac.message.dialogs.as.sheets", "false") 106 | systemProperty("jb.privacy.policy.text", "") 107 | systemProperty("jb.consents.confirmation.enabled", "false") 108 | } 109 | 110 | signPlugin { 111 | certificateChain.set(System.getenv("CERTIFICATE_CHAIN")) 112 | privateKey.set(System.getenv("PRIVATE_KEY")) 113 | password.set(System.getenv("PRIVATE_KEY_PASSWORD")) 114 | } 115 | 116 | publishPlugin { 117 | dependsOn("patchChangelog") 118 | token.set(System.getenv("PUBLISH_TOKEN")) 119 | // pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 120 | // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: 121 | // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel 122 | channels.set(listOf(properties("pluginVersion").split('-').getOrElse(1) { "default" }.split('.').first())) 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /detekt-config.yml: -------------------------------------------------------------------------------- 1 | # Default detekt configuration: 2 | # https://github.com/detekt/detekt/blob/master/detekt-core/src/main/resources/default-detekt-config.yml 3 | 4 | formatting: 5 | Indentation: 6 | continuationIndentSize: 8 7 | ParameterListWrapping: 8 | indentSize: 8 9 | -------------------------------------------------------------------------------- /doc/gutter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/gutter.png -------------------------------------------------------------------------------- /doc/install-plugin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/install-plugin.png -------------------------------------------------------------------------------- /doc/intellij-k6-plugin-cloud-token.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/intellij-k6-plugin-cloud-token.png -------------------------------------------------------------------------------- /doc/intellij-k6-plugin-file-option.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/intellij-k6-plugin-file-option.png -------------------------------------------------------------------------------- /doc/intellij-k6-plugin-run-output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/intellij-k6-plugin-run-output.png -------------------------------------------------------------------------------- /doc/intellij-k6-plugin-search-commands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/intellij-k6-plugin-search-commands.png -------------------------------------------------------------------------------- /doc/intellij-k6-plugin-shortcuts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/intellij-k6-plugin-shortcuts.png -------------------------------------------------------------------------------- /doc/run-from-context-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/run-from-context-menu.png -------------------------------------------------------------------------------- /doc/thresholds-as-tests.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/thresholds-as-tests.gif -------------------------------------------------------------------------------- /doc/thresholds-as-tests.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/thresholds-as-tests.png -------------------------------------------------------------------------------- /doc/typescript-before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/doc/typescript-before.png -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # IntelliJ Platform Artifacts Repositories 2 | # -> https://plugins.jetbrains.com/docs/intellij/intellij-artifacts.html 3 | 4 | pluginGroup = io.k6.ide.plugin 5 | pluginName_ = k6 6 | pluginVersion = 0.3.0 7 | 8 | # See https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html 9 | # for insight into build numbers and IntelliJ Platform versions. 10 | pluginSinceBuild = 203 11 | #pluginUntilBuild = 213.* 12 | 13 | # Plugin Verifier integration -> https://github.com/JetBrains/gradle-intellij-plugin#plugin-verifier-dsl 14 | # See https://jb.gg/intellij-platform-builds-list for available build versions. 15 | pluginVerifierIdeVersions = 2020.3.4, 2021.1.3, 2021.2.1, 2021.3.1 16 | 17 | platformType = IU 18 | platformVersion = 2023.1 19 | platformDownloadSources = true 20 | 21 | # Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html 22 | # Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22 23 | platformPlugins = JavaScript 24 | 25 | # Java language level used to compile sources and to generate the files for - Java 11 is required since 2020.3 26 | javaVersion = 17 27 | 28 | gradleVersion = 7.6 29 | 30 | # Opt-out flag for bundling Kotlin standard library. 31 | # See https://plugins.jetbrains.com/docs/intellij/kotlin.html#kotlin-standard-library for details. 32 | # suppress inspection "UnusedProperty" 33 | kotlin.stdlib.default.dependency = false 34 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "k6" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/K6ProjectListener.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin 2 | 3 | import com.intellij.execution.configurations.GeneralCommandLine 4 | import com.intellij.execution.process.OSProcessHandler 5 | import com.intellij.ide.BrowserUtil 6 | import com.intellij.notification.Notification 7 | import com.intellij.notification.NotificationAction 8 | import com.intellij.notification.NotificationType 9 | import com.intellij.notification.Notifications 10 | import com.intellij.openapi.actionSystem.AnActionEvent 11 | import com.intellij.openapi.progress.runBackgroundableTask 12 | import com.intellij.openapi.project.Project 13 | import com.intellij.openapi.project.ProjectManagerListener 14 | import io.k6.ide.plugin.actions.K6_NOTIFICATION_GROUP 15 | 16 | internal class K6ProjectListener : ProjectManagerListener { 17 | private val which = if (java.io.File.separatorChar == '\\') "where" else "which" 18 | private val installationUrl = "https://k6.io/docs/getting-started/installation" 19 | 20 | override fun projectOpened(project: Project) { 21 | val line = GeneralCommandLine(which, "k6") 22 | runBackgroundableTask("Check k6 Installation", project, false) { 23 | val found = run { 24 | try { 25 | val osProcessHandler = OSProcessHandler(line) 26 | osProcessHandler.startNotify() 27 | 28 | if (!osProcessHandler.waitFor(5000)) return@run false 29 | return@run osProcessHandler.exitCode == 0 30 | } catch (e: Exception) { 31 | false 32 | } 33 | } 34 | if (!found) { 35 | val msg = "Could not find any installation of k6 on your system. For this plugin to work, make sure it is available in your PATH" 36 | Notifications.Bus.notify(Notification(K6_NOTIFICATION_GROUP, "", msg, NotificationType.INFORMATION) 37 | .addAction(object : NotificationAction("Go to k6 installation page") { 38 | override fun actionPerformed(e: AnActionEvent, notification: Notification) { 39 | BrowserUtil.browse(installationUrl) 40 | } 41 | })) 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/actions/RunK6Action.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin.actions 2 | 3 | import com.intellij.execution.RunContentExecutor 4 | import com.intellij.execution.configurations.GeneralCommandLine 5 | import com.intellij.execution.process.OSProcessHandler 6 | import com.intellij.ide.projectView.impl.ProjectViewTree 7 | import com.intellij.ide.projectView.impl.nodes.PsiFileNode 8 | import com.intellij.notification.Notification 9 | import com.intellij.notification.NotificationAction 10 | import com.intellij.notification.NotificationType 11 | import com.intellij.notification.Notifications 12 | import com.intellij.openapi.actionSystem.AnAction 13 | import com.intellij.openapi.actionSystem.AnActionEvent 14 | import com.intellij.openapi.actionSystem.PlatformDataKeys 15 | import com.intellij.openapi.options.ShowSettingsUtil 16 | import com.intellij.openapi.project.Project 17 | import com.intellij.openapi.project.guessProjectDir 18 | import com.intellij.openapi.vfs.VirtualFile 19 | import io.k6.ide.plugin.run.isK6Supported 20 | import io.k6.ide.plugin.settings.K6Settings 21 | import io.k6.ide.plugin.settings.K6SettingsConfigurable 22 | import java.nio.charset.Charset 23 | import javax.swing.tree.DefaultMutableTreeNode 24 | 25 | const val TOKEN_ENV_NAME = "K6_CLOUD_TOKEN" 26 | const val K6_NOTIFICATION_GROUP = "k6" 27 | 28 | open class RunK6ActionBase(private val command: String) : AnAction() { 29 | 30 | override fun update(e: AnActionEvent) { 31 | if (e.extractSupportedFile() == null) { 32 | e.presentation.isVisible = false 33 | } 34 | } 35 | 36 | open fun configureCommandLine(project: Project, commandLine: GeneralCommandLine) = true 37 | 38 | override fun actionPerformed(e: AnActionEvent) { 39 | val file = e.extractSupportedFile()?.also { if (!it.isInLocalFileSystem) { 40 | showBalloon("The k6 plugin currently only works with files saved on disk") 41 | return 42 | } } ?: return 43 | val project = e.project ?: return 44 | val generalCommandLine = GeneralCommandLine("k6", command, file.path) 45 | generalCommandLine.charset = Charset.forName("UTF-8") 46 | project.guessProjectDir()?.let { 47 | generalCommandLine.setWorkDirectory(it.path) 48 | } 49 | 50 | if (!configureCommandLine(project, generalCommandLine)) { 51 | return 52 | } 53 | 54 | val processHandler = try { 55 | OSProcessHandler(generalCommandLine) 56 | } catch (e: Exception) { 57 | showBalloon("Unable to start k6: ${e.localizedMessage}") 58 | return 59 | } 60 | RunContentExecutor(project, processHandler).run() 61 | } 62 | 63 | private fun showBalloon(msg: String) { 64 | Notifications.Bus.notify(Notification(K6_NOTIFICATION_GROUP, "", msg, NotificationType.INFORMATION)) 65 | } 66 | } 67 | 68 | class RunK6Action : RunK6ActionBase("run") 69 | 70 | class RunK6CloudAction : RunK6ActionBase("cloud") { 71 | override fun configureCommandLine(project: Project, commandLine: GeneralCommandLine) : Boolean { 72 | val token = K6Settings.instance.cloudToken.takeIf { it.isNotBlank() } ?: commandLine.effectiveEnvironment[TOKEN_ENV_NAME] ?: run { 73 | val msg = "This option requires you to either have a cloud token added in your environment variables or in the k6 plugin settings" 74 | Notifications.Bus.notify(Notification(K6_NOTIFICATION_GROUP, "No cloud token", msg, NotificationType.ERROR) 75 | .addAction(object : NotificationAction("Edit settings") { 76 | override fun actionPerformed(e: AnActionEvent, notification: Notification) { 77 | ShowSettingsUtil.getInstance().editConfigurable(project, K6SettingsConfigurable()) 78 | } 79 | })) 80 | return false 81 | } 82 | commandLine.environment[TOKEN_ENV_NAME] = token 83 | return true 84 | } 85 | } 86 | 87 | private fun AnActionEvent.extractSupportedFile() = extractFile()?.takeIf { it.isK6Supported() } 88 | 89 | private fun AnActionEvent.extractFile() : VirtualFile? { 90 | getData(PlatformDataKeys.FILE_EDITOR)?.file?.let { return it } 91 | (getData(PlatformDataKeys.CONTEXT_COMPONENT) as? ProjectViewTree)?.selectionPath?.lastPathComponent?.let { 92 | ((it as? PsiFileNode)?.virtualFile ?: ((it as? DefaultMutableTreeNode)?.userObject as? PsiFileNode)?.virtualFile)?.let { return it } 93 | } 94 | 95 | return null 96 | } 97 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/icons.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin 2 | 3 | import com.intellij.openapi.util.IconLoader 4 | 5 | object K6Icons { 6 | val k6 = IconLoader.getIcon("/icons/k6_16x16.png", K6Icons::class.java) 7 | } 8 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/run/K6ConfigurableEditor.form: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 |
104 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/run/config.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin.run 2 | 3 | import com.devexperts.K6.plug.idea.run.K6ConfigurableEditorPanel 4 | import com.intellij.execution.Executor 5 | import com.intellij.execution.configuration.EnvironmentVariablesComponent 6 | import com.intellij.execution.configurations.* 7 | import com.intellij.execution.runners.ExecutionEnvironment 8 | import com.intellij.openapi.options.SettingsEditor 9 | import com.intellij.openapi.options.ShowSettingsUtil 10 | import com.intellij.openapi.project.Project 11 | import com.intellij.openapi.project.guessProjectDir 12 | import com.intellij.openapi.vfs.VfsUtilCore 13 | import com.intellij.openapi.vfs.VirtualFile 14 | import com.intellij.util.xmlb.XmlSerializer 15 | import io.k6.ide.plugin.K6Icons 16 | import io.k6.ide.plugin.actions.TOKEN_ENV_NAME 17 | import io.k6.ide.plugin.settings.K6Settings 18 | import io.k6.ide.plugin.settings.K6SettingsConfigurable 19 | import org.jdom.Element 20 | import org.jetbrains.io.LocalFileFinder 21 | import java.io.File 22 | 23 | val supportedK6FileTypes = setOf("js") 24 | fun VirtualFile?.isK6Supported() = this?.extension in supportedK6FileTypes 25 | 26 | class K6RunConfigurationType : ConfigurationTypeBase("K6ConfigurationType", "k6", "Run k6 Script", K6Icons.k6) { 27 | init { 28 | addFactory(configurationFactory()) 29 | } 30 | 31 | private fun configurationFactory(): ConfigurationFactory { 32 | return object : ConfigurationFactory(this) { 33 | override fun createTemplateConfiguration(p: Project): RunConfiguration { 34 | return K6RunConfig(p, this) 35 | } 36 | 37 | override fun getIcon() = K6Icons.k6 38 | 39 | override fun isApplicable(project: Project): Boolean { 40 | return true 41 | } 42 | 43 | override fun getId(): String { 44 | return name 45 | } 46 | } 47 | } 48 | } 49 | 50 | class K6RunConfig(project: Project, factory: ConfigurationFactory) : 51 | LocatableConfigurationBase(project, factory, "") { 52 | 53 | var data = K6RunData() 54 | 55 | override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState? { 56 | return K6RunState(environment, this) 57 | } 58 | 59 | override fun getConfigurationEditor(): SettingsEditor { 60 | return K6ConfigurableEditorPanel(project) 61 | } 62 | 63 | override fun clone(): RunConfiguration { 64 | val res = super.clone() as K6RunConfig 65 | res.data = res.data.clone() 66 | return res 67 | } 68 | 69 | override fun readExternal(element: Element) { 70 | super.readExternal(element) 71 | XmlSerializer.deserializeInto(this, element) 72 | XmlSerializer.deserializeInto(data, element) 73 | 74 | EnvironmentVariablesComponent.readExternal(element, data.envs) 75 | } 76 | 77 | override fun writeExternal(element: Element) { 78 | super.writeExternal(element) 79 | XmlSerializer.serializeInto(this, element) 80 | XmlSerializer.serializeInto(data, element) 81 | 82 | EnvironmentVariablesComponent.writeExternal(element, data.envs) 83 | } 84 | 85 | override fun suggestedName(): String? { 86 | return getRelativePath(project, data.script ?: return null) 87 | } 88 | 89 | override fun getActionName(): String? { 90 | return getLastPathComponent(data.script ?: return null) 91 | } 92 | 93 | override fun checkConfiguration() { 94 | val scriptPath = data.getScriptPath(project) 95 | if (scriptPath?.isFile != true) { 96 | throw RuntimeConfigurationError("Script file does not exist: ${scriptPath}") 97 | } 98 | if (data.type == RunType.cloud) { 99 | if ((K6Settings.instance.cloudToken.takeIf { it.isNotBlank() } ?: System.getenv(TOKEN_ENV_NAME)) == null) { 100 | throw RuntimeConfigurationError( 101 | "The cloud execution mode requires you to either have a cloud token added in your environment variables or in the k6 plugin settings", 102 | Runnable { 103 | ShowSettingsUtil.getInstance().editConfigurable(project, K6SettingsConfigurable()) 104 | } 105 | ) 106 | } 107 | } 108 | } 109 | } 110 | 111 | fun getRelativePath(project: Project, path: String): String { 112 | val file = LocalFileFinder.findFile(path) 113 | if (file != null && file.isValid) { 114 | val root = project.guessProjectDir() 115 | if (root != null && root.isValid) { 116 | val relativePath = VfsUtilCore.getRelativePath(file, root, File.separatorChar) 117 | relativePath?.let { return relativePath } 118 | } 119 | } 120 | return getLastPathComponent(path) 121 | } 122 | 123 | private fun getLastPathComponent(path: String): String { 124 | val lastIndex = path.lastIndexOf('/') 125 | return if (lastIndex >= 0) path.substring(lastIndex + 1) else path 126 | } 127 | 128 | enum class RunType { local, cloud } 129 | 130 | class K6RunData : Cloneable { 131 | var script: String? = null 132 | 133 | var type = RunType.local 134 | 135 | var envs: MutableMap = LinkedHashMap() 136 | 137 | var additionalParams: String? = null 138 | 139 | var pty = true 140 | 141 | var thresholdsAsTests = true 142 | 143 | fun getScriptPath(project: Project) : File? { 144 | val script = script ?: return null 145 | File(script).takeIf { it.isAbsolute }?.let { return it } 146 | return File((project.guessProjectDir() ?: return null).toNioPath().toFile(), script) 147 | } 148 | 149 | public override fun clone(): K6RunData { 150 | try { 151 | val data = super.clone() as K6RunData 152 | data.envs = LinkedHashMap(envs) 153 | return data 154 | } catch (e: CloneNotSupportedException) { 155 | throw RuntimeException(e) 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/run/produce.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin.run 2 | 3 | import com.intellij.execution.actions.ConfigurationContext 4 | import com.intellij.execution.actions.LazyRunConfigurationProducer 5 | import com.intellij.execution.configurations.ConfigurationTypeUtil 6 | import com.intellij.execution.lineMarker.ExecutorAction 7 | import com.intellij.execution.lineMarker.RunLineMarkerContributor 8 | import com.intellij.icons.AllIcons 9 | import com.intellij.lang.ecmascript6.psi.ES6ExportDefaultAssignment 10 | import com.intellij.lang.javascript.JSKeywordElementType 11 | import com.intellij.lang.javascript.JSTokenTypes 12 | import com.intellij.lang.javascript.psi.JSFile 13 | import com.intellij.openapi.actionSystem.AnAction 14 | import com.intellij.openapi.util.Ref 15 | import com.intellij.openapi.util.text.StringUtil 16 | import com.intellij.openapi.vfs.LocalFileSystem 17 | import com.intellij.psi.PsiElement 18 | import com.intellij.psi.impl.source.tree.LeafElement 19 | import com.intellij.psi.util.PsiUtilCore 20 | import com.intellij.util.containers.ContainerUtil 21 | 22 | class K6Producer : LazyRunConfigurationProducer() { 23 | override fun getConfigurationFactory() = 24 | ConfigurationTypeUtil.findConfigurationType(K6RunConfigurationType::class.java).configurationFactories[0] 25 | 26 | override fun isConfigurationFromContext(configuration: K6RunConfig, context: ConfigurationContext): Boolean { 27 | val script = configuration.data.getScriptPath(context.project) ?: return false 28 | val file = context.location?.virtualFile ?: return false 29 | return file == LocalFileSystem.getInstance().findFileByIoFile(script) 30 | } 31 | 32 | override fun setupConfigurationFromContext( 33 | configuration: K6RunConfig, 34 | context: ConfigurationContext, 35 | sourceElement: Ref 36 | ): Boolean { 37 | val file = context.location?.virtualFile ?: return false 38 | if (!file.isK6Supported()) { 39 | return false 40 | } 41 | configuration.data.script = getRelativePath(context.project, file.path) 42 | configuration.setGeneratedName() 43 | return true 44 | } 45 | } 46 | 47 | class K6RunLineMarkerProvider : RunLineMarkerContributor() { 48 | private val allActions = ExecutorAction.getActions(0).filter { it.toString().startsWith("Run context configuration") }.toTypedArray() 49 | 50 | override fun getInfo(e: PsiElement): Info? { 51 | if (e !is LeafElement || e.containingFile !is JSFile || !e.containingFile.virtualFile.isK6Supported()) { 52 | return null 53 | } 54 | val elementType = PsiUtilCore.getElementType(e as PsiElement) 55 | if ((elementType is JSKeywordElementType && elementType.keyword == "function" || elementType == JSTokenTypes.EQGT) && e.parent.parent is ES6ExportDefaultAssignment) { 56 | val actions = allActions 57 | return object : Info( 58 | AllIcons.RunConfigurations.TestState.Run, 59 | { element1 -> StringUtil.join(ContainerUtil.mapNotNull(actions) { action -> getText(action, element1) }, "\n") }, 60 | *actions) { 61 | override fun shouldReplace(other: Info): Boolean { 62 | return true 63 | } 64 | } 65 | } 66 | return null 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/run/state.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin.run 2 | 3 | import com.intellij.execution.DefaultExecutionResult 4 | import com.intellij.execution.ExecutionResult 5 | import com.intellij.execution.Executor 6 | import com.intellij.execution.PsiLocation 7 | import com.intellij.execution.configurations.GeneralCommandLine 8 | import com.intellij.execution.configurations.PtyCommandLine 9 | import com.intellij.execution.configurations.RunProfileState 10 | import com.intellij.execution.process.KillableColoredProcessHandler 11 | import com.intellij.execution.process.ProcessAdapter 12 | import com.intellij.execution.process.ProcessEvent 13 | import com.intellij.execution.process.ProcessOutputTypes 14 | import com.intellij.execution.runners.ExecutionEnvironment 15 | import com.intellij.execution.runners.ProgramRunner 16 | import com.intellij.execution.testframework.TestConsoleProperties 17 | import com.intellij.execution.testframework.sm.SMCustomMessagesParsing 18 | import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil 19 | import com.intellij.execution.testframework.sm.runner.OutputToGeneralTestEventsConverter 20 | import com.intellij.execution.testframework.sm.runner.SMTRunnerConsoleProperties 21 | import com.intellij.execution.testframework.sm.runner.SMTestLocator 22 | import com.intellij.execution.testframework.sm.runner.SMTestProxy 23 | import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView 24 | import com.intellij.openapi.project.guessProjectDir 25 | import com.intellij.openapi.util.Key 26 | import com.intellij.openapi.vfs.LocalFileSystem 27 | import com.intellij.psi.PsiManager 28 | import com.intellij.util.net.NetUtils 29 | import com.sun.net.httpserver.HttpServer 30 | import io.k6.ide.plugin.actions.TOKEN_ENV_NAME 31 | import io.k6.ide.plugin.settings.K6Settings 32 | import java.io.File 33 | import java.net.InetSocketAddress 34 | import java.nio.charset.Charset 35 | import java.util.* 36 | 37 | class K6ConsoleProperties(val config: K6RunConfig, executor: Executor): SMTRunnerConsoleProperties(config, "k6", executor), SMCustomMessagesParsing { 38 | @Volatile 39 | var k6TestEventsConverter: K6TestEventsConverter? = null 40 | override fun createTestEventsConverter( 41 | testFrameworkName: String, 42 | consoleProperties: TestConsoleProperties 43 | ): OutputToGeneralTestEventsConverter { 44 | return K6TestEventsConverter(consoleProperties).also { k6TestEventsConverter = it } 45 | } 46 | 47 | override fun getTestLocator() = SMTestLocator { protocol, path, project, scope -> 48 | if (protocol != "k6") return@SMTestLocator emptyList() 49 | val script = config.data.getScriptPath(project)?.absolutePath?.toVFile() ?: return@SMTestLocator emptyList() 50 | val psiFile = PsiManager.getInstance(project).findFile(script) ?: return@SMTestLocator emptyList() 51 | val element = psiFile.findElementAt(psiFile.text.indexOf(path)) ?: return@SMTestLocator emptyList() 52 | return@SMTestLocator listOf(PsiLocation(element)) 53 | } 54 | } 55 | 56 | internal fun String.toVFile(base: String? = null) = LocalFileSystem.getInstance().findFileByIoFile(File(base, this)) 57 | 58 | private const val portEvnKey = "intellij_plugin_test_port" // <==> port in /resources/wrapper.js 59 | 60 | class K6RunState(val myEnv: ExecutionEnvironment, val myRunConfiguration: K6RunConfig) : RunProfileState { 61 | override fun execute(executor: Executor?, runner: ProgramRunner<*>): ExecutionResult { 62 | val myConsoleProperties = K6ConsoleProperties(myRunConfiguration, myEnv.executor) 63 | val createConsole = SMTestRunnerConnectionUtil.createConsole( myConsoleProperties.testFrameworkName, myConsoleProperties) 64 | val data = myRunConfiguration.data 65 | val script = data.getScriptPath(myEnv.project) ?: error("Incorrect script path: ${data.script}") 66 | val generalCommandLine = GeneralCommandLine("k6", if (data.type == RunType.local) "run" else "cloud", 67 | if (data.thresholdsAsTests) wrapScript(script.absolutePath) else script.absolutePath, 68 | *translateCommandline(data.additionalParams ?: "") 69 | ) 70 | .withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE) 71 | val commandLine = if (data.pty) PtyCommandLine(generalCommandLine).withInitialColumns(120) else generalCommandLine 72 | commandLine.charset = Charset.forName("UTF-8") 73 | commandLine.environment.putAll(data.envs) 74 | val testPort = if (data.thresholdsAsTests) { 75 | NetUtils.findAvailableSocketPort().also { commandLine.environment[portEvnKey] = it.toString() } 76 | } else 0 77 | if (data.type == RunType.cloud) { 78 | K6Settings.instance.cloudToken.takeIf { it.isNotBlank() }?.let { commandLine.environment.put(TOKEN_ENV_NAME, it)} 79 | } 80 | myEnv.project.guessProjectDir()?.let { 81 | commandLine.setWorkDirectory(it.path) 82 | } 83 | 84 | val processHandler = KillableColoredProcessHandler(commandLine) 85 | createConsole.attachToProcess(processHandler) 86 | processHandler.setHasPty(true) 87 | val testName = script.name 88 | val location = LocalFileSystem.getInstance().findFileByIoFile(script)?.url 89 | val smTestProxy = (createConsole as SMTRunnerConsoleView).resultsViewer.root as SMTestProxy.SMRootTestProxy 90 | smTestProxy.setTestsReporterAttached() 91 | smTestProxy.setSuiteStarted() 92 | fun testNode() = smTestProxy.children.first() 93 | processHandler.addProcessListener(object : ProcessAdapter() { 94 | lateinit var server : HttpServer 95 | 96 | init { 97 | if (data.thresholdsAsTests) { 98 | server = HttpServer.create(InetSocketAddress(testPort), 0) 99 | server.createContext("/") { 100 | val response = "" 101 | val readAllBytes = it.requestBody.readAllBytes() 102 | val req = readAllBytes.toString(Charset.defaultCharset()) 103 | myConsoleProperties.k6TestEventsConverter?.processConsistentText(req, ProcessOutputTypes.SYSTEM) 104 | it.sendResponseHeaders(200, response.length.toLong()) 105 | val os = it.responseBody 106 | os.write(response.toByteArray()) 107 | os.close() 108 | } 109 | server.executor = null 110 | server.start() 111 | } 112 | } 113 | 114 | override fun startNotified(event: ProcessEvent) { 115 | myConsoleProperties.k6TestEventsConverter?.processConsistentText("##teamcity[testSuiteStarted name='$testName' locationHint='$location']", ProcessOutputTypes.SYSTEM) 116 | } 117 | 118 | override fun processTerminated(event: ProcessEvent) { 119 | if (data.thresholdsAsTests) server.stop(0) 120 | if (event.exitCode != 0 && !data.thresholdsAsTests) { 121 | testNode().setTestFailed("", null, false) 122 | smTestProxy.setTestFailed("", null, false) 123 | } 124 | } 125 | 126 | override fun processWillTerminate(event: ProcessEvent, willBeDestroyed: Boolean) { 127 | testNode().setFinished() 128 | smTestProxy.setFinished() 129 | } 130 | }) 131 | return DefaultExecutionResult(createConsole, processHandler) 132 | } 133 | 134 | private fun wrapScript(script: String): String { 135 | val wrapper = this::class.java.getResourceAsStream("/wrapper.js")?.readBytes()?.toString(Charset.defaultCharset()) 136 | ?: error("unable to extract wrapper") 137 | val wrapped = wrapper.replace("\$PATH\$", File(script).absolutePath.replace("\\", "/")) 138 | return File(System.getProperty("java.io.tmpdir"), File(script).name).also { it.writeText(wrapped); it.deleteOnExit() }.absolutePath 139 | } 140 | } 141 | 142 | /* this function was taken from the ant lib (ant:ant:1.6.5) */ 143 | fun translateCommandline(toProcess: String): Array { 144 | if (toProcess.isEmpty()) { 145 | return emptyArray() 146 | } 147 | 148 | val normal = 0 149 | val inQuote = 1 150 | val inDoubleQuote = 2 151 | var state = normal 152 | val tok = StringTokenizer(toProcess, "\"\' ", true) 153 | val result = mutableListOf() 154 | var current = StringBuffer() 155 | var lastTokenHasBeenQuoted = false 156 | while (tok.hasMoreTokens()) { 157 | val nextTok = tok.nextToken() 158 | when (state) { 159 | inQuote -> if ("\'" == nextTok) { 160 | lastTokenHasBeenQuoted = true 161 | state = normal 162 | } else { 163 | current.append(nextTok) 164 | } 165 | inDoubleQuote -> if ("\"" == nextTok) { 166 | lastTokenHasBeenQuoted = true 167 | state = normal 168 | } else { 169 | current.append(nextTok) 170 | } 171 | else -> { 172 | if ("\'" == nextTok) { 173 | state = inQuote 174 | } else if ("\"" == nextTok) { 175 | state = inDoubleQuote 176 | } else if (" " == nextTok) { 177 | if (lastTokenHasBeenQuoted || current.isNotEmpty()) { 178 | result.add(current.toString()) 179 | current = StringBuffer() 180 | } 181 | } else { 182 | current.append(nextTok) 183 | } 184 | lastTokenHasBeenQuoted = false 185 | } 186 | } 187 | } 188 | if (lastTokenHasBeenQuoted || current.isNotEmpty()) { 189 | result.add(current.toString()) 190 | } 191 | if (state == inQuote || state == inDoubleQuote) { 192 | error("unbalanced quotes in $toProcess") 193 | } 194 | return result.toTypedArray() 195 | } 196 | 197 | class K6TestEventsConverter(consoleProperties: TestConsoleProperties) : OutputToGeneralTestEventsConverter("k6", consoleProperties) { 198 | 199 | public override fun processConsistentText(text: String, outputType: Key<*>) { 200 | super.processConsistentText(text, outputType) 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/run/ui.kt: -------------------------------------------------------------------------------- 1 | package com.devexperts.K6.plug.idea.run 2 | 3 | import com.intellij.execution.configuration.EnvironmentVariablesTextFieldWithBrowseButton 4 | import com.intellij.openapi.fileChooser.FileChooserDescriptor 5 | import com.intellij.openapi.options.SettingsEditor 6 | import com.intellij.openapi.project.DumbAware 7 | import com.intellij.openapi.project.Project 8 | import com.intellij.openapi.ui.TextFieldWithBrowseButton 9 | import com.intellij.ui.PanelWithAnchor 10 | import io.k6.ide.plugin.run.K6RunConfig 11 | import io.k6.ide.plugin.run.RunType 12 | import javax.swing.* 13 | 14 | class K6ConfigurableEditorPanel(myProject: Project) : SettingsEditor(), PanelWithAnchor, DumbAware { 15 | 16 | private lateinit var myWholePanel: JPanel 17 | private var anchor: JComponent? = null 18 | 19 | private lateinit var myScript: TextFieldWithBrowseButton 20 | private lateinit var myEnvs: EnvironmentVariablesTextFieldWithBrowseButton 21 | private lateinit var myArguments: JTextField 22 | private lateinit var myLocal: JRadioButton 23 | private lateinit var myCloud: JRadioButton 24 | private lateinit var myPty: JCheckBox 25 | private lateinit var myThresholdsAsTests: JCheckBox 26 | 27 | private lateinit var myPathLabel: JLabel 28 | private lateinit var myEnvLabel: JLabel 29 | 30 | private val radios : List get() = listOf(myLocal, myCloud) 31 | 32 | init { 33 | val scriptDescriptor = FileChooserDescriptor(true, false, false, false, false, false) 34 | scriptDescriptor.title = "k6 Script Path" 35 | scriptDescriptor.description = "Select path to k6 Script to be run" 36 | myScript.addBrowseFolderListener( 37 | scriptDescriptor.title, 38 | scriptDescriptor.description, 39 | myProject, 40 | scriptDescriptor 41 | ) 42 | radios.forEach { it.addActionListener { e -> 43 | val find = radios.find { it == e.source } ?: return@addActionListener 44 | (radios - find).forEach { if (it.isSelected) it.isSelected = false } 45 | if (myCloud.isSelected) { 46 | myThresholdsAsTests.isEnabled = false 47 | myThresholdsAsTests.isSelected = false 48 | } else { 49 | myThresholdsAsTests.isEnabled = true 50 | } 51 | } } 52 | 53 | myPathLabel.labelFor = myScript 54 | myEnvLabel.labelFor = myEnvs 55 | } 56 | 57 | override fun resetEditorFrom(s: K6RunConfig) { 58 | s.data.apply { 59 | myScript.text = script ?: "" 60 | myEnvs.envs = envs.toMutableMap() 61 | myArguments.text = additionalParams 62 | val selected = if (type == RunType.local) myLocal else myCloud 63 | selected.isSelected = true 64 | (radios - selected).first().isSelected = false 65 | myPty.isSelected = pty 66 | myThresholdsAsTests.isSelected = thresholdsAsTests 67 | myThresholdsAsTests.isEnabled = type == RunType.local 68 | } 69 | } 70 | 71 | override fun applyEditorTo(s: K6RunConfig) { 72 | s.data.apply { 73 | script = myScript.text 74 | envs = myEnvs.envs.toMutableMap() 75 | additionalParams = myArguments.text 76 | type = if (myLocal.isSelected) RunType.local else RunType.cloud 77 | pty = myPty.isSelected 78 | thresholdsAsTests = myThresholdsAsTests.isSelected 79 | } 80 | } 81 | 82 | override fun createEditor() = myWholePanel 83 | 84 | override fun getAnchor() = anchor 85 | 86 | override fun setAnchor(anchor: JComponent?) { 87 | this.anchor = anchor 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/kotlin/io/k6/ide/plugin/settings/settings.kt: -------------------------------------------------------------------------------- 1 | package io.k6.ide.plugin.settings 2 | 3 | import com.intellij.openapi.components.PersistentStateComponent 4 | import com.intellij.openapi.components.ServiceManager 5 | import com.intellij.openapi.components.State 6 | import com.intellij.openapi.components.Storage 7 | import com.intellij.openapi.options.Configurable 8 | import com.intellij.openapi.options.ConfigurationException 9 | import com.intellij.openapi.options.SearchableConfigurable 10 | import com.intellij.openapi.ui.panel.ComponentPanelBuilder 11 | import com.intellij.ui.components.JBPanel 12 | import com.intellij.ui.components.JBTextField 13 | import com.intellij.util.ui.FormBuilder 14 | import com.intellij.util.xmlb.XmlSerializerUtil 15 | import io.k6.ide.plugin.actions.TOKEN_ENV_NAME 16 | import org.jetbrains.annotations.Nls 17 | import java.awt.BorderLayout 18 | import java.awt.LayoutManager 19 | import javax.swing.JComponent 20 | import javax.swing.JPanel 21 | 22 | @State(name = "K6Settings", storages = [Storage("other.xml")]) 23 | class K6Settings : PersistentStateComponent { 24 | var cloudToken: String = "" 25 | 26 | override fun getState(): K6Settings { 27 | return this 28 | } 29 | 30 | override fun loadState(`object`: K6Settings) { 31 | XmlSerializerUtil.copyBean(`object`, this) 32 | } 33 | 34 | companion object { 35 | val instance: K6Settings 36 | get() = ServiceManager.getService(K6Settings::class.java) 37 | } 38 | } 39 | 40 | class K6SettingsConfigurable : SearchableConfigurable, Configurable.NoScroll { 41 | private val myCloudTokenField = JBTextField() 42 | 43 | @Nls 44 | override fun getDisplayName(): String { 45 | return "k6" 46 | } 47 | 48 | override fun getHelpTopic(): String { 49 | return "preferences.K6" 50 | } 51 | 52 | override fun createComponent(): JComponent { 53 | val builder = FormBuilder.createFormBuilder() 54 | builder.addComponent(ComponentPanelBuilder(myCloudTokenField) 55 | .withLabel("Cloud token:") 56 | .withComment("If this field is left empty, k6 will look for an environment variable named `$TOKEN_ENV_NAME`.
No account yet? Register for a free trial here.", false) 57 | .createPanel() 58 | ) 59 | val borderLayout : LayoutManager = BorderLayout() 60 | val wrapper: JPanel = JBPanel>(borderLayout) 61 | wrapper.add(builder.panel, BorderLayout.NORTH) 62 | return wrapper 63 | } 64 | 65 | 66 | override fun isModified(): Boolean { 67 | return myCloudTokenField.text != K6Settings.instance.cloudToken 68 | } 69 | 70 | @Throws(ConfigurationException::class) 71 | override fun apply() { 72 | K6Settings.instance.cloudToken = myCloudTokenField.text 73 | } 74 | 75 | override fun reset() { 76 | myCloudTokenField.text = K6Settings.instance.cloudToken 77 | } 78 | 79 | 80 | override fun getId(): String { 81 | return helpTopic 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin-js.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | io.k6.ide.plugin 3 | k6 4 | mbolotov 5 | 6 | com.intellij.modules.platform 7 | JavaScript 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 21 | 22 | 23 | 28 | 29 | 30 | 31 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/pluginIcon.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 9 | 44 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/resources/icons/k6_16x16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mbolotov/k6-intellij-plugin/6d32891ab2433ebfa5aab81ffdf6630b4a7eabf7/src/main/resources/icons/k6_16x16.png -------------------------------------------------------------------------------- /src/main/resources/wrapper.js: -------------------------------------------------------------------------------- 1 | import http from 'k6/http'; 2 | import {humanizeValue, textSummary} from 'https://jslib.k6.io/k6-summary/0.0.1/index.js' 3 | 4 | var script = require('$PATH$'); 5 | 6 | let port = __ENV.intellij_plugin_test_port // <==> io.k6.ide.plugin.run.StateKt.portEvnKey 7 | let address = `http://localhost:${port}`; 8 | 9 | function post(data) { 10 | return http.post(address, data) 11 | } 12 | 13 | function wrapperHandleSummary(data) { 14 | const result = script.handleSummary ? script.handleSummary(data) : {}; 15 | for (let metric in data.metrics) { 16 | let thresholds = data.metrics[metric].thresholds; 17 | if (thresholds !== undefined) { 18 | post(`##teamcity[testStarted name='${metric}' locationHint='k6://${metric}']`) 19 | post(`##teamcity[testStdOut name='${metric}' out='${escape(humanizeMetricValues(data.metrics[metric]))}']`) 20 | let pass = true 21 | for (let v of Object.values(thresholds)) { 22 | pass &= v["ok"] 23 | } 24 | if (!pass) { 25 | post(`##teamcity[testFailed name='${metric}' message='threshold failed: ${escape(Object.keys(thresholds).toString())}' details='']`) 26 | } 27 | post(`##teamcity[testFinished name='${metric}']`) 28 | } 29 | } 30 | if (!script.handleSummary) { 31 | console.log("\n" + textSummary(data)) 32 | } 33 | return result; 34 | } 35 | 36 | function humanizeMetricValues(metric) { 37 | var result = [] 38 | if (metric.type === 'trend') { 39 | for (const [key, value] of Object.entries(metric.values)) { 40 | result.push(key + " = " + humanizeValue(value, metric, 'ms')) 41 | } 42 | } else { 43 | result = nonTrendMetricValueForSum(metric, 'ms') 44 | } 45 | return result.join(", ") 46 | } 47 | 48 | function nonTrendMetricValueForSum(metric, timeUnit) { 49 | switch (metric.type) { 50 | case 'counter1': 51 | return [ 52 | "count=" + humanizeValue(metric.values.count, metric, timeUnit), 53 | "rate=" + humanizeValue(metric.values.rate1, metric, timeUnit) + '/s', 54 | ] 55 | case 'gauge': 56 | return [ 57 | humanizeValue(metric.values.value, metric, timeUnit), 58 | 'min=' + humanizeValue(metric.values.min, metric, timeUnit), 59 | 'max=' + humanizeValue(metric.values.max, metric, timeUnit), 60 | ] 61 | case 'rate': 62 | return [ 63 | 'rate=' + humanizeValue(metric.values.rate1, metric, timeUnit), 64 | 'pass=' + metric.values.passes, 65 | 'fail=' + metric.values.fails, 66 | ] 67 | default: 68 | return ['[no data]'] 69 | } 70 | } 71 | 72 | function escape(str) { 73 | if (!isAttributeValueEscapingNeeded(str)) { 74 | return str; 75 | } 76 | var res = '' 77 | , len = str.length; 78 | for (var i = 0; i < len; i++) { 79 | var escaped = doEscapeCharCode(str.charCodeAt(i)); 80 | if (escaped) { 81 | res += '|'; 82 | res += escaped; 83 | } 84 | else { 85 | res += str.charAt(i); 86 | } 87 | } 88 | return res; 89 | } 90 | 91 | var doEscapeCharCode = (function () { 92 | var obj = {}; 93 | 94 | function addMapping(fromChar, toChar) { 95 | if (fromChar.length !== 1 || toChar.length !== 1) { 96 | throw Error('String length should be 1'); 97 | } 98 | var fromCharCode = fromChar.charCodeAt(0); 99 | if (typeof obj[fromCharCode] === 'undefined') { 100 | obj[fromCharCode] = toChar; 101 | } 102 | else { 103 | throw Error('Bad mapping'); 104 | } 105 | } 106 | 107 | addMapping('\n', 'n'); 108 | addMapping('\r', 'r'); 109 | addMapping('\u0085', 'x'); 110 | addMapping('\u2028', 'l'); 111 | addMapping('\u2029', 'p'); 112 | addMapping('|', '|'); 113 | addMapping('\'', '\''); 114 | addMapping('[', '['); 115 | addMapping(']', ']'); 116 | 117 | return function (charCode) { 118 | return obj[charCode]; 119 | }; 120 | }()); 121 | 122 | function isAttributeValueEscapingNeeded(str) { 123 | var len = str.length; 124 | for (var i = 0; i < len; i++) { 125 | if (doEscapeCharCode(str.charCodeAt(i))) { 126 | return true; 127 | } 128 | } 129 | return false; 130 | } 131 | 132 | 133 | Object.assign(exports, script, { handleSummary: wrapperHandleSummary }); 134 | --------------------------------------------------------------------------------