This commit is contained in:
stud_i_sram 2026-05-14 20:08:57 +03:00
commit 8e923f0054
38 changed files with 3766 additions and 0 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
.DS_Store
.gradle
.idea
.intellijPlatform
.kotlin
build

25
.run/Run Plugin.run.xml Normal file
View File

@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Plugin" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="IDE logs" path="$PROJECT_DIR$/.intellijPlatform/sandbox/*/*/log/idea.log" show_all="true" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIde" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>false</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

25
.run/Run Tests.run.xml Normal file
View File

@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="IDE logs" path="$PROJECT_DIR$/.intellijPlatform/sandbox/*/*/log-test/idea.log" show_all="true" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="check" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>true</RunAsTest>
<method v="2" />
</configuration>
</component>

View File

@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Verifications" type="GradleRunConfiguration" factoryName="Gradle">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="verifyPlugin" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

1007
CHANGELOG.md Normal file

File diff suppressed because it is too large Load Diff

4
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,4 @@
## Code of Conduct
This project and the corresponding community is governed by the [JetBrains Open Source and Community Code of Conduct](https://confluence.jetbrains.com/display/ALL/JetBrains+Open+Source+and+Community+Code+of+Conduct). Please make sure you read it.

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2000-2021 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

538
README.md Normal file
View File

@ -0,0 +1,538 @@
# IntelliJ Platform Plugin Template
[![official JetBrains project](https://jb.gg/badges/official.svg)][jb:github]
[![Twitter Follow](https://img.shields.io/badge/follow-%40JBPlatform-1DA1F2?logo=twitter)](https://x.com/JBPlatform)
[![Build](https://github.com/JetBrains/intellij-platform-plugin-template/workflows/Build/badge.svg)][gh:build]
![IntelliJ Platform Plugin Template][file:intellij-platform-plugin-template-dark]
![IntelliJ Platform Plugin Template][file:intellij-platform-plugin-template-light]
> [!NOTE]
> Click the <kbd>Use this template</kbd> button and clone it in IntelliJ IDEA.
**IntelliJ Platform Plugin Template** is a repository that provides a pure template to make it easier to create a new plugin project (check the [Creating a repository from a template][gh:template] article).
The main goal of this template is to speed up the setup phase of plugin development for both new and experienced developers by preconfiguring the project scaffold and CI, linking to the proper documentation pages, and keeping everything organized.
[gh:template]: https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template
If you're still not quite sure what this is all about, read our introduction: [What is the IntelliJ Platform?][docs:intro]
> [!NOTE]
> Click the <kbd>Watch</kbd> button on the top to be notified about releases containing new features and fixes.
### Table of contents
In this README, we will highlight the following elements of template-project creation:
- [Getting started](#getting-started)
- [Gradle configuration](#gradle-configuration)
- [Plugin template structure](#plugin-template-structure)
- [Plugin configuration file](#plugin-configuration-file)
- [Sample code](#sample-code):
- startup activity project-open sample
- services project-level service
- tool window sample UI entry point
- [Testing](#testing)
- [Functional tests](#functional-tests)
- [UI tests](#ui-tests)
- [Predefined Run/Debug configurations](#predefined-rundebug-configurations)
- [Continuous integration](#continuous-integration) based on GitHub Actions
- [Dependencies management](#dependencies-management) with Dependabot
- [Changelog maintenance](#changelog-maintenance) with the Gradle Changelog Plugin
- [Release flow](#release-flow) using GitHub Releases
- [Plugin signing](#plugin-signing) with Marketplace signing
- [Publishing the plugin](#publishing-the-plugin) with the IntelliJ Platform Gradle Plugin
- [FAQ](#faq)
- [Useful links](#useful-links)
## Getting started
Before we dive into plugin development and everything related to it, it's worth mentioning the benefits of using GitHub Templates.
By creating a new project using the current template, you start with no history or reference to this repository.
This allows you to create a new repository easily without copying and pasting previous content, cloning repositories, or clearing the history manually.
All you have to do is click the <kbd>Use this template</kbd> button (you must be logged in with your GitHub account).
![Use this template][file:use-this-template.png]
After using the template to create your blank project, the [Template Cleanup][file:template_cleanup.yml] workflow will be triggered to override or remove any template-specific configurations, such as the plugin name, current changelog, etc.
Once this is complete, open the newly created project's _Settings | Actions | General_ page and enable option _Allow GitHub Actions to create and approve pull requests_.
Now the project is ready to be cloned to your local environment and opened with [IntelliJ IDEA][jb:download-ij].
The most convenient way for getting your new project from GitHub is the <kbd>Get from VCS</kbd> action available on the Welcome Screen, where you can filter your GitHub repository by its name.
![Get from Version Control][file:get-from-version-control]
The next step, after opening your project in IntelliJ IDEA, is to set the proper <kbd>SDK</kbd> to Java in version `21` within the [Project Structure settings][docs:project-structure-settings].
![Project Structure — SDK][file:project-structure-sdk.png]
For the last step, review the project metadata in [`gradle.properties`][file:gradle.properties] and [`plugin.xml`][file:plugin.xml], then *optionally* move sources from the generated package to the one that works best for you.
Then you can get to work implementing your ideas.
> [!NOTE]
> To use Java in your plugin, create the `/src/main/java` directory.
## Gradle configuration
The recommended method for plugin development involves using the [Gradle][gradle] setup with the [intellij-platform-gradle-plugin][gh:intellij-platform-gradle-plugin] installed.
The IntelliJ Platform Gradle Plugin makes it possible to run the IDE with your plugin and publish your plugin to JetBrains Marketplace.
> [!NOTE]
> Make sure to always upgrade to the latest version of IntelliJ Platform Gradle Plugin.
A project built using the IntelliJ Platform Plugin Template includes a Gradle configuration already set up.
Feel free to read through the [Using Gradle][docs:using-gradle] articles to understand your build better and learn how to customize it.
The most significant parts of the current configuration are:
- Integration with the [intellij-platform-gradle-plugin][gh:intellij-platform-gradle-plugin] for smoother development.
- Repository configuration moved to [`settings.gradle.kts`][file:settings.gradle.kts] using the IntelliJ Platform repositories extension.
- Configuration written with [Gradle Kotlin DSL][gradle:kotlin-dsl].
- Support for Kotlin and Java implementation.
- Plugin and dependency versions are declared directly in the Gradle build files.
- Integration with the [gradle-changelog-plugin][gh:gradle-changelog-plugin], which automatically patches the change notes based on the `CHANGELOG.md` file.
- [Plugin publishing][docs:publishing] through the `publishPlugin` task and GitHub Actions workflows.
For more details regarding Kotlin integration, please see [Kotlin for Plugin Developers][docs:kotlin] in the IntelliJ Platform Plugin SDK documentation.
### Gradle properties
The project-specific configuration file [`gradle.properties`][file:gradle.properties] starts with values expected to vary between repositories created from this template:
| Property name | Description |
|-----------------------|------------------------------------------------------------------------------------------------------|
| `group` | Project group and default base package for the sample sources. |
| `version` | Current plugin version in [SemVer][semver] format. |
| `pluginRepositoryUrl` | Repository URL used for generating URLs by the [Gradle Changelog Plugin][gh:gradle-changelog-plugin] |
The remaining plugin metadata lives closer to where it is used:
- [`settings.gradle.kts`][file:settings.gradle.kts] declares Gradle plugin versions and repository management.
- [`build.gradle.kts`][file:build.gradle.kts] declares the target IntelliJ Platform version and project dependencies.
- [`plugin.xml`][file:plugin.xml] contains the plugin `id`, `name`, `vendor`, `description`, and extension registrations.
It also configures Gradle build behavior flags, such as:
| Property name | Value | Description |
|--------------------------------------------------|---------|------------------------------------------------------------------------------------------------|
| `kotlin.stdlib.default.dependency` | `false` | Opt-out flag for bundling [Kotlin standard library][docs:kotlin-stdlib] |
| `org.gradle.configuration-cache` | `true` | Enable [Gradle Configuration Cache][gradle:configuration-cache] |
| `org.gradle.caching` | `true` | Enable [Gradle Build Cache][gradle:build-cache] |
### Environment variables
Some values used during signing and publishing should not be stored in project files.
Provide them through local *Run/Debug Configurations* or on CI, for example in GitHub under `Settings > Secrets and variables > Actions`.
The current template uses the following variables for the [plugin signing](#plugin-signing) and [publishing](#publishing-the-plugin) flow:
| Environment variable name | Description |
|---------------------------|--------------------------------------------------------------------------------------------------------------|
| `PRIVATE_KEY` | Certificate private key, should contain: `-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----` |
| `PRIVATE_KEY_PASSWORD` | Password used for encrypting the certificate file. |
| `CERTIFICATE_CHAIN` | Certificate chain, should contain: `-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----` |
| `PUBLISH_TOKEN` | Publishing token generated in your JetBrains Marketplace profile dashboard. |
For more details on how to generate proper values, check the relevant sections mentioned above.
To configure GitHub secret environment variables, go to the `⚙️ Settings > Secrets and variables > Actions` section of your project repository:
![Settings > Secrets][file:settings-secrets.png]
## Plugin template structure
A generated IntelliJ Platform Plugin Template repository contains the following content structure:
```
.
├── .github/ GitHub Actions workflows and Dependabot configuration files
├── .run/ Predefined Run/Debug Configurations
├── gradle
│ └── wrapper/ Gradle Wrapper
├── src Plugin sources
│ ├── main
│ │ ├── kotlin/ Kotlin production sources
│ │ └── resources/ Resources - plugin.xml, icons, messages
│ └── test
│ ├── kotlin/ Kotlin test sources
│ └── testData/ Test data used by tests
├── .gitignore Git ignoring rules
├── build.gradle.kts Gradle configuration
├── CHANGELOG.md Full change history
├── gradle.properties Gradle configuration properties
├── gradlew *nix Gradle Wrapper script
├── gradlew.bat Windows Gradle Wrapper script
├── LICENSE License, MIT by default
├── README.md README
└── settings.gradle.kts Gradle project settings and repositories
```
In addition to the configuration files, the most crucial part is the `src` directory, which contains our implementation and the manifest for our plugin [plugin.xml][file:plugin.xml].
> [!NOTE]
> To use Java in your plugin, create the `/src/main/java` directory.
## Plugin configuration file
The plugin configuration file is a [plugin.xml][file:plugin.xml] file located in the `src/main/resources/META-INF` directory.
It provides general information about the plugin, its dependencies, and its extensions.
Maintain the plugin description directly in this file, using HTML wrapped in CDATA when needed.
> [!NOTE]
> When using this template for a real plugin, replace the placeholder description with content that describes the final plugin.
```xml
<idea-plugin>
<id>org.jetbrains.plugins.template</id>
<name>IntelliJ Platform Plugin Template</name>
<vendor>JetBrains</vendor>
<description><![CDATA[
<p>Plugin description in HTML.</p>
]]></description>
<depends>com.intellij.modules.platform</depends>
<resource-bundle>messages.MyBundle</resource-bundle>
<extensions defaultExtensionNs="com.intellij">
<toolWindow factoryClass="..." id="..."/>
<postStartupActivity implementation="..."/>
</extensions>
</idea-plugin>
```
You can read more about this file in the [Plugin Configuration File][docs:plugin.xml] section of our documentation.
## Sample code
The prepared template provides as little code as possible because it is impossible for a general scaffold to fulfill all the specific requirements for all types of plugins (language support, build tools, VCS related tools).
Therefore, the template contains only the following files:
```
.
├── startup
│ └── MyProjectActivity.kt Project startup activity
├── services
│ └── MyProjectService.kt Project-level service
├── toolWindow
│ └── MyToolWindowFactory.kt Tool window factory — creates tool window content
└── MyBundle.kt Bundle class providing access to the resources messages
```
These files are located in `src/main/kotlin`.
This location indicates the language being used.
So if you decide to use Java instead (or in addition to Kotlin), these sources should be located in the `src/main/java` directory.
> [!TIP]
> It is possible to use the [IntelliJ Platform Icons](https://jb.gg/new-ui-icons) in your plugin.
To start with the actual implementation, you may check our [IntelliJ Platform SDK DevGuide][docs], which contains an introduction to the essential areas of the plugin development together with dedicated tutorials.
> [!WARNING]
> Remember to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.
For those who value example codes the most, there are also available [IntelliJ SDK Code Samples][gh:code-samples] and [IntelliJ Platform Explorer][jb:ipe] a search tool for browsing Extension Points inside existing implementations of open-source IntelliJ Platform plugins.
## Testing
[Testing plugins][docs:testing-plugins] is an essential part of the plugin development to make sure that everything works as expected between IDE releases and plugin refactorings.
The IntelliJ Platform Plugin Template project ships with functional test examples and leaves UI testing setup to the plugin author.
### Functional tests
Most of the IntelliJ Platform codebase tests are model-level, run in a headless environment using an actual IDE instance.
The tests usually test a feature as a whole rather than individual functions that comprise its implementation, like in unit tests.
In `src/test/kotlin`, you will find a basic `MyPluginTest` test that utilizes `BasePlatformTestCase` and runs a few checks against the XML files to indicate an example operation of creating files on the fly or reading them from `src/test/testData/rename` test resources.
> [!NOTE]
> Run your tests using predefined *Run Tests* configuration or by invoking the `./gradlew check` Gradle task.
### UI tests
If your plugin provides complex user interfaces, you should consider covering them with tests and the functionality they use.
The template does not wire UI testing into the Gradle build by default anymore.
If you need UI coverage, start with the IntelliJ Platform SDK guides for [Integration Tests][docs:integration-tests] and [Integration Tests: UI Testing][docs:integration-tests-ui], then add your own test source set, Gradle tasks, and CI workflow for the operating systems you support.
## Predefined Run/Debug configurations
Within the default project structure, there is a `.run` directory provided containing predefined *Run/Debug configurations* that expose corresponding Gradle tasks:
![Run/Debug configurations][file:run-debug-configurations.png]
| Configuration name | Description |
|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Run Plugin | Runs [`:runIde`][gh:intellij-platform-gradle-plugin-runIde] IntelliJ Platform Gradle Plugin task. Use the *Debug* icon for plugin debugging. |
| Run Tests | Runs [`:check`][gradle:lifecycle-tasks] Gradle task. |
| Run Verifications | Runs [`:verifyPlugin`][gh:intellij-platform-gradle-plugin-verifyPlugin] IntelliJ Platform Gradle Plugin task to check the plugin compatibility against the specified IntelliJ IDEs. |
> [!NOTE]
> You can find the logs from the running task in the `idea.log` tab.
>
> ![Run/Debug configuration logs][file:run-logs.png]
## Continuous integration
Continuous integration depends on [GitHub Actions][gh:actions], a set of workflows that make it possible to automate your testing and release process.
Thanks to such automation, you can delegate the testing and verification phases to the Continuous Integration (CI) and instead focus on development (and writing more tests).
> [!NOTE]
> To ensure the "Create Pull Request" step functions correctly in the "Publish Plugin" job, make sure to enable "Read and write permissions" for actions by navigating to `⚙️ Settings > Actions > General > Workflow permissions`.
In the `.github/workflows` directory, you can find definitions for the following GitHub Actions workflows:
- [Build](.github/workflows/build.yml)
- Triggered on `push` and `pull_request` events.
- Builds the plugin with the `buildPlugin` Gradle task and uploads the plugin ZIP as a workflow artifact.
- Runs the `check` Gradle task in a dedicated test job.
- Runs the `verifyPlugin` Gradle task in a dedicated verification job.
- Prepares a draft release of the GitHub Releases page for manual verification.
- [Release](.github/workflows/release.yml)
- Triggered on `prereleased` and `released` events.
- Updates `CHANGELOG.md` with the published release notes when a release body is provided.
- Signs the plugin with a provided certificate before publishing.
- Publishes the plugin to JetBrains Marketplace using the provided `PUBLISH_TOKEN`.
- Uploads the built plugin distribution as a GitHub release asset.
- Creates a pull request with the patched changelog when needed.
- [Template Cleanup](.github/workflows/template-cleanup.yml)
- Triggered once on the `push` event when a new template-based repository has been created.
- Overrides the scaffold with files from the `.github/template-cleanup` directory.
- Overrides JetBrains-specific sentences or package names with ones specific to the target repository.
- Removes redundant files.
All the workflow files include inline documentation, so it's a good idea to take a look through their sources.
### Dependencies management
This template keeps dependency management explicit and local to the Gradle files that use it:
- [`settings.gradle.kts`][file:settings.gradle.kts] declares Gradle plugin versions and repositories.
- [`build.gradle.kts`][file:build.gradle.kts] declares the target IntelliJ Platform version and project dependencies.
- [`gradle.properties`][file:gradle.properties] stores repository-specific metadata shared by the build and CI workflows.
> [!NOTE]
> To add a regular library dependency, declare it directly in the `dependencies { ... }` block:
>
> ```kotlin
> dependencies {
> implementation("group:artifact:version")
> }
> ```
>
> Add IntelliJ Platform plugin or module dependencies through the `intellijPlatform { ... }` dependency extension described in the [IntelliJ Platform Gradle Plugin documentation][gh:intellij-platform-gradle-plugin-docs].
Keeping the project in good shape and having all the dependencies up to date requires time and effort, but it is possible to automate that process using [Dependabot][gh:dependabot].
Dependabot is a bot provided by GitHub that checks build configuration files for outdated or insecure dependencies.
When an update is available, it creates a new pull request providing [the proper change][gh:dependabot-pr].
> [!NOTE]
> Dependabot supports [Gradle Wrapper updates][gh:dependabot-supported-ecosystems].
> To update Gradle manually, check the [Gradle Releases][gradle:releases] page and run
> ```bash
> ./gradlew wrapper --gradle-version <version> && ./gradlew wrapper
> ```
### Changelog maintenance
When releasing an update, it is essential to let your users know what the new version offers.
The best way to do this is to provide release notes.
The changelog is a curated list that contains information about any new features, fixes, and deprecations.
When they're provided, these lists are available in a few different places:
- the [CHANGELOG.md](./CHANGELOG.md) file,
- the [Releases page][gh:releases],
- the *What's new* section of the JetBrains Marketplace Plugin page,
- and inside the Plugin Manager's item details.
There are many methods for handling the project's changelog.
The one used in the current template project is the [Keep a Changelog][keep-a-changelog] approach.
The [Gradle Changelog Plugin][gh:gradle-changelog-plugin] takes care of propagating information provided within the [CHANGELOG.md](./CHANGELOG.md) to the [IntelliJ Platform Gradle Plugin][gh:intellij-platform-gradle-plugin].
You only have to take care of writing down the actual changes in proper sections of the `[Unreleased]` section.
You start with an almost empty changelog:
```
# YourPlugin Changelog
## [Unreleased]
### Added
- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
```
Now proceed with providing more entries to the `Added` group, or any other one that suits your change the most (see [How do I make a good changelog?][keep-a-changelog-how] for more details).
When releasing a plugin update, you don't have to care about bumping the `[Unreleased]` header to the upcoming version it will be handled automatically on the Continuous Integration (CI) after you publish your plugin.
GitHub Actions will swap it and provide you with an empty section for the next release so that you can proceed with your development:
```
# YourPlugin Changelog
## [Unreleased]
## [0.0.1]
### Added
- An awesome feature
- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
### Fixed
- One annoying bug
```
To configure how the Changelog plugin behaves, i.e., to create headers with the release date, see the [Gradle Changelog Plugin][gh:gradle-changelog-plugin] README file.
### Release flow
The release process depends on the workflows already described above.
When your main branch receives a new pull request or a direct push, the [Build](.github/workflows/build.yml) workflow runs multiple tests on your plugin and prepares a draft release.
![Release draft][file:draft-release.png]
The draft release is a working copy of a release, which you can review before publishing.
It uses the current plugin version from [`gradle.properties`][file:gradle.properties] as both the title and git tag, for example, `0.0.1`.
The changelog is provided automatically using the [gradle-changelog-plugin][gh:gradle-changelog-plugin].
The built plugin archive is uploaded as a workflow artifact during the Build run rather than attached to the draft release itself.
Every new Build overrides the previous draft to keep your *Releases* page clean.
When you edit the draft and use the <kbd>Publish release</kbd> button, GitHub will tag your repository with the given version and add a new entry to the Releases tab.
Next, it will notify users who are *watching* the repository, triggering the final [Release](.github/workflows/release.yml) workflow.
### Plugin signing
Plugin Signing is a mechanism introduced in the 2021.2 release cycle to increase security in [JetBrains Marketplace](https://plugins.jetbrains.com) and all of our IntelliJ-based IDEs.
JetBrains Marketplace signing is designed to ensure that plugins aren't modified over the course of the publishing and delivery pipeline.
The current template keeps signing configuration out of `build.gradle.kts` and relies on the standard environment variables consumed by the IntelliJ Platform Gradle Plugin.
That allows you to sign and publish your plugin from both the Continuous Integration (CI) and local environments without checking secrets into VCS.
To find out how to generate signing certificates, check the [Plugin Signing][docs:plugin-signing] section in the IntelliJ Platform Plugin SDK documentation.
### Publishing the plugin
> [!TIP]
> Make sure to follow all guidelines listed in [Publishing a Plugin][docs:publishing] to follow all recommended and required steps.
Releasing a plugin to [JetBrains Marketplace](https://plugins.jetbrains.com) is a straightforward operation that uses the `publishPlugin` Gradle task provided by the [intellij-platform-gradle-plugin][gh:intellij-platform-gradle-plugin-docs].
In addition, the [Release](.github/workflows/release.yml) workflow automates this process by running the task when a new release appears in the GitHub Releases section.
> [!NOTE]
> If you need custom Marketplace channels or additional publishing options, add explicit publishing configuration to [`build.gradle.kts`][file:build.gradle.kts] as described in the [publishing documentation][docs:publishing].
The authorization process relies on the `PUBLISH_TOKEN` secret environment variable, specified in the `⚙️ Settings > Secrets and variables > Actions` section of your project repository.
You can get that token in your JetBrains Marketplace profile dashboard in the [My Tokens][jb:my-tokens] tab.
> [!WARNING]
> Before using the automated deployment process, it is necessary to manually create a new plugin in JetBrains Marketplace to specify options like the license, repository URL, etc.
> Please follow the [Publishing a Plugin][docs:publishing] instructions.
## FAQ
### How to use Java in my project?
Java language is supported by default along with Kotlin.
Initially, the `/src/main/kotlin` directory is available with minimal examples.
You can still replace it or add the `/src/main/java` directory to start working with Java language instead.
### How to disable *tests* or *build* job using the `[skip ci]` commit message?
Since February 2021, GitHub Actions [has supported the skip CI feature][github-actions-skip-ci].
If the message contains one of the following strings: `[skip ci]`, `[ci skip]`, `[no ci]`, `[skip actions]`, or `[actions skip]` workflows will not be triggered.
### Why does the draft release no longer contain a built plugin artifact?
All binaries created by the workflows are still available as workflow artifacts together with failed test reports or Plugin Verifier results.
That approach gives more possibilities for testing and debugging pre-releases, for example, in your local environment.
## Useful links
- [IntelliJ Platform Plugin SDK][docs]
- [IntelliJ Platform Gradle Plugin Documentation][gh:intellij-platform-gradle-plugin-docs]
- [IntelliJ Platform Explorer][jb:ipe]
- [JetBrains Marketplace Quality Guidelines][jb:quality-guidelines]
- [IntelliJ Platform UI Guidelines][jb:ui-guidelines]
- [JetBrains Marketplace Paid Plugins][jb:paid-plugins]
- [Kotlin UI DSL][docs:kotlin-ui-dsl]
- [IntelliJ SDK Code Samples][gh:code-samples]
- [JetBrains Platform Slack][jb:slack]
- [JetBrains Platform Twitter][jb:twitter]
- [IntelliJ IDEA Open API and Plugin Development Forum][jb:forum]
- [Keep a Changelog][keep-a-changelog]
- [GitHub Actions][gh:actions]
[docs]: https://plugins.jetbrains.com/docs/intellij?from=IJPluginTemplate
[docs:intro]: https://plugins.jetbrains.com/docs/intellij/intellij-platform.html?from=IJPluginTemplate
[docs:kotlin-ui-dsl]: https://plugins.jetbrains.com/docs/intellij/kotlin-ui-dsl-version-2.html?from=IJPluginTemplate
[docs:kotlin]: https://plugins.jetbrains.com/docs/intellij/using-kotlin.html?from=IJPluginTemplate
[docs:kotlin-stdlib]: https://plugins.jetbrains.com/docs/intellij/using-kotlin.html?from=IJPluginTemplate#kotlin-standard-library
[docs:plugin.xml]: https://plugins.jetbrains.com/docs/intellij/plugin-configuration-file.html?from=IJPluginTemplate
[docs:publishing]: https://plugins.jetbrains.com/docs/intellij/publishing-plugin.html?from=IJPluginTemplate
[docs:using-gradle]: https://plugins.jetbrains.com/docs/intellij/developing-plugins.html?from=IJPluginTemplate
[docs:plugin-signing]: https://plugins.jetbrains.com/docs/intellij/plugin-signing.html?from=IJPluginTemplate
[docs:project-structure-settings]: https://www.jetbrains.com/help/idea/project-settings-and-structure.html
[docs:testing-plugins]: https://plugins.jetbrains.com/docs/intellij/testing-plugins.html?from=IJPluginTemplate
[docs:integration-tests]: https://plugins.jetbrains.com/docs/intellij/integration-tests.html?from=IJPluginTemplate
[docs:integration-tests-ui]: https://plugins.jetbrains.com/docs/intellij/integration-tests-ui.html?from=IJPluginTemplate
[file:build.gradle.kts]: ./build.gradle.kts
[file:draft-release.png]: ./.github/readme/draft-release.png
[file:get-from-version-control]: ./.github/readme/get-from-version-control.png
[file:gradle.properties]: ./gradle.properties
[file:intellij-platform-plugin-template-dark]: ./.github/readme/intellij-platform-plugin-template-dark.svg#gh-dark-mode-only
[file:intellij-platform-plugin-template-light]: ./.github/readme/intellij-platform-plugin-template-light.svg#gh-light-mode-only
[file:project-structure-sdk.png]: ./.github/readme/project-structure-sdk.png
[file:plugin.xml]: ./src/main/resources/META-INF/plugin.xml
[file:run-debug-configurations.png]: ./.github/readme/run-debug-configurations.png
[file:run-logs.png]: ./.github/readme/run-logs.png
[file:settings-secrets.png]: ./.github/readme/settings-secrets.png
[file:settings.gradle.kts]: ./settings.gradle.kts
[file:template_cleanup.yml]: ./.github/workflows/template-cleanup.yml
[file:use-this-template.png]: ./.github/readme/use-this-template.png
[gh:actions]: https://docs.github.com/actions
[gh:build]: https://github.com/JetBrains/intellij-platform-plugin-template/actions?query=workflow%3ABuild
[gh:code-samples]: https://github.com/JetBrains/intellij-sdk-code-samples
[gh:dependabot]: https://docs.github.com/en/code-security/dependabot/dependabot-version-updates
[gh:dependabot-pr]: https://github.com/JetBrains/intellij-platform-plugin-template/pull/73
[gh:dependabot-supported-ecosystems]: https://docs.github.com/en/code-security/dependabot/ecosystems-supported-by-dependabot/supported-ecosystems-and-repositories#gradle
[gh:gradle-changelog-plugin]: https://github.com/JetBrains/gradle-changelog-plugin
[gh:intellij-platform-gradle-plugin]: https://github.com/JetBrains/intellij-platform-gradle-plugin
[gh:intellij-platform-gradle-plugin-docs]: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin.html
[gh:intellij-platform-gradle-plugin-runIde]: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-tasks.html#runIde
[gh:intellij-platform-gradle-plugin-verifyPlugin]: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-tasks.html#verifyPlugin
[gh:releases]: https://github.com/JetBrains/intellij-platform-plugin-template/releases
[gradle]: https://gradle.org
[gradle:build-cache]: https://docs.gradle.org/current/userguide/build_cache.html
[gradle:configuration-cache]: https://docs.gradle.org/current/userguide/configuration_cache.html
[gradle:kotlin-dsl]: https://docs.gradle.org/current/userguide/kotlin_dsl.html
[gradle:lifecycle-tasks]: https://docs.gradle.org/current/userguide/java_plugin.html#lifecycle_tasks
[gradle:releases]: https://gradle.org/releases
[jb:github]: https://github.com/JetBrains/.github/blob/main/profile/README.md
[jb:download-ij]: https://www.jetbrains.com/idea/download
[jb:forum]: https://intellij-support.jetbrains.com/hc/en-us/community/topics/200366979-IntelliJ-IDEA-Open-API-and-Plugin-Development
[jb:ipe]: https://jb.gg/ipe
[jb:my-tokens]: https://plugins.jetbrains.com/author/me/tokens
[jb:paid-plugins]: https://plugins.jetbrains.com/docs/marketplace/paid-plugins-marketplace.html
[jb:quality-guidelines]: https://plugins.jetbrains.com/docs/marketplace/quality-guidelines.html
[jb:slack]: https://plugins.jetbrains.com/slack
[jb:twitter]: https://twitter.com/JBPlatform
[jb:ui-guidelines]: https://jetbrains.github.io/ui
[github-actions-skip-ci]: https://github.blog/changelog/2021-02-08-github-actions-skip-pull-request-and-push-workflows-with-skip-ci/
[keep-a-changelog]: https://keepachangelog.com
[keep-a-changelog-how]: https://keepachangelog.com/en/1.0.0/#how
[semver]: https://semver.org

19
build.gradle.kts Normal file
View File

@ -0,0 +1,19 @@
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
plugins {
id("java")
id("org.jetbrains.kotlin.jvm")
id("org.jetbrains.intellij.platform")
id("org.jetbrains.changelog")
}
dependencies {
testImplementation("junit:junit:4.13.2")
implementation("com.github.mwiede:jsch:0.2.20")
// IntelliJ Platform Gradle Plugin Dependencies Extension - read more: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-dependencies-extension.html
intellijPlatform {
intellijIdeaCommunity("2024.1.7")
testFramework(TestFrameworkType.Platform)
}
}

13
gradle.properties Normal file
View File

@ -0,0 +1,13 @@
group = org.jetbrains.plugins.template
version = 2.6.0
pluginRepositoryUrl = https://github.com/JetBrains/intellij-platform-plugin-template
# 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

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Executable file
View File

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
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 optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"

82
gradlew.bat vendored Normal file
View File

@ -0,0 +1,82 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%

28
settings.gradle.kts Normal file
View File

@ -0,0 +1,28 @@
import org.jetbrains.intellij.platform.gradle.extensions.intellijPlatform
rootProject.name = "IntelliJ Platform Plugin Template"
pluginManagement {
plugins {
id("org.jetbrains.kotlin.jvm") version "2.1.20"
id("org.jetbrains.changelog") version "2.5.0"
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
id("org.jetbrains.intellij.platform.settings") version "2.16.0"
}
@Suppress("UnstableApiUsage")
dependencyResolutionManagement {
// Configure all projects' repositories
repositories {
mavenCentral()
// IntelliJ Platform Gradle Plugin Repositories Extension - read more: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-repositories-extension.html
intellijPlatform {
defaultRepositories()
}
}
}

View File

@ -0,0 +1,125 @@
package com.example.plugin;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.*;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class ChooseServerWidget implements StatusBarWidget,
StatusBarWidget.IconPresentation,
StatusBarWidget.TextPresentation {
private final Project project;
public ChooseServerWidget(Project project) {
this.project = project;
}
@Override
public @NotNull String ID() {
return "SSHRemoteServerWidget";
}
@Override
public @Nullable WidgetPresentation getPresentation(@NotNull PlatformType platformType) {
return this;
}
// ---------- IconPresentation ----------
@Override
public @Nullable Icon getIcon() {
return null;
}
@Override
public @Nullable String getTooltipText() {
return "Click to switch remote server";
}
@Override
public @Nullable Consumer<MouseEvent> getClickConsumer() {
return event -> {
List<SshServer> servers = SshServerManager.getInstance().getServers();
List<String> names = new ArrayList<>();
for (SshServer s : servers) names.add(s.name);
if (names.isEmpty()) names.add("No servers configured");
names.add("Configure servers...");
JBPopupFactory.getInstance()
.createPopupChooserBuilder(names)
.setTitle("Remote servers")
.setItemChosenCallback(selected -> {
if (selected.equals("Configure servers...")) {
openSettings();
return;
}
for (SshServer server : servers) {
if (server.name.equals(selected)) {
switchToServer(server);
return;
}
}
})
.createPopup()
.showUnderneathOf(event.getComponent());
};
}
// ---------- TextPresentation ----------
@Override
public @Nullable String getText() {
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(project.getBasePath());
if (serverId != null) {
Optional<SshServer> server = SshServerManager.getInstance().findServer(serverId);
if (server.isPresent()) return "Remote: " + server.get().name;
}
return "Remote: none";
}
@Override
public float getAlignment() {
return JComponent.CENTER_ALIGNMENT;
}
// ---------- Логика переключения ----------
private void switchToServer(SshServer server) {
SshServerManager.getInstance().setCurrentServerId(server.id);
String localPath = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath)).toString().replace('\\', '/');
for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
if (openProject.getBasePath() != null && openProject.getBasePath().equals(localPath)) {
ApplicationManager.getApplication().invokeLater(() ->
WindowManager.getInstance().getFrame(openProject).toFront());
return;
}
}
if (project != null && !project.isDisposed()) {
ProjectManager.getInstance().closeProject(project);
}
ConnectToRemoteAction.openProjectForServer(server);
}
private void openSettings() {
com.intellij.openapi.options.ShowSettingsUtil.getInstance()
.showSettingsDialog(project, SshServerConfigurable.class);
}
private String sanitize(String input) {
return input.replaceAll("[^a-zA-Z0-9.-]", "_");
}
}

View File

@ -0,0 +1,15 @@
package com.example.plugin;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.StatusBarWidgetProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ChooseServerWidgetProvider implements StatusBarWidgetProvider {
@Nullable
@Override
public StatusBarWidget getWidget(@NotNull Project project) {
return new ChooseServerWidget(project);
}
}

View File

@ -0,0 +1,237 @@
package com.example.plugin;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.jcraft.jsch.*;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import org.jdom.JDOMException;
import java.io.File;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Vector;
public class ConnectToRemoteAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
// Показываем окно настройки серверов
ShowSettingsUtil.getInstance().showSettingsDialog(e.getProject(), SshServerConfigurable.class);
}
// Статический метод для открытия проекта (используется из виджета и действия)
public static void openProjectForServer(SshServer server) {
String localPath = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath)).toString().replace('\\', '/');
// Если папка уже существует, просто открываем
File localDir = new File(localPath);
if (localDir.exists() && localDir.listFiles().length > 0) {
openExistingProject(localPath, server.id);
} else {
// Скачиваем и открываем
downloadAndOpen(localPath, server);
}
}
private static void downloadAndOpen(String localPath, SshServer server) {
ProgressManager.getInstance().run(new Task.Backgroundable(null, "Downloading project...", true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(false);
try {
downloadProject(indicator, localPath, server);
createProjectStructure(new File(localPath));
ApplicationManager.getApplication().invokeLater(() -> openExistingProject(localPath, server.id));
} catch (Exception ex) {
ApplicationManager.getApplication().invokeLater(() ->
Messages.showErrorDialog("Download error: " + ex.getMessage(), "Error"));
}
}
});
}
private static void openExistingProject(String localPath, String serverId) {
ProjectServerMapping.getInstance().setServerIdForProject(localPath, serverId);
try {
ProjectManager.getInstance().loadAndOpenProject(localPath);
} catch (IOException | JDOMException ex) {
ApplicationManager.getApplication().invokeLater(() ->
Messages.showErrorDialog("Ошибка открытия проекта: " + ex.getMessage(), "Ошибка"));
}
}
private static void downloadProject(ProgressIndicator indicator, String localPath, SshServer server) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(server.user, server.host, server.port);
session.setPassword(SshServerManager.getInstance().getPassword(server.id));
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(5000);
ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect(3000);
try {
File localDir = new File(localPath);
if (!localDir.exists()) localDir.mkdirs();
downloadDirContent(sftp, server.remoteProjectPath, localDir, indicator);
} finally {
sftp.disconnect();
session.disconnect();
}
}
private static void downloadDirContent(ChannelSftp sftp, String remoteDir, File localDir, ProgressIndicator indicator) throws SftpException {
@SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> entries = sftp.ls(remoteDir);
for (ChannelSftp.LsEntry entry : entries) {
String filename = entry.getFilename();
if (filename.equals(".") || filename.equals("..")) continue;
String remotePath = remoteDir + "/" + filename;
if (entry.getAttrs().isDir()) {
File subDir = new File(localDir, filename);
if (!subDir.exists()) subDir.mkdirs();
downloadDirContent(sftp, remotePath, subDir, indicator);
} else {
File localFile = new File(localDir, filename);
indicator.setText("Downloading: " + filename);
indicator.setFraction(0.0);
sftp.get(remotePath, localFile.getAbsolutePath());
}
}
}
private static void createProjectStructure(File projectDir) throws IOException {
File ideaDir = new File(projectDir, ".idea");
if (!ideaDir.exists()) ideaDir.mkdirs();
String projectName = projectDir.getName();
writeFile(new File(ideaDir, ".name"), projectName);
writeFile(new File(ideaDir, "modules.xml"),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project version=\"4\">\n" +
" <component name=\"ProjectModuleManager\">\n" +
" <modules>\n" +
" <module fileurl=\"file://$PROJECT_DIR$/remote.iml\" filepath=\"$PROJECT_DIR$/remote.iml\" />\n" +
" </modules>\n" +
" </component>\n" +
"</project>");
writeFile(new File(ideaDir, "misc.xml"),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project version=\"4\">\n" +
" <component name=\"ProjectType\">\n" +
" <option name=\"id\" value=\"unknown\" />\n" +
" </component>\n" +
"</project>");
writeFile(new File(ideaDir, "vcs.xml"),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project version=\"4\">\n" +
" <component name=\"VcsDirectoryMappings\">\n" +
" <mapping directory=\"$PROJECT_DIR$\" vcs=\"\" />\n" +
" </component>\n" +
"</project>");
writeFile(new File(projectDir, "remote.iml"),
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<module type=\"JAVA_MODULE\" version=\"4\">\n" +
" <component name=\"NewModuleRootManager\" inherit-compiler-output=\"true\">\n" +
" <exclude-output />\n" +
" <content url=\"file://$MODULE_DIR$\">\n" +
" <sourceFolder url=\"file://$MODULE_DIR$/src\" isTestSource=\"false\" />\n" +
" </content>\n" +
" <orderEntry type=\"inheritedJdk\" />\n" +
" <orderEntry type=\"sourceFolder\" forTests=\"false\" />\n" +
" </component>\n" +
"</module>");
}
private static void writeFile(File file, String content) throws IOException {
try (Writer writer = new FileWriter(file)) {
writer.write(content);
}
}
private static String sanitize(String input) {
return input.replaceAll("[^a-zA-Z0-9.-]", "_");
}
public static void syncProject(SshServer server, String localPath, ProgressIndicator indicator) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(server.user, server.host, server.port);
session.setPassword(SshServerManager.getInstance().getPassword(server.id));
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(5000);
ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect(3000);
try {
File localDir = new File(localPath);
if (!localDir.exists()) localDir.mkdirs();
syncDir(sftp, server.remoteProjectPath, localDir, indicator);
} finally {
sftp.disconnect();
session.disconnect();
}
}
private static void syncDir(ChannelSftp sftp, String remoteDir, File localDir, ProgressIndicator indicator) {
try {
@SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> entries = sftp.ls(remoteDir);
for (ChannelSftp.LsEntry entry : entries) {
if (indicator.isCanceled()) break;
String filename = entry.getFilename();
if (filename.equals(".") || filename.equals("..")) continue;
String remotePath = remoteDir + "/" + filename;
try {
if (entry.getAttrs().isDir()) {
File subDir = new File(localDir, filename);
if (!subDir.exists()) subDir.mkdirs();
syncDir(sftp, remotePath, subDir, indicator);
} else {
File localFile = new File(localDir, filename);
boolean needDownload = !localFile.exists();
if (!needDownload && localFile.isFile()) {
long remoteSize = entry.getAttrs().getSize();
long remoteMtime = entry.getAttrs().getMTime();
if (localFile.length() != remoteSize || localFile.lastModified() / 1000L != remoteMtime) {
needDownload = true;
}
}
if (needDownload) {
indicator.setText("Syncing: " + filename);
sftp.get(remotePath, localFile.getAbsolutePath());
if (entry.getAttrs().getMTime() > 0) {
localFile.setLastModified(entry.getAttrs().getMTime() * 1000L);
}
}
}
} catch (Exception e) {
// Логируем и пропускаем файл, который не удалось скачать/записать
System.err.println("Skip entry: " + remotePath + " - " + e.getMessage());
}
}
} catch (SftpException e) {
System.err.println("Cannot list directory: " + remoteDir + " - " + e.getMessage());
}
}
}

View File

@ -0,0 +1,47 @@
package com.example.plugin;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
@State(
name = "ProjectMappingService",
storages = { @Storage("ssh-project-mapping.xml") }
)
public class ProjectMappingService implements PersistentStateComponent<ProjectMappingService.State> {
public static class State {
public Map<String, String> hostPathToLocalPath = new HashMap<>();
}
private State myState = new State();
@Nullable
@Override
public State getState() {
return myState;
}
@Override
public void loadState(@NotNull State state) {
XmlSerializerUtil.copyBean(state, myState);
}
public void setLocalPathFor(String host, String remotePath, String localPath) {
myState.hostPathToLocalPath.put(host + ":" + remotePath, localPath);
}
public String getLocalPath(String host, String remotePath) {
return myState.hostPathToLocalPath.get(host + ":" + remotePath);
}
public static ProjectMappingService getInstance() {
return com.intellij.openapi.application.ApplicationManager.getApplication()
.getService(ProjectMappingService.class);
}
}

View File

@ -0,0 +1,53 @@
package com.example.plugin;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
@State(
name = "ProjectServerMapping",
storages = { @Storage("ssh-project-server-mapping.xml") }
)
public class ProjectServerMapping implements PersistentStateComponent<ProjectServerMapping.State> {
public static class State {
// projectBasePath -> serverId
public Map<String, String> mappings = new HashMap<>();
}
private State myState = new State();
@Nullable
@Override
public State getState() {
return myState;
}
@Override
public void loadState(@NotNull State state) {
XmlSerializerUtil.copyBean(state, myState);
}
public String getServerIdForProject(String projectBasePath) {
return myState.mappings.get(projectBasePath);
}
public void setServerIdForProject(String projectBasePath, String serverId) {
myState.mappings.put(projectBasePath, serverId);
}
public void removeProject(String projectBasePath) {
myState.mappings.remove(projectBasePath);
}
public static ProjectServerMapping getInstance() {
return com.intellij.openapi.application.ApplicationManager.getApplication()
.getService(ProjectServerMapping.class);
}
}

View File

@ -0,0 +1,69 @@
package com.example.plugin;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Paths;
import java.util.Optional;
public class RefreshFromServerAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
String projectPath = project.getBasePath();
if (projectPath == null) return;
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(projectPath);
if (serverId == null) {
Messages.showErrorDialog("No server associated with this project.", "Error");
return;
}
Optional<SshServer> maybeServer = SshServerManager.getInstance().findServer(serverId);
if (maybeServer.isEmpty()) {
Messages.showErrorDialog("Server not found.", "Error");
return;
}
SshServer server = maybeServer.get();
ProgressManager.getInstance().run(new Task.Modal(project, "Refreshing from " + server.name, true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
String localRoot = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath))
.toString().replace('\\', '/');
ConnectToRemoteAction.syncProject(server, localRoot, indicator);
// Обновляем виртуальную файловую систему, чтобы IDE увидела изменения
ApplicationManager.getApplication().invokeLater(() -> {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath(localRoot);
if (rootDir != null) {
VfsUtil.markDirtyAndRefresh(true, true, true, rootDir);
}
Messages.showInfoMessage("Project refreshed from " + server.name, "Refresh Complete");
});
} catch (Exception ex) {
ApplicationManager.getApplication().invokeLater(() ->
Messages.showErrorDialog("Refresh failed: " + ex.getMessage(), "Error"));
}
}
});
}
private String sanitize(String input) {
return input.replaceAll("[^a-zA-Z0-9.-]", "_");
}
}

View File

@ -0,0 +1,59 @@
package com.example.plugin;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.jcraft.jsch.*;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Optional;
public class RemoteCommandAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(project.getBasePath());
if (serverId == null) {
Messages.showErrorDialog("No server associated with this project", "Error");
return;
}
Optional<SshServer> maybeServer = SshServerManager.getInstance().findServer(serverId);
if (maybeServer.isEmpty()) return;
SshServer server = maybeServer.get();
String command = Messages.showInputDialog("Enter command to run on " + server.host, "Remote Command", null);
if (command == null || command.isEmpty()) return;
try {
String output = executeCommand(server, command);
Messages.showInfoMessage(output, "Command output");
} catch (Exception ex) {
Messages.showErrorDialog("Command error: " + ex.getMessage(), "Error");
}
}
private String executeCommand(SshServer server, String command) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(server.user, server.host, server.port);
session.setPassword(SshServerManager.getInstance().getPassword(server.id));
session.setConfig("StrictHostKeyChecking", "no");
session.connect(5000);
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.connect();
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) output.append(line).append("\n");
channel.disconnect();
session.disconnect();
return output.toString();
}
}

View File

@ -0,0 +1,56 @@
package com.example.plugin;
import com.intellij.openapi.project.Project;
import com.jcraft.jsch.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
public class SftpSessionManager {
private final ConcurrentHashMap<String, ChannelSftp> channels = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
private final Object lock = new Object();
public ChannelSftp getChannel(SshServer server) throws Exception {
ChannelSftp channel = channels.get(server.id);
if (channel != null && channel.isConnected() && !channel.isClosed()) {
return channel;
}
synchronized (lock) {
channel = channels.get(server.id);
if (channel != null && channel.isConnected() && !channel.isClosed()) return channel;
JSch jsch = new JSch();
Session session = jsch.getSession(server.user, server.host, server.port);
session.setPassword(SshServerManager.getInstance().getPassword(server.id));
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(5000);
ChannelSftp newChannel = (ChannelSftp) session.openChannel("sftp");
newChannel.connect(3000);
sessions.put(server.id, session);
channels.put(server.id, newChannel);
return newChannel;
}
}
public void disconnect() {
synchronized (lock) {
for (ChannelSftp ch : channels.values()) {
if (ch.isConnected()) ch.disconnect();
}
for (Session s : sessions.values()) {
if (s.isConnected()) s.disconnect();
}
channels.clear();
sessions.clear();
}
}
public static SftpSessionManager getInstance(Project project) {
return project.getService(SftpSessionManager.class);
}
}

View File

@ -0,0 +1,51 @@
package com.example.plugin;
import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@State(
name = "SshConnectionState",
storages = { @Storage("ssh-connection.xml") }
)
public class SshConnectionState implements PersistentStateComponent<SshConnectionState> {
public String host = "";
public int port = 22;
public String user = "";
public String remoteProjectPath = "/home/user/project";
public String getPassword() {
CredentialAttributes attributes = createCredentialAttributes();
return PasswordSafe.getInstance().getPassword(attributes);
}
public void setPassword(String password) {
CredentialAttributes attributes = createCredentialAttributes();
PasswordSafe.getInstance().setPassword(attributes, password);
}
private CredentialAttributes createCredentialAttributes() {
return new CredentialAttributes("SshRemotePlugin." + host + "." + user);
}
@Nullable
@Override
public SshConnectionState getState() {
return this;
}
@Override
public void loadState(@NotNull SshConnectionState state) {
XmlSerializerUtil.copyBean(state, this);
}
public static SshConnectionState getInstance() {
return com.intellij.openapi.application.ApplicationManager.getApplication()
.getService(SshConnectionState.class);
}
}

View File

@ -0,0 +1,39 @@
package com.example.plugin;
import java.util.Objects;
import java.util.UUID;
public class SshServer {
public String id;
public String name;
public String host;
public int port = 22;
public String user;
public String remoteProjectPath;
public SshServer() {
this.id = UUID.randomUUID().toString();
}
public SshServer(String id, String name, String host, int port, String user, String remoteProjectPath) {
this.id = id != null ? id : UUID.randomUUID().toString();
this.name = name;
this.host = host;
this.port = port;
this.user = user;
this.remoteProjectPath = remoteProjectPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SshServer server = (SshServer) o;
return Objects.equals(id, server.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -0,0 +1,217 @@
package com.example.plugin;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class SshServerConfigurable implements Configurable {
private JPanel mainPanel;
private JBTable table;
private ServerTableModel tableModel;
private boolean modified = false;
@Nls(capitalization = Nls.Capitalization.Title)
@Override
public String getDisplayName() {
return "SSH Remote Project";
}
@Nullable
@Override
public JComponent createComponent() {
List<SshServer> servers = SshServerManager.getInstance().getServers();
tableModel = new ServerTableModel(new ArrayList<>(servers));
table = new JBTable(tableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ToolbarDecorator decorator = ToolbarDecorator.createDecorator(table)
.setAddAction(button -> addServer())
.setEditAction(button -> editServer())
.setRemoveAction(button -> removeServer());
mainPanel = new JPanel(new BorderLayout());
mainPanel.add(decorator.createPanel(), BorderLayout.CENTER);
mainPanel.setBorder(JBUI.Borders.empty(10));
return mainPanel;
}
private void addServer() {
SshServer newServer = new SshServer();
ServerDialog dialog = new ServerDialog(mainPanel, "Add Server", newServer);
if (dialog.showAndGet()) {
SshServerManager.getInstance().addServer(dialog.getServer());
tableModel.servers.add(dialog.getServer());
tableModel.fireTableDataChanged();
modified = true;
}
}
private void editServer() {
int row = table.getSelectedRow();
if (row < 0) return;
SshServer server = tableModel.servers.get(row);
ServerDialog dialog = new ServerDialog(mainPanel, "Edit Server", server);
if (dialog.showAndGet()) {
SshServer updated = dialog.getServer();
SshServerManager.getInstance().updateServer(updated);
tableModel.servers.set(row, updated);
tableModel.fireTableRowsUpdated(row, row);
modified = true;
}
}
private void removeServer() {
int row = table.getSelectedRow();
if (row < 0) return;
SshServer server = tableModel.servers.get(row);
int result = Messages.showYesNoDialog(mainPanel,
"Удалить сервер \"" + server.name + "\"?", "Подтверждение", null);
if (result == Messages.YES) {
SshServerManager.getInstance().removeServer(server.id);
tableModel.servers.remove(row);
tableModel.fireTableRowsDeleted(row, row);
modified = true;
}
}
@Override
public boolean isModified() {
return modified;
}
@Override
public void apply() throws ConfigurationException {
// все изменения уже применены в SshServerManager
modified = false;
}
@Override
public void reset() {
tableModel.servers.clear();
tableModel.servers.addAll(SshServerManager.getInstance().getServers());
tableModel.fireTableDataChanged();
modified = false;
}
// ----- Таблица -----
private static class ServerTableModel extends AbstractTableModel {
private final String[] columns = {"Name", "Host", "User", "Remote Path"};
public final List<SshServer> servers;
ServerTableModel(List<SshServer> servers) {
this.servers = servers;
}
@Override public int getRowCount() { return servers.size(); }
@Override public int getColumnCount() { return columns.length; }
@Override public String getColumnName(int col) { return columns[col]; }
@Override public Object getValueAt(int row, int col) {
SshServer s = servers.get(row);
switch (col) {
case 0: return s.name;
case 1: return s.host;
case 2: return s.user;
case 3: return s.remoteProjectPath;
default: return "";
}
}
}
}
// ----- Диалог редактирования сервера -----
class ServerDialog extends DialogWrapper {
private final JTextField nameField = new JTextField(20);
private final JTextField hostField = new JTextField(20);
private final JTextField portField = new JTextField("22", 5);
private final JTextField userField = new JTextField(20);
private final JPasswordField passwordField = new JPasswordField(20);
private final JTextField remotePathField = new JTextField(30);
private SshServer server;
protected ServerDialog(Component parent, String title, SshServer server) {
super(parent, true);
setTitle(title);
this.server = server;
init();
// Заполняем поля
nameField.setText(server.name);
hostField.setText(server.host);
portField.setText(String.valueOf(server.port));
userField.setText(server.user);
remotePathField.setText(server.remoteProjectPath);
// Пароль загружаем из хранилища
String savedPassword = SshServerManager.getInstance().getPassword(server.id);
if (savedPassword != null) passwordField.setText(savedPassword);
}
@Override
protected @Nullable JComponent createCenterPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = JBUI.insets(4);
gbc.gridx = 0; gbc.gridy = 0; panel.add(new JLabel("Name:"), gbc);
gbc.gridx = 1; panel.add(nameField, gbc);
gbc.gridx = 0; gbc.gridy++; panel.add(new JLabel("Host:"), gbc);
gbc.gridx = 1; panel.add(hostField, gbc);
gbc.gridx = 0; gbc.gridy++; panel.add(new JLabel("Port:"), gbc);
gbc.gridx = 1; panel.add(portField, gbc);
gbc.gridx = 0; gbc.gridy++; panel.add(new JLabel("User:"), gbc);
gbc.gridx = 1; panel.add(userField, gbc);
gbc.gridx = 0; gbc.gridy++; panel.add(new JLabel("Password:"), gbc);
gbc.gridx = 1; panel.add(passwordField, gbc);
gbc.gridx = 0; gbc.gridy++; panel.add(new JLabel("Remote Path:"), gbc);
gbc.gridx = 1; panel.add(remotePathField, gbc);
return panel;
}
@Override
protected @NotNull List<ValidationInfo> doValidateAll() {
List<ValidationInfo> result = new ArrayList<>();
if (nameField.getText().trim().isEmpty()) result.add(new ValidationInfo("Name required", nameField));
if (hostField.getText().trim().isEmpty()) result.add(new ValidationInfo("Host required", hostField));
if (userField.getText().trim().isEmpty()) result.add(new ValidationInfo("User required", userField));
try { Integer.parseInt(portField.getText()); } catch (NumberFormatException e) {
result.add(new ValidationInfo("Invalid port", portField));
}
if (remotePathField.getText().trim().isEmpty()) result.add(new ValidationInfo("Remote path required", remotePathField));
return result;
}
@Override
protected void doOKAction() {
if (doValidateAll().isEmpty()) {
server.name = nameField.getText().trim();
server.host = hostField.getText().trim();
server.port = Integer.parseInt(portField.getText().trim());
server.user = userField.getText().trim();
server.remoteProjectPath = remotePathField.getText().trim();
// Сохраняем пароль, только если он не пустой
String pass = new String(passwordField.getPassword());
if (!pass.isEmpty()) {
SshServerManager.getInstance().setPassword(server.id, pass);
}
// Если поле пустое оставляем старый пароль (если есть) нетронутым
super.doOKAction();
}
}
public SshServer getServer() {
return server;
}
}

View File

@ -0,0 +1,106 @@
package com.example.plugin;
import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@State(
name = "SshServerManager",
storages = { @Storage("ssh-servers.xml") }
)
public class SshServerManager implements PersistentStateComponent<SshServerManager.State> {
public static class State {
public List<SshServer> servers = new ArrayList<>();
public String currentServerId;
}
private State myState = new State();
@Nullable
@Override
public State getState() {
return myState;
}
@Override
public void loadState(@NotNull State state) {
XmlSerializerUtil.copyBean(state, myState);
}
// ---------- CRUD ----------
public List<SshServer> getServers() {
return myState.servers;
}
public Optional<SshServer> findServer(String id) {
return myState.servers.stream().filter(s -> s.id.equals(id)).findFirst();
}
public void addServer(SshServer server) {
myState.servers.add(server);
}
public void removeServer(String id) {
myState.servers.removeIf(s -> s.id.equals(id));
if (id.equals(myState.currentServerId)) {
myState.currentServerId = null;
}
// Удаляем сохранённый пароль
PasswordSafe.getInstance().setPassword(createCredentialAttributes(id), null);
}
public void updateServer(SshServer updated) {
for (int i = 0; i < myState.servers.size(); i++) {
if (myState.servers.get(i).id.equals(updated.id)) {
myState.servers.set(i, updated);
break;
}
}
}
// ---------- Текущий сервер ----------
public String getCurrentServerId() {
return myState.currentServerId;
}
public void setCurrentServerId(String id) {
myState.currentServerId = id;
}
public Optional<SshServer> getCurrentServer() {
return Optional.ofNullable(myState.currentServerId).flatMap(this::findServer);
}
// ---------- Пароль ----------
public String getPassword(String serverId) {
return PasswordSafe.getInstance().getPassword(createCredentialAttributes(serverId));
}
public void setPassword(String serverId, String password) {
PasswordSafe.getInstance().setPassword(createCredentialAttributes(serverId), password);
}
private CredentialAttributes createCredentialAttributes(String serverId) {
return new CredentialAttributes("SshRemotePlugin.server." + serverId);
}
// ---------- Singleton ----------
public static SshServerManager getInstance() {
return com.intellij.openapi.application.ApplicationManager.getApplication()
.getService(SshServerManager.class);
}
}

View File

@ -0,0 +1,174 @@
package com.example.plugin;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.*;
import com.jcraft.jsch.*;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SuppressWarnings("deprecation")
public class SshSyncStartupActivity implements StartupActivity {
private static final ExecutorService uploadExecutor = Executors.newSingleThreadExecutor();
@Override
public void runActivity(@NotNull Project project) {
// При закрытии проекта разрываем SFTP-подключение
project.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
@Override
public void projectClosed(@NotNull Project closedProject) {
if (closedProject.equals(project)) {
SftpSessionManager.getInstance(project).disconnect();
}
}
});
// Слушатель изменений файлов для синхронизации
VirtualFile baseDir = project.getBaseDir();
if (baseDir != null) {
VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileListener() {
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
syncFile(event.getFile(), project);
}
@Override
public void fileCreated(@NotNull VirtualFileEvent event) {
syncFile(event.getFile(), project);
}
private void syncFile(VirtualFile file, Project project) {
if (!file.isDirectory()) {
uploadFile(file, project);
}
}
}, project);
}
// === Автосинхронизация при открытии проекта ===
String projectPath = project.getBasePath();
if (projectPath != null) {
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(projectPath);
if (serverId != null) {
Optional<SshServer> maybeServer = SshServerManager.getInstance().findServer(serverId);
if (maybeServer.isPresent()) {
SshServer server = maybeServer.get();
// Модальный диалог блокирует IDE до завершения синхронизации
ApplicationManager.getApplication().invokeLater(() -> {
ProgressManager.getInstance().run(new Task.Modal(project, "Synchronizing with " + server.name, true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
String localRoot = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath))
.toString().replace('\\', '/');
ConnectToRemoteAction.syncProject(server, localRoot, indicator);
// Обновляем виртуальную файловую систему, чтобы IDE увидела изменения
ApplicationManager.getApplication().invokeLater(() -> {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath(localRoot);
if (rootDir != null) {
VfsUtil.markDirtyAndRefresh(true, true, true, rootDir);
}
});
} catch (Exception e) {
ApplicationManager.getApplication().invokeLater(() ->
Messages.showErrorDialog("Sync failed: " + e.getMessage(), "Sync Error"));
}
}
});
});
}
}
}
}
private void uploadFile(VirtualFile localFile, Project project) {
String projectPath = project.getBasePath();
if (projectPath == null) return;
// Определяем привязанный сервер
String serverId = ProjectServerMapping.getInstance().getServerIdForProject(projectPath);
if (serverId == null) return;
Optional<SshServer> maybeServer = SshServerManager.getInstance().findServer(serverId);
if (maybeServer.isEmpty()) return;
SshServer server = maybeServer.get();
// Вычисляем локальный корень проекта (как он был сохранен при создании)
String localRoot = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath))
.toString().replace('\\', '/');
String localFilePath = localFile.getPath(); // всегда с прямыми слешами
// Игнорируем служебные файлы IDE
if (localFilePath.contains("/.idea/") || localFile.getName().equals("remote.iml")) {
return;
}
// Проверяем, что файл принадлежит проекту
if (!localFilePath.startsWith(localRoot)) {
return;
}
// Относительный путь и удалённый путь
String relativePath = localFilePath.substring(localRoot.length());
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
String remoteFilePath = server.remoteProjectPath + "/" + relativePath;
// Отправляем файл в отдельном потоке через общее SFTP-соединение
uploadExecutor.submit(() -> {
try {
ChannelSftp sftp = SftpSessionManager.getInstance(project).getChannel(server);
String remoteParent = remoteFilePath.substring(0, remoteFilePath.lastIndexOf('/'));
createRemoteDirs(sftp, remoteParent);
sftp.put(localFilePath, remoteFilePath);
} catch (Exception e) {
ApplicationManager.getApplication().invokeLater(() ->
com.intellij.openapi.ui.Messages.showErrorDialog(
"Sync error " + localFile.getName() + ": " + e.getMessage(),
"SFTP Error"
)
);
}
});
}
private void createRemoteDirs(ChannelSftp sftp, String dir) throws SftpException {
if (dir.isEmpty() || dir.equals("/")) return;
String[] parts = dir.split("/");
StringBuilder path = new StringBuilder();
for (String part : parts) {
if (part.isEmpty()) continue;
path.append("/").append(part);
try {
sftp.stat(path.toString());
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
sftp.mkdir(path.toString());
} else {
throw e;
}
}
}
}
private String sanitize(String input) {
return input.replaceAll("[^a-zA-Z0-9.-]", "_");
}
}

View File

@ -0,0 +1,75 @@
package com.example.plugin;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.WindowManager;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class SwitchServerAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
if (project == null) return;
List<SshServer> servers = SshServerManager.getInstance().getServers();
if (servers.isEmpty()) {
Messages.showInfoMessage("No servers configured. Add them in Settings -> SSH Remote Project.", "No Servers");
return;
}
List<String> names = new ArrayList<>();
for (SshServer s : servers) names.add(s.name);
JBPopupFactory.getInstance()
.createPopupChooserBuilder(names)
.setTitle("Switch Remote Server")
.setItemChosenCallback(selected -> {
for (SshServer server : servers) {
if (server.name.equals(selected)) {
switchToServer(server, project);
return;
}
}
})
.createPopup()
.showInFocusCenter();
}
private void switchToServer(SshServer server, Project currentProject) {
SshServerManager.getInstance().setCurrentServerId(server.id);
String localPath = Paths.get(System.getProperty("user.home"), "ssh-remote-projects",
sanitize(server.host), sanitize(server.remoteProjectPath))
.toString().replace('\\', '/');
// Проверяем, открыт ли уже проект с этим путём
for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {
if (openProject.getBasePath() != null && openProject.getBasePath().equals(localPath)) {
ApplicationManager.getApplication().invokeLater(() ->
WindowManager.getInstance().getFrame(openProject).toFront());
return;
}
}
// Закрываем текущий проект и открываем новый
if (currentProject != null && !currentProject.isDisposed()) {
ProjectManager.getInstance().closeProject(currentProject);
}
ConnectToRemoteAction.openProjectForServer(server);
}
private String sanitize(String input) {
return input.replaceAll("[^a-zA-Z0-9.-]", "_");
}
}

View File

@ -0,0 +1,23 @@
package org.jetbrains.plugins.template
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) {
operator fun get(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getMessage(key, *params)
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getLazyMessage(key, *params)
}

View File

@ -0,0 +1,17 @@
package org.jetbrains.plugins.template.services
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import org.jetbrains.plugins.template.MyBundle
@Service(Service.Level.PROJECT)
class MyProjectService(project: Project) {
init {
thisLogger().info(MyBundle["projectService", project.name])
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
fun getRandomNumber() = (1..100).random()
}

View File

@ -0,0 +1,12 @@
package org.jetbrains.plugins.template.startup
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectActivity
class MyProjectActivity : ProjectActivity {
override suspend fun execute(project: Project) {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
}

View File

@ -0,0 +1,45 @@
package org.jetbrains.plugins.template.toolWindow
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.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.content.ContentFactory
import org.jetbrains.plugins.template.MyBundle
import org.jetbrains.plugins.template.services.MyProjectService
import javax.swing.JButton
class MyToolWindowFactory : ToolWindowFactory {
init {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val myToolWindow = MyToolWindow(toolWindow)
val content = ContentFactory.getInstance().createContent(myToolWindow.getContent(), null, false)
toolWindow.contentManager.addContent(content)
}
override fun shouldBeAvailable(project: Project) = true
class MyToolWindow(toolWindow: ToolWindow) {
private val service = toolWindow.project.service<MyProjectService>()
fun getContent() = JBPanel<JBPanel<*>>().apply {
val label = JBLabel(MyBundle["randomLabel", "?"])
add(label)
add(JButton(MyBundle["shuffle"]).apply {
addActionListener {
label.text = MyBundle["randomLabel", service.getRandomNumber()]
}
})
}
}
}

View File

@ -0,0 +1,67 @@
<idea-plugin>
<id>com.example.ssh.remote.plugin</id>
<name>SSH Remote Sync</name>
<vendor>Your Name</vendor>
<description><![CDATA[
<h2>SSH Remote Sync</h2>
<p>Работайте с кодом на удалённых серверах так же удобно, как с локальным проектом. Плагин автоматически синхронизирует файлы при сохранении, поддерживает список виртуальных машин и переключение между ними.</p>
<h3>Основные возможности</h3>
<ul>
<li><b>Менеджер серверов</b> добавляйте несколько ВМ с адресами, пользователями и паролями. Пароли надёжно хранятся в системном хранилище IDE.</li>
<li><b>Открытие удалённого проекта</b> плагин скачивает проект с сервера в локальную папку и открывает его в IDE как обычный проект.</li>
<li><b>Автосинхронизация при сохранении</b> каждое нажатие Ctrl+S мгновенно отправляет изменённый файл на сервер.</li>
<li><b>Обновление с сервера</b> кнопка Refresh загружает все изменения с сервера, даже если они были сделаны кем-то другим.</li>
<li><b>Выполнение команд</b> можно запустить любую команду на привязанном сервере прямо из IDE.</li>
<li><b>Переключение между серверами</b> быстрое переключение между проектами разных ВМ без ручного поиска файлов.</li>
</ul>
<h3>Как начать</h3>
<ol>
<li>Откройте <b>File → Settings → SSH Remote Project</b> и добавьте сервер (хост, порт, логин, пароль, путь к проекту).</li>
<li>Выберите <b>Tools → SSH Remote Manager → Switch Remote Server</b> и укажите нужный сервер. Проект откроется в отдельном окне.</li>
<li>Редактируйте файлы при сохранении они автоматически уйдут на сервер.</li>
<li>Чтобы подтянуть изменения с сервера, используйте <b>Tools → SSH Remote Manager → Refresh from Server</b>.</li>
</ol>
<p><i>Плагин работает в Community Edition и совместим с IntelliJ IDEA 2024.1.7 и новее.</i></p>
]]>
</description>
<depends>com.intellij.modules.platform</depends>
<extensions defaultExtensionNs="com.intellij">
<projectConfigurable instance="com.example.plugin.SshServerConfigurable"
displayName="SSH Remote Project"/>
<applicationService serviceImplementation="com.example.plugin.SshServerManager"/>
<applicationService serviceImplementation="com.example.plugin.ProjectServerMapping"/>
<projectService serviceImplementation="com.example.plugin.SftpSessionManager"/>
<applicationService serviceImplementation="com.example.plugin.ProjectMappingService"/>
<postStartupActivity implementation="com.example.plugin.SshSyncStartupActivity"/>
</extensions>
<actions>
<group id="SshRemote.MainGroup"
text="SSH Remote Manager"
description="SSH Remote Project actions"
popup="true">
<action id="SshRemote.ConfigureServers"
class="com.example.plugin.ConnectToRemoteAction"
text="Configure SSH Servers"
description="Add or remove remote servers"/>
<action id="SshRemote.SwitchServer"
class="com.example.plugin.SwitchServerAction"
text="Switch Remote Server"
description="Switch to a different remote server"/>
<action id="SshRemote.RefreshFromServer"
class="com.example.plugin.RefreshFromServerAction"
text="Refresh from Server"
description="Synchronize local project with the associated remote server"/>
<action id="SshRemote.RemoteCommand"
class="com.example.plugin.RemoteCommandAction"
text="Run Remote Command"
description="Execute command on the associated server"/>
<add-to-group group-id="ToolsMenu" anchor="last"/>
</group>
</actions>
</idea-plugin>

View File

@ -0,0 +1,3 @@
projectService=Project service: {0}
randomLabel=The random number is: {0}
shuffle=Shuffle

View File

@ -0,0 +1,39 @@
package org.jetbrains.plugins.template
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 org.jetbrains.plugins.template.services.MyProjectService
@TestDataPath("\$CONTENT_ROOT/src/test/testData")
class MyPluginTest : BasePlatformTestCase() {
fun testXMLFile() {
val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "<foo>bar</foo>")
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<MyProjectService>()
assertNotSame(projectService.getRandomNumber(), projectService.getRandomNumber())
}
override fun getTestDataPath() = "src/test/testData/rename"
}

View File

@ -0,0 +1,3 @@
<root>
<a<caret>1>Foo</a1>
</root>

View File

@ -0,0 +1,3 @@
<root>
<a2>Foo</a2>
</root>