├── .github
└── workflows
│ └── mavenBuild.yml
├── .gitignore
├── LICENSE
├── README.md
├── data
├── components.json
├── jvms.json
└── pnx.ico
├── lang
└── ZH-README.md
├── pom.xml
├── src
└── main
│ ├── java
│ └── cn
│ │ └── powernukkitx
│ │ └── cli
│ │ ├── App.java
│ │ ├── CLIConstant.java
│ │ ├── Main.java
│ │ ├── Preprocessor.java
│ │ ├── cmd
│ │ ├── StartCommand.java
│ │ └── SysInstallCommand.java
│ │ ├── data
│ │ ├── bean
│ │ │ ├── ArtifactBean.java
│ │ │ ├── BuildBean.java
│ │ │ ├── GitHubArtifactBean.java
│ │ │ ├── ReleaseBean.java
│ │ │ ├── RemoteFileBean.java
│ │ │ └── RequestIDBean.java
│ │ ├── builder
│ │ │ └── JVMStartCommandBuilder.java
│ │ ├── converter
│ │ │ └── LocaleConverter.java
│ │ ├── locator
│ │ │ ├── GraalJITLocator.java
│ │ │ ├── GraalModuleLocator.java
│ │ │ ├── JarLocator.java
│ │ │ ├── JavaLocator.java
│ │ │ ├── LibsLocator.java
│ │ │ ├── Location.java
│ │ │ └── Locator.java
│ │ └── remote
│ │ │ ├── VersionListHelper.java
│ │ │ └── VersionListHelperV2.java
│ │ └── util
│ │ ├── CollectionUtils.java
│ │ ├── CompressUtils.java
│ │ ├── ConfigUtils.java
│ │ ├── EnumOS.java
│ │ ├── EnvEntry.java
│ │ ├── FileUtils.java
│ │ ├── GitUtils.java
│ │ ├── HttpUtils.java
│ │ ├── INIParser.java
│ │ ├── InputUtils.java
│ │ ├── Logger.java
│ │ ├── NullUtils.java
│ │ ├── OSUtils.java
│ │ └── StringUtils.java
│ └── resources
│ ├── META-INF
│ └── native-image
│ │ └── pnx-cli
│ │ └── resource-config.json
│ ├── bin
│ ├── GSharpTools.dll
│ ├── log4net.dll
│ └── pathed.exe
│ └── cn
│ └── powernukkitx
│ └── cli
│ ├── App.properties
│ ├── Preprocessor.properties
│ ├── cmd
│ ├── Start.properties
│ ├── SysInstall.properties
│ └── Update.properties
│ └── util
│ ├── Http.properties
│ └── Input.properties
└── tool
└── rcedit-x64.exe
/.github/workflows/mavenBuild.yml:
--------------------------------------------------------------------------------
1 | name: Maven构建
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 | check-files:
11 | name: 检查仓库文件
12 | runs-on: ubuntu-latest
13 | outputs:
14 | changed-files: ${{ steps.check-changed-files.outputs.all_changed_and_modified_files }}
15 |
16 | steps:
17 | - name: 检出仓库内容
18 | uses: actions/checkout@v2
19 | with:
20 | fetch-depth: 0
21 |
22 | - name: 检查文件改动情况
23 | id: check-changed-files
24 | uses: tj-actions/changed-files@v11.4
25 | with:
26 | since_last_remote_commit: 'true'
27 |
28 | - name: 输出更改文件列表
29 | run: echo ${{ steps.check-changed-files.outputs.all_changed_and_modified_files }}
30 |
31 | windows-x86-build:
32 | name: Windows x86 构建
33 | runs-on: windows-latest
34 | needs: check-files
35 | if: contains(needs.check-files.outputs.changed-files, 'src/') || (github.event_name == 'push' && contains(github.event.commits[0].message, '+b'))
36 |
37 | steps:
38 | - name: 检出仓库内容
39 | uses: actions/checkout@v2
40 |
41 | - name: 缓存Maven依赖项
42 | id: cache
43 | uses: actions/cache@v2
44 | with:
45 | path: |
46 | ~/.m2/repository
47 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}-PNX-CLI-WINDOWS-X86
48 | restore-keys: |
49 | ${{ runner.os }}-PNX-CLI-WINDOWS-X86
50 |
51 | - uses: graalvm/setup-graalvm@v1
52 | with:
53 | java-version: '21'
54 | distribution: 'graalvm'
55 | github-token: ${{ secrets.GITHUB_TOKEN }}
56 |
57 | - name: Maven构建
58 | run: mvn -B package --file pom.xml
59 |
60 | - id: get-version
61 | uses: jactions/maven-version@v1.2.0
62 |
63 | - name: 配置msvc环境
64 | uses: ilammy/msvc-dev-cmd@v1
65 | with:
66 | arch: amd64
67 |
68 | - name: 本机静态编译
69 | shell: cmd
70 | run: |
71 | chcp 936
72 | cd .\target
73 | native-image -jar PNX-CLI-${{ steps.get-version.outputs.version }}.jar -Dfile.encoding=GBK -H:Name=pnx -H:-CheckToolchain
74 |
75 | - name: 添加图标
76 | shell: cmd
77 | run: tool\rcedit-x64 "target\pnx.exe" --set-icon "data\pnx.ico"
78 |
79 | - name: 上传可执行文件
80 | uses: actions/upload-artifact@v2
81 | with:
82 | name: PNX-CLI-Windows-x86
83 | path: target/pnx.exe
84 |
85 | linux-x86-build:
86 | name: Linux x86 构建
87 | runs-on: ubuntu-20.04
88 | needs: check-files
89 | if: contains(needs.check-files.outputs.changed-files, 'src/') || (github.event_name == 'push' && contains(github.event.commits[0].message, '+b'))
90 |
91 | steps:
92 | - name: 检出仓库内容
93 | uses: actions/checkout@v2
94 |
95 | - name: 缓存Maven依赖项
96 | id: cache
97 | uses: actions/cache@v2
98 | with:
99 | path: |
100 | ~/.m2/repository
101 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}-PNX-CLI-LINUX-X86
102 | restore-keys: |
103 | ${{ runner.os }}-PNX-CLI-LINUX-X86
104 |
105 | - uses: graalvm/setup-graalvm@v1
106 | with:
107 | java-version: '21'
108 | distribution: 'graalvm'
109 | github-token: ${{ secrets.GITHUB_TOKEN }}
110 |
111 | - name: Maven构建
112 | run: mvn -B package --file pom.xml
113 |
114 | - id: get-version
115 | uses: jactions/maven-version@v1.2.0
116 |
117 | - name: 配置GCC环境
118 | uses: egor-tensin/setup-gcc@v1
119 | with:
120 | version: latest
121 | platform: x64
122 |
123 | - name: 本机静态编译
124 | run: |
125 | cd target
126 | native-image -jar PNX-CLI-${{ steps.get-version.outputs.version }}.jar -H:Name=pnx
127 |
128 | - name: 上传jar包
129 | uses: actions/upload-artifact@v2
130 | with:
131 | name: PNX-CLI-Jar
132 | path: target/PNX-CLI-*.jar
133 |
134 | - name: 上传可执行文件
135 | uses: actions/upload-artifact@v2
136 | with:
137 | name: PNX-CLI-Linux-x86
138 | path: target/pnx
139 |
140 | # linux-arm-build:
141 | # name: Linux arm 构建
142 | # runs-on: self-hosted
143 | # needs: check-files
144 | # if: contains(needs.check-files.outputs.changed-files, 'src/') || (github.event_name == 'push' && contains(github.event.commits[0].message, '+b'))
145 | #
146 | # steps:
147 | # - name: 检出仓库内容
148 | # uses: actions/checkout@v2
149 | #
150 | # - name: Maven构建
151 | # run: mvn -B package --file pom.xml
152 | #
153 | # - id: get-version
154 | # uses: jactions/maven-version@v1.2.0
155 | #
156 | # - name: 本机静态编译
157 | # run: |
158 | # cd target
159 | # native-image -jar PNX-CLI-${{ steps.get-version.outputs.version }}.jar -H:Name=pnx
160 | #
161 | # - name: 上传可执行文件
162 | # uses: actions/upload-artifact@v2
163 | # with:
164 | # name: PNX-CLI-Linux-arm
165 | # path: target/pnx
166 |
167 | release:
168 | name: 发布发行版
169 | runs-on: ubuntu-latest
170 | needs: [ windows-x86-build, linux-x86-build ]
171 | if: startsWith(github.ref, 'refs/heads/master')
172 |
173 | steps:
174 | - name: 检出仓库内容
175 | uses: actions/checkout@v2
176 | with:
177 | fetch-depth: 0
178 | - id: get-version
179 | uses: jactions/maven-version@v1.2.0
180 | - name: 下载Windows x86可执行文件
181 | uses: actions/download-artifact@v2
182 | with:
183 | name: PNX-CLI-Windows-x86
184 | path: target/windows-x86
185 | - name: 下载Linux x86可执行文件
186 | uses: actions/download-artifact@v2
187 | with:
188 | name: PNX-CLI-Linux-x86
189 | path: target/linux-x86
190 | - name: 下载jar包
191 | uses: actions/download-artifact@v2
192 | with:
193 | name: PNX-CLI-Jar
194 | path: target/jar
195 | - name: 压缩可执行文件
196 | run: |
197 | zip -r PNX-CLI-Windows-x86.zip target/windows-x86/pnx.exe
198 | zip -r PNX-CLI-Linux-x86.zip target/linux-x86/pnx
199 | - name: 创建发行版
200 | uses: softprops/action-gh-release@v1
201 | with:
202 | files: |
203 | PNX-CLI-Windows-x86.zip
204 | PNX-CLI-Linux-x86.zip
205 | target/jar/PNX-CLI-${{ steps.get-version.outputs.version }}.jar
206 | draft: false
207 | prerelease: true
208 | tag_name: ${{ steps.get-version.outputs.version }}
209 | name: PNX-CLI v${{ steps.get-version.outputs.version }}
210 | body: ${{ github.sha }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.idea/
2 | /target/
3 | /dependency-reduced-pom.xml
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PNX-CLI
2 | PNX-CLI is a command line tool for PNX. It can help you start PNX quickly.
3 | windows using . \pnx.exe to run.
4 | linux use . /pnx to run.
--------------------------------------------------------------------------------
/data/components.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "graaljit",
4 | "version": "22.2.0",
5 | "description": {
6 | "en": "Graal JIT compiler",
7 | "zh": "Graal即时编译器"
8 | },
9 | "clear": [
10 | "components/graaljit"
11 | ],
12 | "files": [
13 | {
14 | "name": "compiler-22.2.0.jar",
15 | "into": "components/graaljit/compiler-22.2.0.jar",
16 | "url": "https://assets.powernukkitx.cn/components/graaljit/compiler-22.2.0.jar"
17 | },
18 | {
19 | "name": "compiler-management-22.2.0.jar",
20 | "into": "components/graaljit/compiler-management-22.2.0.jar",
21 | "url": "https://assets.powernukkitx.cn/components/graaljit/compiler-management-22.2.0.jar"
22 | }
23 | ]
24 | }
25 | ]
--------------------------------------------------------------------------------
/data/jvms.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "OracleJDK",
4 | "download": {
5 | "windows-x86": {
6 | "url": "https://download.oracle.com/java/17/latest/jdk-17_windows-x64_bin.zip",
7 | "size": "172MB"
8 | },
9 | "linux-x86": {
10 | "url": "https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.tar.gz",
11 | "size": "172MB"
12 | },
13 | "linux-aarch": {
14 | "url": "https://download.oracle.com/java/17/latest/jdk-17_linux-aarch64_bin.tar.gz",
15 | "size": "172MB"
16 | },
17 | "macos-x86": {
18 | "url": "https://download.oracle.com/java/17/latest/jdk-17_macos-x64_bin.tar.gz",
19 | "size": "172MB"
20 | },
21 | "macos-aarch": {
22 | "url": "https://download.oracle.com/java/17/latest/jdk-17_macos-aarch64_bin.tar.gz",
23 | "size": "172MB"
24 | }
25 | }
26 | },
27 | {
28 | "name": "GraalVM",
29 | "download": {
30 | "windows-x86": {
31 | "url": "https://download.oracle.com/graalvm/20/latest/graalvm-jdk-20_windows-x64_bin.zip",
32 | "size": "312MB"
33 | },
34 | "linux-x86": {
35 | "url": "https://download.oracle.com/graalvm/20/latest/graalvm-jdk-20_linux-x64_bin.tar.gz",
36 | "size": "329MB"
37 | },
38 | "linux-aarch": {
39 | "url": "https://download.oracle.com/graalvm/20/latest/graalvm-jdk-20_linux-aarch64_bin.tar.gz",
40 | "size": "310MB"
41 | },
42 | "macos-x86": {
43 | "url": "https://download.oracle.com/graalvm/20/latest/graalvm-jdk-20_macos-x64_bin.tar.gz",
44 | "size": "312MB"
45 | },
46 | "macos-aarch": {
47 | "url": "https://download.oracle.com/graalvm/20/latest/graalvm-jdk-20_macos-aarch64_bin.tar.gz",
48 | "size": "363MB"
49 | }
50 | }
51 | },
52 | {
53 | "name": "AdoptOpenJDK",
54 | "download": {
55 | "windows-x86": {
56 | "url": "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jre/x64/windows/OpenJDK17U-jre_x64_windows_hotspot_17.0.5_8.zip",
57 | "size": "41.1MB"
58 | },
59 | "macos-x86": {
60 | "url": "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jre/x64/mac/OpenJDK17U-jre_x64_mac_hotspot_17.0.5_8.tar.gz",
61 | "size": "41.6MB"
62 | },
63 | "linux-x86": {
64 | "url": "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jre/x64/linux/OpenJDK17U-jre_x64_linux_hotspot_17.0.5_8.tar.gz",
65 | "size": "43.8MB"
66 | },
67 | "macos-aarch": {
68 | "url": "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jre/aarch64/mac/OpenJDK17U-jre_aarch64_mac_hotspot_17.0.5_8.tar.gz",
69 | "size": "34.5MB"
70 | },
71 | "linux-aarch": {
72 | "url": "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/17/jre/aarch64/linux/OpenJDK17U-jre_aarch64_linux_hotspot_17.0.5_8.tar.gz",
73 | "size": "43.2MB"
74 | }
75 | }
76 | }
77 | ]
--------------------------------------------------------------------------------
/data/pnx.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PowerNukkitX/PNX-CLI/584529faa4617335cf6b447fbd753080024fcc2b/data/pnx.ico
--------------------------------------------------------------------------------
/lang/ZH-README.md:
--------------------------------------------------------------------------------
1 | # PNX-CLI
2 | [](https://github.com/PowerNukkitX/PNX-CLI/blob/master/README.md)
3 | [](https://github.com/PowerNukkitX/PNX-CLI/blob/master/lang/ZH-README.md)
4 |
5 |
6 | PNX-CLI 是PNX的命令行工具。可以帮助您快速安装并启动PNX。
7 | windows使用.\pnx.exe运行
8 | linux使用./pnx运行
9 | 以下简写为pnx
10 | ## 常用的一些命令
11 | 子列表为参数体,主列表为命令体
12 | - pnx start
13 | - -g 生成启动命令
14 | - -r 以自动重启模式启动服务器
15 | - --stdin=xxx 从指定文件中读取控制台输入(xxx输入文件地址,从pnx-cli当前路径)
16 | - pnx server
17 | - --latest 安装最新版本pnx core
18 | - -u 安装或升级PNX服务端核心(需手动选择)
19 | - pnx libs
20 | - -u 安装或更新依赖库
21 | - -v 检测依赖库是否为最新
22 | - pnx jvm
23 | - check 查看已经安装了的JVM
24 | - remote 列出PNX远程仓库中的所有可用JVM。
25 | - install=name 根据输入的型号名称安装新的JVM。(名称从上面的指令查询)
26 | - uninstall 根据输入的序号卸载已经安装了的JVM。
27 | - pnx comp
28 | - -c 检查可用的附加组件
29 | - -i=name 根据输入名称安装或修复附加组件。(名称从上面的指令查询)
30 | - sys-install 在系统路径中安装或卸载PNX
31 | - -u 从系统路径中移除PNX-CLI
32 | - pnx about PowerNukkitX CLI的信息
33 | - pnx sponsor 查看赞助PNX的大佬们
34 | - pnx ping 检查本机到PNX服务器各端点的网络情况
35 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | cn.powernukkitx
8 | PNX-CLI
9 | 0.2.4
10 |
11 |
12 | 21
13 | 21
14 | UTF-8
15 | UTF-8
16 |
17 |
18 |
19 |
20 | org.fusesource.jansi
21 | jansi
22 | 2.4.0
23 |
24 |
25 | info.picocli
26 | picocli
27 | 4.6.3
28 |
29 |
30 | com.google.code.gson
31 | gson
32 | 2.9.0
33 |
34 |
35 | net.lingala.zip4j
36 | zip4j
37 | 2.9.1
38 |
39 |
40 | org.kamranzafar
41 | jtar
42 | 2.3
43 |
44 |
45 | org.jetbrains
46 | annotations
47 | 23.1.0
48 | compile
49 |
50 |
51 |
52 |
53 |
54 |
55 | org.apache.maven.plugins
56 | maven-compiler-plugin
57 | 3.8.1
58 |
59 |
60 |
61 | info.picocli
62 | picocli-codegen
63 | 4.6.3
64 |
65 |
66 |
67 |
68 |
69 | org.apache.maven.plugins
70 | maven-jar-plugin
71 | 2.4
72 |
73 |
74 |
75 | cn.powernukkitx.cli.Main
76 |
77 |
78 | PowerNukkitX Dev Team
79 |
80 |
81 |
82 |
83 |
84 | org.apache.maven.plugins
85 | maven-shade-plugin
86 | 3.2.4
87 |
88 |
89 | package
90 |
91 | shade
92 |
93 |
94 |
95 |
96 | *:jansi
97 |
98 | META-INF/*.MF
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/App.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli;
2 |
3 | import cn.powernukkitx.cli.cmd.StartCommand;
4 | import cn.powernukkitx.cli.cmd.SysInstallCommand;
5 | import cn.powernukkitx.cli.util.*;
6 | import picocli.CommandLine;
7 | import picocli.CommandLine.Command;
8 | import picocli.CommandLine.Option;
9 | import picocli.CommandLine.Parameters;
10 |
11 | import java.io.File;
12 | import java.util.Formatter;
13 | import java.util.ResourceBundle;
14 | import java.util.concurrent.Callable;
15 |
16 | import static org.fusesource.jansi.Ansi.ansi;
17 |
18 | @Command(name = "pnx", aliases = {"pnx", "PNX", "cli"}, version = CLIConstant.version, mixinStandardHelpOptions = true,
19 | resourceBundle = "cn.powernukkitx.cli.App", subcommands = {
20 | SysInstallCommand.class,
21 | StartCommand.class
22 | })
23 | public final class App implements Callable {
24 |
25 | @SuppressWarnings("unused")
26 | @Option(names = {"-l", "--lang", "--language"}, paramLabel = "", descriptionKey = "lang")
27 | private String ignoredLocale;
28 |
29 | @Option(names = "--config-path", paramLabel = "", descriptionKey = "config-path")
30 | public String configFilePath;
31 |
32 | @SuppressWarnings("unused")
33 | @Option(names = {"-u", "--update"}, descriptionKey = "update", negatable = true, defaultValue = "true")
34 | public boolean ignoredCheckUpdate;
35 |
36 | @Parameters(index = "0..*", hidden = true)
37 | public String[] args;
38 |
39 | private final ResourceBundle bundle = ResourceBundle.getBundle("cn.powernukkitx.cli.App");
40 |
41 | @Override
42 | public Integer call() {
43 | if (StringUtils.notEmpty(configFilePath)) {
44 | var file = new File(configFilePath);
45 | if (file.exists() && file.canRead() && file.canWrite()) {
46 | ConfigUtils.globalConfigFile = file;
47 | ConfigUtils.parseConfigFile(file);
48 | } else {
49 | Logger.error(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("invalid-file"), configFilePath)).fgDefault());
50 | }
51 | }
52 | var start = new StartCommand();
53 | start.args = args;
54 | if (args != null && args.length != 0) {
55 | Logger.error(ansi().fgBrightYellow().a(new Formatter().format(bundle.getString("args"), OSUtils.getProgramName())).fgDefault());
56 | CommandLine.usage(this, System.out);
57 | return 1;
58 | }
59 | start.generateOnly = false;
60 | var ret = start.call();
61 | if (ret != 0) {
62 | InputUtils.pressEnterToContinue();
63 | }
64 | return ret;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/CLIConstant.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli;
2 |
3 | import cn.powernukkitx.cli.util.OSUtils;
4 |
5 | import java.io.File;
6 | import java.util.List;
7 |
8 | public interface CLIConstant {
9 | String version = "0.2.4";
10 | List authors = List.of("超神的冰凉", "CoolLoong");
11 | File userDir = new File(System.getProperty("user.dir"));
12 | File programDir = new File(OSUtils.getProgramDir());
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/Main.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli;
2 |
3 | import cn.powernukkitx.cli.util.ConfigUtils;
4 | import cn.powernukkitx.cli.util.EnumOS;
5 | import cn.powernukkitx.cli.util.OSUtils;
6 | import org.fusesource.jansi.AnsiConsole;
7 | import picocli.CommandLine;
8 |
9 | import java.util.Locale;
10 | import java.util.Timer;
11 |
12 | public final class Main {
13 | static Timer timer = null;
14 | public static volatile boolean pnxRunning = false;
15 |
16 | public static void main(String[] args) {
17 | AnsiConsole.systemInstall();
18 | ConfigUtils.init();
19 | // 先设置语言
20 | if (ConfigUtils.forceLang() != null) {
21 | Locale.setDefault(Locale.forLanguageTag(ConfigUtils.forceLang().toLowerCase()));
22 | } else {
23 | if (OSUtils.getOS() == EnumOS.WINDOWS) {
24 | var locale = OSUtils.getWindowsLocale();
25 | if (locale != null) {
26 | Locale.setDefault(locale);
27 | ConfigUtils.set("language", locale.toLanguageTag());
28 | }
29 | }
30 | }
31 | var realArgs = args;
32 | if (ConfigUtils.forceArguments() != null) {
33 | realArgs = ConfigUtils.forceArguments();
34 | }
35 | try {
36 | new CommandLine(new Preprocessor()).parseArgs(realArgs);
37 | } catch (Exception ignore) {
38 |
39 | }
40 | // 解析命令行
41 | var exitCode = new CommandLine(new App()).execute(args);
42 | if (timer != null)
43 | timer.cancel();
44 | System.exit(exitCode);
45 | }
46 |
47 | public static Timer getTimer() {
48 | if (timer == null) {
49 | timer = new Timer();
50 | }
51 | return timer;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/Preprocessor.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli;
2 |
3 | import picocli.CommandLine.Command;
4 | import picocli.CommandLine.Option;
5 | import picocli.CommandLine.Unmatched;
6 |
7 | import java.util.List;
8 | import java.util.Locale;
9 |
10 | @Command(resourceBundle = "cn.powernukkitx.cli.Preprocessor")
11 | public class Preprocessor {
12 | @Option(names = { "-l", "--lang", "--language" }, descriptionKey = "lang")
13 | public void setLocale(String locale) {
14 | Locale.setDefault(Locale.forLanguageTag(locale));
15 | }
16 |
17 | @Unmatched
18 | public List remainder;
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/cmd/StartCommand.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.cmd;
2 |
3 | import cn.powernukkitx.cli.CLIConstant;
4 | import cn.powernukkitx.cli.Main;
5 | import cn.powernukkitx.cli.data.builder.JVMStartCommandBuilder;
6 | import cn.powernukkitx.cli.data.locator.JarLocator;
7 | import cn.powernukkitx.cli.data.locator.JavaLocator;
8 | import cn.powernukkitx.cli.util.*;
9 | import picocli.CommandLine.Command;
10 | import picocli.CommandLine.Option;
11 | import picocli.CommandLine.Parameters;
12 |
13 | import java.io.File;
14 | import java.io.FileWriter;
15 | import java.io.IOException;
16 | import java.nio.file.Files;
17 | import java.util.*;
18 | import java.util.concurrent.Callable;
19 |
20 | import static cn.powernukkitx.cli.util.NullUtils.Ok;
21 | import static org.fusesource.jansi.Ansi.ansi;
22 |
23 | @Command(name = "start", mixinStandardHelpOptions = true, resourceBundle = "cn.powernukkitx.cli.cmd.Start")
24 | public final class StartCommand implements Callable {
25 | private final ResourceBundle bundle = ResourceBundle.getBundle("cn.powernukkitx.cli.cmd.Start");
26 |
27 | @Option(names = {"-g", "--generate-only"}, descriptionKey = "generate-only", help = true)
28 | public boolean generateOnly;
29 |
30 | @Option(names = {"-r", "--restart"}, descriptionKey = "restart", help = true, negatable = true)
31 | public boolean restart;
32 |
33 | @Option(names = "--stdin", descriptionKey = "stdin", help = true)
34 | public String stdin;
35 |
36 | @Parameters(index = "0..*", hidden = true)
37 | public String[] args;
38 |
39 | private String[] startCommand = null;
40 |
41 | @Override
42 | public Integer call() {
43 | var cmdBuilder = new JVMStartCommandBuilder();
44 | var javaList = new JavaLocator("21", true).locate();
45 | if (javaList.isEmpty()) {
46 | Logger.error(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("no-java21"), OSUtils.getProgramName())).fgDefault());
47 | return 1;
48 | }
49 | var java = javaList.get(0);
50 | cmdBuilder.setJvmExecutable(java.getFile());
51 | Logger.info(ansi().fgBrightYellow().a(new Formatter().format(bundle.getString("using-jvm"), java.getInfo().getVendor())).fgDefault());
52 | var pnxList = new JarLocator(CLIConstant.userDir, "cn.nukkit.PlayerHandle").locate();
53 | //auto install
54 | if (pnxList.isEmpty()) {
55 | File file = new File(CLIConstant.userDir, "PowerNukkitX-Core.zip");
56 |
57 | if (file.exists()) {
58 | new JarLocator(CLIConstant.userDir, "cn.nukkit.PlayerHandle").locate().forEach(each -> each.getFile().delete());
59 | try {
60 | CompressUtils.uncompressZipFile(file, new File(""));
61 | Files.deleteIfExists(file.toPath());
62 | } catch (IOException e) {
63 | throw new RuntimeException(e);
64 | }
65 | pnxList = new JarLocator(CLIConstant.userDir, "cn.nukkit.PlayerHandle").locate();
66 | } else {
67 | Logger.warn(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("no-pnx"), OSUtils.getProgramName())).fgDefault());
68 | return 1;
69 | }
70 | }
71 | var libDir = new File(CLIConstant.userDir, "libs");
72 | if (!libDir.exists()) {
73 | //noinspection ResultOfMethodCallIgnored
74 | libDir.mkdirs();
75 | }
76 | var oldLibFiles = new LinkedList<>(Arrays.asList(Objects.requireNonNull(libDir.listFiles((dir, name) -> name.endsWith(".jar")))));
77 | if (oldLibFiles.size() < 32) {
78 | File file = new File(CLIConstant.userDir, "PowerNukkitX-Libs.zip");
79 | if (file.exists()) {
80 | File libs = new File(CLIConstant.userDir, "libs");
81 | FileUtils.deleteDir(libs);
82 | try {
83 | CompressUtils.uncompressZipFile(file, libs);
84 | Files.deleteIfExists(file.toPath());
85 | } catch (IOException e) {
86 | throw new RuntimeException(e);
87 | }
88 | } else {
89 | Logger.warn(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("no-libs"), OSUtils.getProgramName())).fgDefault());
90 | return 1;
91 | }
92 | }
93 | var pnx = pnxList.get(0);
94 | cmdBuilder.addClassPath(pnx.getFile().getAbsolutePath());
95 | Logger.info(ansi().fgBrightYellow().a(new Formatter().format(bundle.getString("using-pnx"), Ok(pnx.getInfo().getGitInfo().orElse(null), info -> info.getMainVersion() + " - " + info.getCommitID(), "unknown"))).fgDefault());
96 | cmdBuilder.setStartTarget("cn.nukkit.Nukkit");
97 | cmdBuilder.addClassPath(new File(CLIConstant.userDir, "libs").getAbsolutePath() + File.separator + "*");
98 | cmdBuilder.addProperty("file.encoding", "UTF-8");
99 | cmdBuilder.addProperty("jansi.passthrough", "true");
100 | cmdBuilder.addProperty("terminal.ansi", "true");
101 | cmdBuilder.addAddOpen("java.base/java.lang");
102 | cmdBuilder.addAddOpen("java.base/java.io");
103 | cmdBuilder.addAddOpen("java.base/java.net");
104 | cmdBuilder.addXOption("mx", ConfigUtils.maxVMMemory());
105 | cmdBuilder.addXxOption("UseZGC", true);
106 | cmdBuilder.addXxOption("ZGenerational", true);
107 | cmdBuilder.addXxOption("UseStringDeduplication", true);
108 | for (var each : ConfigUtils.vmParams()) {
109 | cmdBuilder.addOtherArgs(each);
110 | }
111 | for (var each : ConfigUtils.addOpens()) {
112 | cmdBuilder.addAddOpen(each);
113 | }
114 | for (var each : ConfigUtils.xOptions()) {
115 | cmdBuilder.addXOption(each);
116 | }
117 | for (var each : ConfigUtils.xxOptions()) {
118 | cmdBuilder.addXxOption(each);
119 | }
120 | if (generateOnly) {
121 | Logger.raw(cmdBuilder.build() + "\n");
122 | return 0;
123 | }
124 | cmdBuilder.addProperty("pnx.cli.path", OSUtils.getProgramPath());
125 | cmdBuilder.addProperty("pnx.cli.version", CLIConstant.version);
126 | startCommand = cmdBuilder.build().split(" ");
127 | if (restart) {
128 | var result = start();
129 | while (true) {
130 | if (!InputUtils.pressEnterToStopWithTimeLimit(10000)) {
131 | result = start();
132 | } else {
133 | return result;
134 | }
135 | }
136 | } else {
137 | return start();
138 | }
139 | }
140 |
141 | enum GraalStatus {
142 | NotFound,
143 | Standard,
144 | Oracle,
145 | LowVersion
146 | }
147 |
148 | private GraalStatus getGraalStatus(JavaLocator.JavaInfo javaInfo) {
149 | var vendor = javaInfo.getVendor().toLowerCase();
150 | if (!vendor.contains("graal")) {
151 | return GraalStatus.NotFound;
152 | }
153 | if (vendor.contains("oracle graalvm")) {
154 | return GraalStatus.Oracle;
155 | }
156 | var index = vendor.indexOf("2", vendor.indexOf("graalvm"));
157 | if (index == -1) {
158 | return GraalStatus.NotFound;
159 | }
160 | var version = vendor.substring(index, index + 4);
161 | return Integer.parseInt(version.replace(".", "")) < 222 ? GraalStatus.LowVersion : GraalStatus.Standard;
162 | }
163 |
164 | private int start() {
165 | System.gc();
166 | try {
167 | var useStdinFile = stdin != null && !"".equals(stdin.trim());
168 | var builder = new ProcessBuilder().command(startCommand);
169 | if (useStdinFile) {
170 | builder.redirectOutput(ProcessBuilder.Redirect.INHERIT)
171 | .redirectError(ProcessBuilder.Redirect.INHERIT);
172 | } else {
173 | builder.inheritIO();
174 | }
175 | var process = builder.start();
176 | Main.pnxRunning = true;
177 | if (useStdinFile) {
178 | var stdinFile = new File(CLIConstant.userDir, stdin);
179 | if (stdinFile.exists() && stdinFile.isFile() && stdinFile.canRead() && stdinFile.canWrite()) {
180 | Main.getTimer().scheduleAtFixedRate(new TimerTask() {
181 | long lastUpdateTime = -1;
182 |
183 | @Override
184 | public void run() {
185 | try {
186 | if (!process.isAlive()) {
187 | this.cancel();
188 | }
189 | if (stdinFile.lastModified() > lastUpdateTime) {
190 | var tmp = Files.readAllBytes(stdinFile.toPath());
191 | process.getOutputStream().write(tmp);
192 | process.getOutputStream().flush();
193 | try (var fileWriter = new FileWriter(stdinFile)) {
194 | fileWriter.write("");// 清空
195 | fileWriter.flush();
196 | }
197 | lastUpdateTime = stdinFile.lastModified();
198 | }
199 | } catch (Exception ignore) {
200 |
201 | }
202 | }
203 | }, 1000, 1000);
204 | }
205 | }
206 | int exitValue = process.waitFor();
207 | Main.pnxRunning = false;
208 | return exitValue;
209 | } catch (IOException | InterruptedException e) {
210 | e.printStackTrace();
211 | Main.pnxRunning = false;
212 | return 1;
213 | }
214 | }
215 | }
216 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/cmd/SysInstallCommand.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.cmd;
2 |
3 | import cn.powernukkitx.cli.util.EnumOS;
4 | import cn.powernukkitx.cli.util.Logger;
5 | import cn.powernukkitx.cli.util.OSUtils;
6 | import picocli.CommandLine.Command;
7 | import picocli.CommandLine.Option;
8 |
9 | import java.io.IOException;
10 | import java.nio.file.Files;
11 | import java.nio.file.Path;
12 | import java.util.Formatter;
13 | import java.util.ResourceBundle;
14 | import java.util.concurrent.Callable;
15 |
16 | import static org.fusesource.jansi.Ansi.ansi;
17 |
18 | @Command(name = "sys-install", mixinStandardHelpOptions = true, resourceBundle = "cn.powernukkitx.cli.cmd.SysInstall")
19 | public final class SysInstallCommand implements Callable {
20 | @Option(names = {"-u", "--uninstall"}, help = true, descriptionKey = "uninstall")
21 | boolean uninstall = false;
22 |
23 | private final ResourceBundle bundle = ResourceBundle.getBundle("cn.powernukkitx.cli.cmd.SysInstall");
24 |
25 | @Override
26 | public Integer call() {
27 | var os = OSUtils.getOS();
28 | if (!"Substrate VM".equals(System.getProperty("java.vm.name"))) {
29 | Logger.error(ansi().fgBrightRed().a(bundle.getString("executable-only")).fgDefault().toString());
30 | return 1;
31 | }
32 | if (os == EnumOS.UNKNOWN || os == EnumOS.MACOS) {
33 | Logger.error(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("unsupportedOS"), System.getProperty("os.name"))).fgDefault().toString());
34 | return 1;
35 | }
36 | if (uninstall) {
37 | if (os == EnumOS.WINDOWS) {
38 | var sysPath = System.getenv("PATH");
39 | var programDir = OSUtils.getProgramDir();
40 | if (sysPath.contains(programDir)) {
41 | try {
42 | boolean ok = OSUtils.removeWindowsPath(programDir);
43 | if (ok) {
44 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("success-uninstall")).fgDefault().toString());
45 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("windows-cmd")).fgDefault().toString());
46 | return 0;
47 | }
48 | } catch (IOException | InterruptedException e) {
49 | e.printStackTrace();
50 | }
51 | Logger.error(ansi().fgBrightRed().a(bundle.getString("fail-uninstall")).fgDefault().toString());
52 | return 1;
53 | } else {
54 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("have-not")).fgDefault().toString());
55 | return 0;
56 | }
57 | }
58 | } else {
59 | if (os == EnumOS.WINDOWS) {
60 | var sysPath = System.getenv("PATH");
61 | var programDir = OSUtils.getProgramDir();
62 | if (sysPath.contains(programDir)) {
63 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("already")).fgDefault().toString());
64 | return 0;
65 | } else {
66 | try {
67 | boolean ok = OSUtils.addWindowsPath(programDir);
68 | if (ok) {
69 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("success")).fgDefault().toString());
70 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("windows-cmd")).fgDefault().toString());
71 | return 0;
72 | }
73 | } catch (IOException | InterruptedException e) {
74 | e.printStackTrace();
75 | }
76 | Logger.error(ansi().fgBrightRed().a(bundle.getString("fail")).fgDefault().toString());
77 | return 1;
78 | }
79 | } else if (os == EnumOS.LINUX) {
80 | var sysPath = System.getenv("PATH");
81 | var programDir = OSUtils.getProgramDir();
82 | if (sysPath.contains(programDir)) {
83 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("already")).fgDefault().toString());
84 | return 0;
85 | } else {
86 | try {
87 | var homeDir = System.getProperty("user.home");
88 | var profilePath = homeDir + "/.profile";
89 | if (!Files.exists(Path.of(profilePath))) {
90 | profilePath = homeDir + "/.bash_profile";
91 | }
92 | if (!Files.exists(Path.of(profilePath))) {
93 | Logger.error(ansi().fgBrightRed().a(new Formatter().format(bundle.getString("unsupportedOS"), System.getProperty("os.name"))).fgDefault().toString());
94 | return 1;
95 | }
96 | var profile = Files.readAllLines(Path.of(profilePath));
97 | var ok = false;
98 | for (int i = 0, len = profile.size(); i < len; i++) {
99 | var line = profile.get(i);
100 | if (line.startsWith("export") && line.contains("$PATH")) {
101 | profile.set(i, profile.get(i) + ":" + programDir);
102 | ok = true;
103 | break;
104 | }
105 | }
106 | if (!ok) {
107 | profile.add("export PATH=" + programDir + ":$PATH");
108 | }
109 | Files.write(Path.of(profilePath), profile);
110 | Logger.info(ansi().fgBrightGreen().a(bundle.getString("success")).fgDefault().toString());
111 | Logger.info(ansi().fgBrightGreen().a(new Formatter().format(bundle.getString("linux-cmd"), profilePath)).fgDefault().toString());
112 | return 0;
113 | } catch (IOException e) {
114 | e.printStackTrace();
115 | }
116 | Logger.error(ansi().fgBrightRed().a(bundle.getString("fail")).fgDefault().toString());
117 | return 1;
118 | }
119 | }
120 | }
121 |
122 | return 0;
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/ArtifactBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import com.google.gson.JsonObject;
4 | import org.jetbrains.annotations.Contract;
5 | import org.jetbrains.annotations.NotNull;
6 |
7 | import java.util.Date;
8 |
9 | public record ArtifactBean(
10 | String name,
11 | Date createAt,
12 | Date expiresAt,
13 | long sizeInBytes,
14 | long downloadId
15 | ) {
16 | @Contract("_ -> new")
17 | public static @NotNull ArtifactBean from(@NotNull JsonObject jsonObject) {
18 | return new ArtifactBean(
19 | jsonObject.get("name").getAsString(),
20 | new Date(jsonObject.get("createAt").getAsLong()),
21 | new Date(jsonObject.get("expiresAt").getAsLong()),
22 | jsonObject.get("sizeInBytes").getAsLong(),
23 | jsonObject.get("downloadId").getAsLong()
24 | );
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/BuildBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import com.google.gson.JsonObject;
4 | import org.jetbrains.annotations.NotNull;
5 |
6 | public record BuildBean(
7 | ArtifactBean libs,
8 | ArtifactBean full,
9 | ArtifactBean core,
10 | ArtifactBean hashes
11 | ) {
12 | public static @NotNull BuildBean from(@NotNull JsonObject jsonObject) {
13 | return new BuildBean(
14 | ArtifactBean.from(jsonObject.get("libs").getAsJsonObject()),
15 | ArtifactBean.from(jsonObject.get("full").getAsJsonObject()),
16 | ArtifactBean.from(jsonObject.get("core").getAsJsonObject()),
17 | ArtifactBean.from(jsonObject.get("hashes").getAsJsonObject())
18 | );
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/GitHubArtifactBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import com.google.gson.JsonObject;
4 | import org.jetbrains.annotations.Contract;
5 |
6 | import java.time.LocalDateTime;
7 | import java.time.format.DateTimeFormatter;
8 | import java.time.format.DateTimeFormatterBuilder;
9 | import java.util.Locale;
10 |
11 | import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
12 | import static java.time.format.DateTimeFormatter.ISO_LOCAL_TIME;
13 |
14 | public class GitHubArtifactBean {
15 | private long id;
16 | private String nodeId;
17 | private String name;
18 | private long sizeInBytes;
19 | private String url;
20 | private String archiveDownloadUrl;
21 | private boolean expired;
22 | private LocalDateTime createdAt;
23 | private LocalDateTime updatedAt;
24 | private LocalDateTime expiresAt;
25 | private WorkflowRun workflowRun;
26 |
27 | public GitHubArtifactBean(long id, String nodeId, String name, long sizeInBytes, String url, String archiveDownloadUrl, boolean expired, LocalDateTime createdAt, LocalDateTime updatedAt, LocalDateTime expiresAt, WorkflowRun workflowRun) {
28 | this.id = id;
29 | this.nodeId = nodeId;
30 | this.name = name;
31 | this.sizeInBytes = sizeInBytes;
32 | this.url = url;
33 | this.archiveDownloadUrl = archiveDownloadUrl;
34 | this.expired = expired;
35 | this.createdAt = createdAt;
36 | this.updatedAt = updatedAt;
37 | this.expiresAt = expiresAt;
38 | this.workflowRun = workflowRun;
39 | }
40 |
41 | public long getId() {
42 | return id;
43 | }
44 |
45 | public void setId(long id) {
46 | this.id = id;
47 | }
48 |
49 | public String getNodeId() {
50 | return nodeId;
51 | }
52 |
53 | public void setNodeId(String nodeId) {
54 | this.nodeId = nodeId;
55 | }
56 |
57 | public String getName() {
58 | return name;
59 | }
60 |
61 | public void setName(String name) {
62 | this.name = name;
63 | }
64 |
65 | public long getSizeInBytes() {
66 | return sizeInBytes;
67 | }
68 |
69 | public void setSizeInBytes(long sizeInBytes) {
70 | this.sizeInBytes = sizeInBytes;
71 | }
72 |
73 | public String getUrl() {
74 | return url;
75 | }
76 |
77 | public void setUrl(String url) {
78 | this.url = url;
79 | }
80 |
81 | public String getArchiveDownloadUrl() {
82 | return archiveDownloadUrl;
83 | }
84 |
85 | public void setArchiveDownloadUrl(String archiveDownloadUrl) {
86 | this.archiveDownloadUrl = archiveDownloadUrl;
87 | }
88 |
89 | public boolean isExpired() {
90 | return expired;
91 | }
92 |
93 | public void setExpired(boolean expired) {
94 | this.expired = expired;
95 | }
96 |
97 | public LocalDateTime getCreatedAt() {
98 | return createdAt;
99 | }
100 |
101 | public void setCreatedAt(LocalDateTime createdAt) {
102 | this.createdAt = createdAt;
103 | }
104 |
105 | public LocalDateTime getUpdatedAt() {
106 | return updatedAt;
107 | }
108 |
109 | public void setUpdatedAt(LocalDateTime updatedAt) {
110 | this.updatedAt = updatedAt;
111 | }
112 |
113 | public LocalDateTime getExpiresAt() {
114 | return expiresAt;
115 | }
116 |
117 | public void setExpiresAt(LocalDateTime expiresAt) {
118 | this.expiresAt = expiresAt;
119 | }
120 |
121 | public WorkflowRun getWorkflowRun() {
122 | return workflowRun;
123 | }
124 |
125 | public void setWorkflowRun(WorkflowRun workflowRun) {
126 | this.workflowRun = workflowRun;
127 | }
128 |
129 | public static final DateTimeFormatter TIME_FORMATTER;
130 |
131 | static {
132 | TIME_FORMATTER = new DateTimeFormatterBuilder()
133 | .parseCaseInsensitive()
134 | .append(ISO_LOCAL_DATE)
135 | .appendLiteral('T')
136 | .append(ISO_LOCAL_TIME)
137 | .appendLiteral('Z')
138 | .toFormatter(Locale.getDefault(Locale.Category.FORMAT));
139 | }
140 |
141 |
142 | @Contract("_ -> new")
143 | public static GitHubArtifactBean from(JsonObject jsonObject) {
144 | return new GitHubArtifactBean(
145 | jsonObject.get("id").getAsLong(),
146 | jsonObject.get("node_id").getAsString(),
147 | jsonObject.get("name").getAsString(),
148 | jsonObject.get("size_in_bytes").getAsLong(),
149 | jsonObject.get("url").getAsString(),
150 | jsonObject.get("archive_download_url").getAsString(),
151 | jsonObject.get("expired").getAsBoolean(),
152 | LocalDateTime.parse(jsonObject.get("created_at").getAsString(), TIME_FORMATTER),
153 | LocalDateTime.parse(jsonObject.get("updated_at").getAsString(), TIME_FORMATTER),
154 | LocalDateTime.parse(jsonObject.get("expires_at").getAsString(), TIME_FORMATTER),
155 | WorkflowRun.from(jsonObject.getAsJsonObject("workflow_run"))
156 | );
157 | }
158 |
159 | @Override
160 | public String toString() {
161 | return "GitHubArtifactBean{" +
162 | "id=" + id +
163 | ", nodeId='" + nodeId + '\'' +
164 | ", name='" + name + '\'' +
165 | ", sizeInBytes=" + sizeInBytes +
166 | ", url='" + url + '\'' +
167 | ", archiveDownloadUrl='" + archiveDownloadUrl + '\'' +
168 | ", expired=" + expired +
169 | ", createdAt=" + createdAt +
170 | ", updatedAt=" + updatedAt +
171 | ", expiresAt=" + expiresAt +
172 | ", workflowRun=" + workflowRun +
173 | '}';
174 | }
175 |
176 | public static class WorkflowRun {
177 | private long id;
178 | private long repositoryId;
179 | private long headRepositoryId;
180 | private String headBranch;
181 | private String headSha;
182 |
183 | public WorkflowRun(long id, long repositoryId, long headRepositoryId, String headBranch, String headSha) {
184 | this.id = id;
185 | this.repositoryId = repositoryId;
186 | this.headRepositoryId = headRepositoryId;
187 | this.headBranch = headBranch;
188 | this.headSha = headSha;
189 | }
190 |
191 | public long getId() {
192 | return id;
193 | }
194 |
195 | public void setId(long id) {
196 | this.id = id;
197 | }
198 |
199 | public long getRepositoryId() {
200 | return repositoryId;
201 | }
202 |
203 | public void setRepositoryId(long repositoryId) {
204 | this.repositoryId = repositoryId;
205 | }
206 |
207 | public long getHeadRepositoryId() {
208 | return headRepositoryId;
209 | }
210 |
211 | public void setHeadRepositoryId(long headRepositoryId) {
212 | this.headRepositoryId = headRepositoryId;
213 | }
214 |
215 | public String getHeadBranch() {
216 | return headBranch;
217 | }
218 |
219 | public void setHeadBranch(String headBranch) {
220 | this.headBranch = headBranch;
221 | }
222 |
223 | public String getHeadSha() {
224 | return headSha;
225 | }
226 |
227 | public void setHeadSha(String headSha) {
228 | this.headSha = headSha;
229 | }
230 |
231 | public String getTag() {
232 | return getHeadSha().substring(0, 7);
233 | }
234 |
235 | @Contract("_ -> new")
236 | public static WorkflowRun from(JsonObject jsonObject) {
237 | return new WorkflowRun(
238 | jsonObject.get("id").getAsLong(),
239 | jsonObject.get("repository_id").getAsLong(),
240 | jsonObject.get("head_repository_id").getAsLong(),
241 | jsonObject.get("head_branch").getAsString(),
242 | jsonObject.get("head_sha").getAsString()
243 | );
244 | }
245 |
246 | @Override
247 | public String toString() {
248 | return "WorkflowRun{" +
249 | "id=" + id +
250 | ", repositoryId=" + repositoryId +
251 | ", headRepositoryId=" + headRepositoryId +
252 | ", headBranch='" + headBranch + '\'' +
253 | ", headSha='" + headSha + '\'' +
254 | '}';
255 | }
256 | }
257 | }
258 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/ReleaseBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import com.google.gson.JsonObject;
4 | import org.jetbrains.annotations.Contract;
5 | import org.jetbrains.annotations.NotNull;
6 |
7 | import java.util.Date;
8 | import java.util.stream.StreamSupport;
9 |
10 | public record ReleaseBean(
11 | String name,
12 | String tagName,
13 | String body,
14 | Date publishedAt,
15 | ArtifactBean[] artifacts
16 | ) {
17 | @Contract("_ -> new")
18 | public static @NotNull ReleaseBean from(@NotNull JsonObject jsonObject) {
19 | return new ReleaseBean(
20 | jsonObject.get("name").getAsString(),
21 | jsonObject.get("tagName").getAsString(),
22 | jsonObject.get("body").getAsString(),
23 | new Date(jsonObject.get("publishedAt").getAsLong()),
24 | StreamSupport.stream(jsonObject.get("artifacts").getAsJsonArray().spliterator(), false)
25 | .map(JsonObject.class::cast)
26 | .map(ArtifactBean::from)
27 | .toArray(ArtifactBean[]::new)
28 | );
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/RemoteFileBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import cn.powernukkitx.cli.util.StringUtils;
4 | import com.google.gson.JsonObject;
5 | import org.jetbrains.annotations.Contract;
6 | import org.jetbrains.annotations.NotNull;
7 |
8 | import java.util.Date;
9 |
10 | public record RemoteFileBean(
11 | String fullPath,
12 | long size,
13 | Date lastUpdateTime,
14 | String md5,
15 | long downloadID
16 | ) {
17 | @Contract("_ -> new")
18 | public static @NotNull RemoteFileBean from(@NotNull JsonObject jsonObject) {
19 | return new RemoteFileBean(
20 | jsonObject.get("fileName").getAsString(),
21 | jsonObject.get("size").getAsLong(),
22 | new Date(jsonObject.get("lastUpdateTime").getAsLong()),
23 | jsonObject.get("md5").getAsString(),
24 | jsonObject.get("downloadID").getAsLong()
25 | );
26 | }
27 |
28 | public @NotNull String fileName() {
29 | if (fullPath.contains("/"))
30 | return StringUtils.afterLast(fullPath, "/");
31 | return fullPath;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/bean/RequestIDBean.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.bean;
2 |
3 | import com.google.gson.JsonObject;
4 | import org.jetbrains.annotations.Contract;
5 | import org.jetbrains.annotations.NotNull;
6 |
7 | import java.util.UUID;
8 |
9 | public record RequestIDBean(@NotNull String uuid, long acceptTime) {
10 | public RequestIDBean(@NotNull UUID uuid) {
11 | this(uuid.toString(), System.currentTimeMillis());
12 | }
13 |
14 | @Contract("_ -> new")
15 | public static @NotNull RequestIDBean from(@NotNull JsonObject jsonObject) {
16 | if (jsonObject.has("acceptTime")) {
17 | return new RequestIDBean(
18 | jsonObject.get("uuid").getAsString(),
19 | jsonObject.get("acceptTime").getAsLong()
20 | );
21 | } else {
22 | return new RequestIDBean(
23 | UUID.fromString(jsonObject.get("uuid").getAsString())
24 | );
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/builder/JVMStartCommandBuilder.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.builder;
2 |
3 | import cn.powernukkitx.cli.util.StringUtils;
4 | import com.sun.management.OperatingSystemMXBean;
5 |
6 | import java.io.File;
7 | import java.lang.management.ManagementFactory;
8 | import java.util.*;
9 |
10 | public final class JVMStartCommandBuilder {
11 | private File jvmExecutable;
12 | private Map properties = new LinkedHashMap<>(); // -Dxxx=xxx
13 | private Map xxOptions = new LinkedHashMap<>(); // -XX:
14 | private Map xOptions = new LinkedHashMap<>(); // -X:
15 | private List modulePath = new ArrayList<>(2);
16 | private List upgradeModulePath = new ArrayList<>(2);
17 | private List classPath = new ArrayList<>(2);
18 | private Map addOpens = new LinkedHashMap<>();
19 | private List otherArgs = new ArrayList<>(0);
20 | private String startTarget;
21 |
22 | public JVMStartCommandBuilder useMaxPhysicalMemory() {
23 | var osMxb = (OperatingSystemMXBean) ManagementFactory
24 | .getOperatingSystemMXBean();
25 | addXOption("mx" + (osMxb.getTotalMemorySize() / 1024 / 1024) + "m");
26 | return this;
27 | }
28 |
29 | public File getJvmExecutable() {
30 | return jvmExecutable;
31 | }
32 |
33 | public JVMStartCommandBuilder setJvmExecutable(File jvmExecutable) {
34 | this.jvmExecutable = jvmExecutable;
35 | return this;
36 | }
37 |
38 | public Map getProperties() {
39 | return properties;
40 | }
41 |
42 | public JVMStartCommandBuilder addProperty(String key, String value) {
43 | properties.put(key, value);
44 | return this;
45 | }
46 |
47 | public JVMStartCommandBuilder setProperties(Map properties) {
48 | this.properties = properties;
49 | return this;
50 | }
51 |
52 | public String getProperty(String key) {
53 | return properties.get(key);
54 | }
55 |
56 | public Map getXxOptions() {
57 | return xxOptions;
58 | }
59 |
60 | public JVMStartCommandBuilder addXxOption(String key, Object value) {
61 | xxOptions.put(key, value);
62 | return this;
63 | }
64 |
65 | public JVMStartCommandBuilder addXxOption(String key) {
66 | xxOptions.put(key, null);
67 | return this;
68 | }
69 |
70 | public JVMStartCommandBuilder setXxOptions(Map xxOptions) {
71 | this.xxOptions = xxOptions;
72 | return this;
73 | }
74 |
75 | public T getXxOption(String key, Class clazz) {
76 | var tmp = xxOptions.get(key);
77 | if (clazz.isInstance(tmp)) {
78 | return clazz.cast(tmp);
79 | }
80 | return null;
81 | }
82 |
83 | public Map getXOptions() {
84 | return xOptions;
85 | }
86 |
87 | public JVMStartCommandBuilder addXOption(String key, Object value) {
88 | xOptions.put(key, value);
89 | return this;
90 | }
91 |
92 | public JVMStartCommandBuilder addXOption(String key) {
93 | xOptions.put(key, null);
94 | return this;
95 | }
96 |
97 | public JVMStartCommandBuilder setXOptions(Map xxOptions) {
98 | this.xOptions = xxOptions;
99 | return this;
100 | }
101 |
102 | public T getXOption(String key, Class clazz) {
103 | var tmp = xOptions.get(key);
104 | if (clazz.isInstance(tmp)) {
105 | return clazz.cast(tmp);
106 | }
107 | return null;
108 | }
109 |
110 | public List getOtherArgs() {
111 | return otherArgs;
112 | }
113 |
114 | public JVMStartCommandBuilder setOtherArgs(List otherArgs) {
115 | this.otherArgs = otherArgs;
116 | return this;
117 | }
118 |
119 | public JVMStartCommandBuilder setOtherArgs(String... args) {
120 | this.otherArgs = Arrays.asList(args);
121 | return this;
122 | }
123 |
124 | public JVMStartCommandBuilder addOtherArgs(String... args) {
125 | otherArgs.addAll(List.of(args));
126 | return this;
127 | }
128 |
129 | public List getModulePath() {
130 | return modulePath;
131 | }
132 |
133 | public JVMStartCommandBuilder setModulePath(List modulePath) {
134 | this.modulePath = modulePath;
135 | return this;
136 | }
137 |
138 | public JVMStartCommandBuilder setModulePath(String... modulePath) {
139 | this.modulePath = Arrays.asList(modulePath);
140 | return this;
141 | }
142 |
143 | public JVMStartCommandBuilder addModulePath(String... modulePath) {
144 | this.modulePath.addAll(List.of(modulePath));
145 | return this;
146 | }
147 |
148 | public String getStartTarget() {
149 | return startTarget;
150 | }
151 |
152 | public JVMStartCommandBuilder setStartTarget(String startTarget) {
153 | this.startTarget = startTarget;
154 | return this;
155 | }
156 |
157 | public List getUpgradeModulePath() {
158 | return upgradeModulePath;
159 | }
160 |
161 | public JVMStartCommandBuilder setUpgradeModulePath(List upgradeModulePath) {
162 | this.upgradeModulePath = upgradeModulePath;
163 | return this;
164 | }
165 |
166 | public JVMStartCommandBuilder setUpgradeModulePath(String... upgradeModulePath) {
167 | this.upgradeModulePath = Arrays.asList(upgradeModulePath);
168 | return this;
169 | }
170 |
171 | public JVMStartCommandBuilder addUpgradeModuleArgs(String... upgradeModulePath) {
172 | this.upgradeModulePath.addAll(List.of(upgradeModulePath));
173 | return this;
174 | }
175 |
176 | public List getClassPath() {
177 | return classPath;
178 | }
179 |
180 | public JVMStartCommandBuilder setClassPath(List classPath) {
181 | this.classPath = classPath;
182 | return this;
183 | }
184 |
185 | public JVMStartCommandBuilder setClassPath(String... classPath) {
186 | this.classPath = Arrays.asList(classPath);
187 | return this;
188 | }
189 |
190 | public JVMStartCommandBuilder addClassPath(String... classPath) {
191 | this.classPath.addAll(List.of(classPath));
192 | return this;
193 | }
194 |
195 | public Map getAddOpens() {
196 | return addOpens;
197 | }
198 |
199 | public JVMStartCommandBuilder setAddOpens(Map addOpens) {
200 | this.addOpens = addOpens;
201 | return this;
202 | }
203 |
204 | public JVMStartCommandBuilder addAddOpen(String key, String value) {
205 | addOpens.put(key, value);
206 | return this;
207 | }
208 |
209 | public JVMStartCommandBuilder addAddOpen(String key) {
210 | addOpens.put(key, "ALL-UNNAMED");
211 | return this;
212 | }
213 |
214 | public String build() {
215 | var sb = new StringBuilder();
216 | sb.append(StringUtils.tryWrapQuotation(jvmExecutable.getAbsolutePath())).append(" ");
217 | for (var entry : properties.entrySet()) {
218 | sb.append(StringUtils.tryWrapQuotation("-D" + entry.getKey() + "=" + entry.getValue())).append(" ");
219 | }
220 | for (var iterator = otherArgs.iterator(); iterator.hasNext(); ) {
221 | var each = iterator.next();
222 | if (each.startsWith("-D")) {
223 | sb.append(StringUtils.tryWrapQuotation(each)).append(" ");
224 | iterator.remove();
225 | }
226 | }
227 | for (var entry : xxOptions.entrySet()) {
228 | sb.append("-XX:");
229 | if (entry.getValue() != null) {
230 | if (entry.getValue() instanceof Boolean bool) {
231 | sb.append(bool ? "+" : "-").append(entry.getKey());
232 | } else {
233 | sb.append(entry.getKey()).append("=").append(entry.getValue());
234 | }
235 | } else {
236 | sb.append(entry.getKey());
237 | }
238 | sb.append(" ");
239 | }
240 | for (var iterator = otherArgs.iterator(); iterator.hasNext(); ) {
241 | var each = iterator.next();
242 | if (each.startsWith("-XX:")) {
243 | sb.append(each).append(" ");
244 | iterator.remove();
245 | }
246 | }
247 | for (var entry : xOptions.entrySet()) {
248 | sb.append("-X").append(entry.getKey());
249 | if (entry.getValue() != null) {
250 | sb.append(entry.getValue());
251 | }
252 | sb.append(" ");
253 | }
254 | for (var iterator = otherArgs.iterator(); iterator.hasNext(); ) {
255 | var each = iterator.next();
256 | if (each.startsWith("-X")) {
257 | sb.append(each).append(" ");
258 | iterator.remove();
259 | }
260 | }
261 | sb.append(StringUtils.tryWrapQuotation("--module-path=" + String.join(File.pathSeparator, modulePath) + File.pathSeparator)).append(" ");
262 | sb.append(StringUtils.tryWrapQuotation("--upgrade-module-path=" + String.join(File.pathSeparator, upgradeModulePath) + File.pathSeparator)).append(" ");
263 | for (var entry : addOpens.entrySet()) {
264 | sb.append("--add-opens ").append(entry.getKey()).append("=").append(entry.getValue()).append(" ");
265 | }
266 | sb.append("-cp ").append(StringUtils.tryWrapQuotation(String.join(File.pathSeparator, classPath))).append(" ");
267 | sb.append(startTarget);
268 | for (var arg : otherArgs) {
269 | sb.append(" ").append(StringUtils.tryWrapQuotation(arg));
270 | }
271 | return sb.toString();
272 | }
273 | }
274 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/converter/LocaleConverter.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.converter;
2 |
3 | import picocli.CommandLine;
4 |
5 | import java.util.Locale;
6 |
7 | public class LocaleConverter implements CommandLine.ITypeConverter {
8 | @Override
9 | public Locale convert(String s) {
10 | return Locale.forLanguageTag(s);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/GraalJITLocator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.CLIConstant;
4 |
5 | import java.io.File;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 |
10 | public class GraalJITLocator extends Locator {
11 | @Override
12 | public List> locate() {
13 | final File graalJITDir = new File(CLIConstant.userDir, "./components/graaljit");
14 | if (graalJITDir.exists() && graalJITDir.isDirectory()) {
15 | GraalJITLocation compiler = null;
16 | GraalJITLocation management = null;
17 | final File[] files = graalJITDir.listFiles((dir, name) -> name.endsWith(".jar"));
18 | if (files == null) {
19 | return Collections.emptyList();
20 | }
21 | for (File file : files) {
22 | if (file.getName().startsWith("compiler-management")) {
23 | management = new GraalJITLocation(file, file.getName().replace("compiler-management-", "").replace(".jar", ""));
24 | } else if (file.getName().startsWith("compiler")) {
25 | compiler = new GraalJITLocation(file, file.getName().replace("compiler-", "").replace(".jar", ""));
26 | }
27 | }
28 | return Arrays.asList(compiler, management);
29 | } else {
30 | return Collections.emptyList();
31 | }
32 | }
33 |
34 | public static class GraalJITLocation extends Location {
35 | public GraalJITLocation(File file, String info) {
36 | super(file, info);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/GraalModuleLocator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.CLIConstant;
4 |
5 | import java.io.File;
6 | import java.util.Arrays;
7 | import java.util.Collections;
8 | import java.util.List;
9 | import java.util.stream.Collectors;
10 |
11 | public class GraalModuleLocator extends Locator {
12 | @Override
13 | public List> locate() {
14 | final File libsDir = new File(CLIConstant.userDir, "./libs");
15 | if (libsDir.exists() && libsDir.isDirectory()) {
16 | File[] files = libsDir.listFiles();
17 | if (files == null) {
18 | return Collections.emptyList();
19 | }
20 | return Arrays.stream(files).filter(file -> (file.getName().startsWith("graal-sdk") && file.getName().endsWith(".jar")) || (file.getName().startsWith("truffle-api") && file.getName().endsWith(".jar")))
21 | .map(file -> new Location(file, null)).collect(Collectors.toList());
22 | }
23 | return Collections.emptyList();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/JarLocator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.util.GitUtils;
4 |
5 | import java.io.File;
6 | import java.io.IOException;
7 | import java.util.ArrayList;
8 | import java.util.List;
9 | import java.util.Optional;
10 | import java.util.jar.JarFile;
11 | import java.util.zip.ZipEntry;
12 |
13 | public class JarLocator extends Locator {
14 | private final File dir;
15 | private final String withClassOrPackage;
16 |
17 | public JarLocator(File dir, String withPackage) {
18 | this.dir = dir;
19 | this.withClassOrPackage = withPackage;
20 | }
21 |
22 | @Override
23 | public List> locate() {
24 | final List> output = new ArrayList<>(1);
25 | final File[] files = dir.listFiles((dir, name) -> name.endsWith(".jar"));
26 | if (files == null) return output;
27 | for (final File each : files) {
28 | if (hasPackage(each)) {
29 | output.add(new Location<>(each, new JarInfo(GitUtils.getFullGitInfo(each).orElse(null))));
30 | }
31 | }
32 | return output;
33 | }
34 |
35 | private boolean hasPackage(File file) {
36 | if (!file.exists()) {
37 | return false;
38 | }
39 | if (!file.getName().endsWith(".jar")) {
40 | return false;
41 | }
42 | try (final JarFile jarFile = new JarFile(file)) {
43 | String tmp = withClassOrPackage.replace('.', '/');
44 | ZipEntry entry = jarFile.getEntry(tmp);
45 | if (entry == null) {
46 | tmp += ".class";
47 | entry = jarFile.getJarEntry(tmp);
48 | }
49 | return entry != null;
50 | } catch (IOException e) {
51 | return false;
52 | }
53 | }
54 |
55 | public static final class JarInfo {
56 | private GitUtils.FullGitInfo gitInfo;
57 |
58 | public JarInfo(GitUtils.FullGitInfo gitInfo) {
59 | this.gitInfo = gitInfo;
60 | }
61 |
62 | public Optional getGitInfo() {
63 | return Optional.ofNullable(gitInfo);
64 | }
65 |
66 | public JarInfo setGitInfo(GitUtils.FullGitInfo gitInfo) {
67 | this.gitInfo = gitInfo;
68 | return this;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/JavaLocator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.CLIConstant;
4 | import cn.powernukkitx.cli.util.CollectionUtils;
5 | import cn.powernukkitx.cli.util.ConfigUtils;
6 | import cn.powernukkitx.cli.util.StringUtils;
7 |
8 | import java.io.BufferedReader;
9 | import java.io.File;
10 | import java.io.IOException;
11 | import java.io.InputStreamReader;
12 | import java.nio.file.Files;
13 | import java.util.*;
14 | import java.util.concurrent.TimeUnit;
15 | import java.util.stream.Collectors;
16 |
17 | public class JavaLocator extends Locator {
18 | private final String version;
19 | private final boolean sort4GraalVM;
20 |
21 | public JavaLocator(String version) {
22 | this.version = version;
23 | this.sort4GraalVM = false;
24 | }
25 |
26 | public JavaLocator(String version, boolean sort4GraalVM) {
27 | this.version = version;
28 | this.sort4GraalVM = sort4GraalVM;
29 | }
30 |
31 | @Override
32 | public List> locate() {
33 | final List> javaExecutableList = new ArrayList<>();
34 | final File localJavaDir = new File(CLIConstant.programDir, "java");
35 | final List binDirs = new ArrayList<>();
36 | { // 探测当前运行环境
37 | var javaHome = System.getProperty("java.home");
38 | if (javaHome != null) {
39 | var binDir = new File(javaHome);
40 | if (binDir.exists() && binDir.isDirectory()) {
41 | if (isJavaDir(binDir)) {
42 | binDirs.add(binDir);
43 | } else {
44 | final File innerBinDir = new File(binDir, "bin");
45 | if (isJavaDir(innerBinDir)) {
46 | binDirs.add(innerBinDir);
47 | }
48 | }
49 | }
50 | }
51 | }
52 | { // 当前文件夹下缓存探测
53 | if (localJavaDir.exists()) {
54 | final File[] files = localJavaDir.listFiles();
55 | if (files != null) {
56 | for (File each : files) {
57 | File binDir = new File(each, "bin");
58 | if (binDir.exists() && isJavaDir(binDir)) {
59 | binDirs.add(binDir);
60 | }
61 | }
62 | }
63 | }
64 | }
65 | { // JAVA*(_HOME)环境变量探测
66 | for (final Map.Entry entry : System.getenv().entrySet()) {
67 | final String key = entry.getKey();
68 | if (key.contains("JAVA") || key.contains("java") || key.contains("Java") || key.contains("GRAAL")
69 | || key.contains("graal") || key.contains("Graal") || key.contains("JDK") || key.contains("jdk")
70 | || key.contains("JRE") || key.contains("jre")) {
71 | final File binDir = new File(entry.getValue());
72 | if (binDir.exists() && binDir.isDirectory()) {
73 | if (isJavaDir(binDir)) {
74 | binDirs.add(binDir);
75 | } else {
76 | final File innerBinDir = new File(binDir, "bin");
77 | if (isJavaDir(innerBinDir)) {
78 | binDirs.add(innerBinDir);
79 | }
80 | }
81 | }
82 | }
83 | }
84 | }
85 | { // where/which探测
86 | try {
87 | Process process = new ProcessBuilder().command("where", "java").redirectErrorStream(true).start();
88 | testSystemJava(binDirs, process);
89 | } catch (IOException | InterruptedException ignore) {
90 |
91 | }
92 | try {
93 | Process process = new ProcessBuilder().command("which", "java").redirectErrorStream(true).start();
94 | testSystemJava(binDirs, process);
95 | } catch (IOException | InterruptedException ignore) {
96 |
97 | }
98 | }
99 | { // 用户自定义探测
100 | for (var each : ConfigUtils.customJVMPaths()) {
101 | if (each == null || "".equals(each)) {
102 | continue;
103 | }
104 | final File binDir = new File(each);
105 | if (binDir.exists() && binDir.isDirectory()) {
106 | if (isJavaDir(binDir)) {
107 | binDirs.add(binDir);
108 | } else {
109 | final File innerBinDir = new File(binDir, "bin");
110 | if (isJavaDir(innerBinDir)) {
111 | binDirs.add(innerBinDir);
112 | }
113 | }
114 | }
115 | }
116 | }
117 | for (final File binDir : binDirs) {
118 | Optional jv = getJavaVersion(binDir);
119 | if (jv.isPresent()) {
120 | JavaInfo v = jv.get();
121 | if (version != null && !greaterOrEqual(version, v.getMajorVersion())) {
122 | continue;
123 | }
124 | javaExecutableList.add(new Location<>(new File(binDir, "java" + Locator.platformSuffix()), v));
125 | } else if (version == null) {
126 | javaExecutableList.add(new Location<>(new File(binDir, "java" + Locator.platformSuffix()),
127 | new JavaInfo("Unknown", "Unknown", "Unknown")));
128 | }
129 | }
130 | // 去重、排序并返回
131 | final List> out = javaExecutableList.stream()
132 | .filter(CollectionUtils.distinctByKey(each -> each.getFile().getAbsolutePath()))
133 | .sorted(Comparator.comparing(a -> a.getInfo().getMajorVersion()))
134 | .collect(Collectors.toList());
135 | if (sort4GraalVM) {
136 | out.sort((a, b) -> {
137 | if (a.equals(b)) return 0;
138 | final boolean a1 = a.getInfo().getVendor().contains(ConfigUtils.preferredJVM());
139 | final boolean b1 = b.getInfo().getVendor().contains(ConfigUtils.preferredJVM());
140 | if (a1 && !b1) {
141 | return -1;
142 | } else if (!a1 && b1) {
143 | return 1;
144 | } else {
145 | return 0;
146 | }
147 | });
148 | }
149 | return out;
150 | }
151 |
152 | private boolean greaterOrEqual(String targetVersion, String givenVersion) {
153 | try {
154 | var target = Integer.parseInt(targetVersion);
155 | var given = Integer.parseInt(givenVersion);
156 | return given >= target;
157 | } catch (Exception ignore) {
158 | return targetVersion.equals(givenVersion);
159 | }
160 | }
161 |
162 | private void testSystemJava(List binDirs, Process process) throws InterruptedException, IOException {
163 | BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
164 | process.waitFor(1000, TimeUnit.MILLISECONDS);
165 | String s;
166 | while ((s = reader.readLine()) != null) {
167 | if (s.contains("java")) {
168 | binDirs.add(new File(s).getParentFile());
169 | }
170 | }
171 | process.destroy();
172 | }
173 |
174 | private boolean isJavaDir(File binDir) {
175 | if (!binDir.exists()) return false;
176 | final File javaExecutable = new File(binDir, "java" + Locator.platformSuffix());
177 | return javaExecutable.exists();
178 | }
179 |
180 | private Optional getJavaVersion(File binDir) {
181 | final File javaExecutable = new File(binDir, "java" + Locator.platformSuffix());
182 | if (!javaExecutable.canExecute()) {
183 | boolean r = javaExecutable.setExecutable(true);
184 | if (!r) {
185 | return Optional.empty();
186 | }
187 | }
188 | try {
189 | Process process = new ProcessBuilder().command(StringUtils.tryWrapQuotation(javaExecutable.getAbsolutePath()), "-version")
190 | .redirectErrorStream(true).start();
191 | BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
192 | process.waitFor(1000, TimeUnit.MILLISECONDS);
193 | String s;
194 | String fullVersion = null;
195 | String majorVersion = null;
196 | String vendor = null;
197 | while ((s = reader.readLine()) != null) {
198 | if (s.contains("version")) {
199 | String[] t = s.split("\"");
200 | if (t.length >= 2) {
201 | fullVersion = t[1];
202 | String[] tmp = fullVersion.split("\\.");
203 | majorVersion = tmp[0];
204 | if ("1".equals(tmp[0])) {
205 | majorVersion = tmp[1];
206 | }
207 | majorVersion = majorVersion.replace("-internal", "");
208 | }
209 | } else if (s.contains("Server VM") || s.contains("Runtime")) {
210 | vendor = StringUtils.beforeLast(s, " (build");
211 | }
212 | }
213 | process.destroy();
214 | if (majorVersion != null && vendor != null)
215 | return Optional.of(new JavaInfo(majorVersion, fullVersion, vendor));
216 | } catch (IOException | InterruptedException ignore) {
217 |
218 | }
219 | return getJavaVersionByJVMTI(binDir);
220 | }
221 |
222 | private Optional getJavaVersionByJVMTI(File binDir) {
223 | var includeDir = new File(binDir.getParentFile(), "include");
224 | if (!includeDir.exists()) {
225 | return Optional.empty();
226 | }
227 | var jvmtiFile = new File(includeDir, "jvmti.h");
228 | if (!jvmtiFile.exists()) {
229 | return Optional.empty();
230 | }
231 | try {
232 | var lines = Files.readAllLines(jvmtiFile.toPath());
233 | for (var line : lines) {
234 | var tmp = line.trim();
235 | if (tmp.startsWith("JVMTI_VERSION = 0x30000000 + (")) {
236 | var i = tmp.indexOf(" * 0x10000");
237 | var majorVersion = tmp.substring(30, i);
238 | var fullVersion = majorVersion + ".0.0";
239 | return Optional.of(new JavaInfo(majorVersion, fullVersion, "Unknown"));
240 | }
241 | }
242 | } catch (Exception ignore) {
243 |
244 | }
245 | return Optional.empty();
246 | }
247 |
248 | public static final class JavaInfo {
249 | private String majorVersion;
250 | private String fullVersion;
251 | private String vendor;
252 |
253 | public JavaInfo(String majorVersion, String fullVersion, String vendor) {
254 | this.majorVersion = majorVersion;
255 | this.fullVersion = fullVersion;
256 | this.vendor = vendor;
257 | }
258 |
259 | public String getMajorVersion() {
260 | return majorVersion;
261 | }
262 |
263 | public JavaInfo setMajorVersion(String majorVersion) {
264 | this.majorVersion = majorVersion;
265 | return this;
266 | }
267 |
268 | public String getFullVersion() {
269 | return fullVersion;
270 | }
271 |
272 | public JavaInfo setFullVersion(String fullVersion) {
273 | this.fullVersion = fullVersion;
274 | return this;
275 | }
276 |
277 | public String getVendor() {
278 | return vendor;
279 | }
280 |
281 | public JavaInfo setVendor(String vendor) {
282 | this.vendor = vendor;
283 | return this;
284 | }
285 |
286 | @Override
287 | public String toString() {
288 | return "JavaInfo{" +
289 | "majorVersion='" + majorVersion + '\'' +
290 | ", fullVersion='" + fullVersion + '\'' +
291 | ", vendor='" + vendor + '\'' +
292 | '}';
293 | }
294 | }
295 | }
296 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/LibsLocator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.CLIConstant;
4 | import cn.powernukkitx.cli.data.remote.VersionListHelper;
5 |
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.util.Date;
9 | import java.util.List;
10 | import java.util.stream.Collectors;
11 |
12 | public class LibsLocator extends Locator {
13 | @Override
14 | public List> locate() {
15 | try {
16 | var libEntries = VersionListHelper.listRemoteLibs();
17 | return libEntries.stream().map(each -> {
18 | final File file = new File(CLIConstant.userDir, "./libs/" + each.getLibName());
19 | return new Location<>(file, new LibInfo(each.getLibName(), each.getLastUpdate(), file.exists(), !file.exists() || each.getLastUpdate().getTime() > file.lastModified()));
20 | }).collect(Collectors.toList());
21 | } catch (IOException | InterruptedException e) {
22 | e.printStackTrace();
23 | }
24 | return List.of();
25 | }
26 |
27 | public static final class LibInfo {
28 | private String name;
29 | private Date lastUpdate;
30 | private boolean exists;
31 | private boolean needsUpdate;
32 |
33 | public LibInfo(String name, Date lastUpdate, boolean exists, boolean needsUpdate) {
34 | this.name = name;
35 | this.lastUpdate = lastUpdate;
36 | this.exists = exists;
37 | this.needsUpdate = needsUpdate;
38 | }
39 |
40 | public String getName() {
41 | return name;
42 | }
43 |
44 | public LibInfo setName(String name) {
45 | this.name = name;
46 | return this;
47 | }
48 |
49 | public boolean isExists() {
50 | return exists;
51 | }
52 |
53 | public LibInfo setExists(boolean exists) {
54 | this.exists = exists;
55 | return this;
56 | }
57 |
58 | public Date getLastUpdate() {
59 | return lastUpdate;
60 | }
61 |
62 | public LibInfo setLastUpdate(Date lastUpdate) {
63 | this.lastUpdate = lastUpdate;
64 | return this;
65 | }
66 |
67 | public boolean isNeedsUpdate() {
68 | return needsUpdate;
69 | }
70 |
71 | public LibInfo setNeedsUpdate(boolean needsUpdate) {
72 | this.needsUpdate = needsUpdate;
73 | return this;
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/Location.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import java.io.File;
4 |
5 | public class Location {
6 | private File file;
7 | private T info;
8 |
9 | public Location(File file, T info) {
10 | this.file = file;
11 | this.info = info;
12 | }
13 |
14 | public File getFile() {
15 | return file;
16 | }
17 |
18 | public Location setFile(File file) {
19 | this.file = file;
20 | return this;
21 | }
22 |
23 | public T getInfo() {
24 | return info;
25 | }
26 |
27 | public Location setInfo(T info) {
28 | this.info = info;
29 | return this;
30 | }
31 |
32 | @Override
33 | public String toString() {
34 | return "Location{" +
35 | "file=" + file +
36 | ", info=" + info +
37 | '}';
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/locator/Locator.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.locator;
2 |
3 | import cn.powernukkitx.cli.util.EnumOS;
4 | import cn.powernukkitx.cli.util.OSUtils;
5 |
6 | import java.io.File;
7 | import java.util.List;
8 |
9 | public abstract class Locator {
10 | public abstract List> locate();
11 |
12 | public static String platformSuffix() {
13 | if (OSUtils.getOS() == EnumOS.WINDOWS) {
14 | return ".exe";
15 | } else {
16 | return "";
17 | }
18 | }
19 |
20 | public static String platformSplitter() {
21 | return File.separator;
22 | }
23 | }
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/remote/VersionListHelper.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.remote;
2 |
3 | import cn.powernukkitx.cli.util.StringUtils;
4 |
5 | import java.io.IOException;
6 | import java.net.URI;
7 | import java.net.http.HttpClient;
8 | import java.net.http.HttpRequest;
9 | import java.net.http.HttpResponse;
10 | import java.nio.charset.StandardCharsets;
11 | import java.text.ParseException;
12 | import java.text.SimpleDateFormat;
13 | import java.util.*;
14 | import java.util.regex.Matcher;
15 | import java.util.regex.Pattern;
16 |
17 | public final class VersionListHelper {
18 | public static final String OSS = "https://pnx-assets.oss-cn-hongkong.aliyuncs.com";
19 | public static final Pattern keyPattern = Pattern.compile("(?<=)(.*?)(?=)");
20 | public static final Pattern timePattern = Pattern.compile("(?<=)([0-9TZ:.-]*)(?=)");
21 | public static final SimpleDateFormat utcTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
22 | public static final SimpleDateFormat commonTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
23 | private static final WeakHashMap cache = new WeakHashMap<>(3);
24 |
25 | static {
26 | utcTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
27 | commonTimeFormat.setTimeZone(TimeZone.getDefault());
28 | }
29 |
30 | public static List listRemoteVersions(final String category) throws IOException, InterruptedException {
31 | if (cache.containsKey(category)) {
32 | return exactKeys(cache.get(category));
33 | } else {
34 | var client = HttpClient.newHttpClient();
35 | var request = HttpRequest.newBuilder(URI.create(OSS + "?" +
36 | "list-type=2" + "&" +
37 | "prefix=" + category + "/&" +
38 | "max-keys=999" + "&" +
39 | "delimiter=/")).GET().build();
40 | final var result = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body();
41 | cache.put(category, result);
42 | return exactKeys(result);
43 | }
44 | }
45 |
46 | public static List listRemoteLibs() throws IOException, InterruptedException {
47 | if (cache.containsKey("libs")) {
48 | return exactLibs(cache.get("libs"));
49 | } else {
50 | var client = HttpClient.newHttpClient();
51 | var request = HttpRequest.newBuilder(URI.create(OSS + "?" +
52 | "list-type=2" + "&" +
53 | "prefix=libs" + "/&" +
54 | "max-keys=100" + "&" +
55 | "delimiter=/")).GET().build();
56 | final var result = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body();
57 | cache.put("libs", result);
58 | return exactLibs(result);
59 | }
60 | }
61 |
62 | private static List exactKeys(final String xml) {
63 | final Matcher keyMatcher = keyPattern.matcher(xml);
64 | final List out = new ArrayList<>(20);
65 | while (keyMatcher.find()) {
66 | final String[] tmp = keyMatcher.group(0).split("-");
67 | out.add(new VersionEntry().setBranch(StringUtils.afterFirst(tmp[0], "/")).setCommit(tmp[1]));
68 | }
69 |
70 | final Matcher timeMatcher = timePattern.matcher(xml);
71 | int i = 0;
72 | while (timeMatcher.find()) {
73 | try {
74 | out.get(i++).setTime(utcTimeFormat.parse(timeMatcher.group(0)));
75 | } catch (ParseException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 |
80 | if (out.get(0).getCommit().endsWith("/")) {
81 | out.remove(0);
82 | }
83 |
84 | out.sort((a, b) -> b.time.compareTo(a.time));
85 | return out;
86 | }
87 |
88 | private static List exactLibs(final String xml) {
89 | final Matcher keyMatcher = keyPattern.matcher(xml);
90 | final List out = new ArrayList<>(80);
91 | while (keyMatcher.find()) {
92 | final String name = keyMatcher.group(0);
93 | out.add(new LibEntry().setLibName(StringUtils.afterFirst(name, "/")));
94 | }
95 |
96 | final Matcher timeMatcher = timePattern.matcher(xml);
97 | int i = 0;
98 | while (timeMatcher.find()) {
99 | try {
100 | out.get(i++).setLastUpdate(utcTimeFormat.parse(timeMatcher.group(0)));
101 | } catch (ParseException e) {
102 | e.printStackTrace();
103 | }
104 | }
105 |
106 | if (out.size() == 0) {
107 | throw new IllegalArgumentException("Failed to parse the libs list, raw xml: \n" + xml);
108 | }
109 |
110 | if ("".equals(out.get(0).getLibName())) {
111 | out.remove(0);
112 | }
113 |
114 | return out;
115 | }
116 |
117 | public static final class VersionEntry {
118 | private String branch;
119 | private String commit;
120 | private Date time;
121 |
122 | public String getBranch() {
123 | return branch;
124 | }
125 |
126 | public VersionEntry setBranch(String branch) {
127 | this.branch = branch;
128 | return this;
129 | }
130 |
131 | public String getCommit() {
132 | return commit;
133 | }
134 |
135 | public VersionEntry setCommit(String commit) {
136 | this.commit = commit;
137 | return this;
138 | }
139 |
140 | public String getTime() {
141 | return commonTimeFormat.format(time);
142 | }
143 |
144 | public VersionEntry setTime(Date time) {
145 | this.time = time;
146 | return this;
147 | }
148 |
149 | @Override
150 | public String toString() {
151 | return "{" +
152 | "branch='" + branch + '\'' +
153 | ", commit='" + commit + '\'' +
154 | ", time='" + time + '\'' +
155 | '}';
156 | }
157 | }
158 |
159 | public static final class LibEntry {
160 | private String libName;
161 | private Date lastUpdate;
162 |
163 | public String getLibName() {
164 | return libName;
165 | }
166 |
167 | public LibEntry setLibName(String libName) {
168 | this.libName = libName;
169 | return this;
170 | }
171 |
172 | public Date getLastUpdate() {
173 | return lastUpdate;
174 | }
175 |
176 | public LibEntry setLastUpdate(Date lastUpdate) {
177 | this.lastUpdate = lastUpdate;
178 | return this;
179 | }
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/src/main/java/cn/powernukkitx/cli/data/remote/VersionListHelperV2.java:
--------------------------------------------------------------------------------
1 | package cn.powernukkitx.cli.data.remote;
2 |
3 | import cn.powernukkitx.cli.Main;
4 | import cn.powernukkitx.cli.data.bean.*;
5 | import cn.powernukkitx.cli.util.HttpUtils;
6 | import com.google.gson.JsonParser;
7 | import org.jetbrains.annotations.NotNull;
8 |
9 | import java.io.IOException;
10 | import java.net.URI;
11 | import java.net.http.HttpRequest;
12 | import java.net.http.HttpResponse;
13 | import java.nio.charset.StandardCharsets;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import java.util.concurrent.CompletableFuture;
17 |
18 | import static cn.powernukkitx.cli.util.HttpUtils.getAPIUrl;
19 |
20 | public final class VersionListHelperV2 {
21 | private VersionListHelperV2() {
22 | throw new UnsupportedOperationException();
23 | }
24 |
25 | public static @NotNull ReleaseBean getLatestRelease() throws IOException, InterruptedException {
26 | var client = HttpUtils.getClient();
27 | var request = HttpRequest.newBuilder(URI.create(getAPIUrl() + "/git/latest-release/PowerNukkitX/PowerNukkitX")).GET().build();
28 | var future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
29 | var result = HttpUtils.joinFutureWithPlaceholder(future).body();
30 | return ReleaseBean.from(JsonParser.parseString(result).getAsJsonObject());
31 | }
32 |
33 | public static @NotNull ReleaseBean @NotNull [] getAllReleases() throws IOException, InterruptedException {
34 | var client = HttpUtils.getClient();
35 | var request = HttpRequest.newBuilder(URI.create(getAPIUrl() + "/git/all-releases/PowerNukkitX/PowerNukkitX")).GET().build();
36 | var future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
37 | var result = HttpUtils.joinFutureWithPlaceholder(future).body();
38 | var jsonArray = JsonParser.parseString(result).getAsJsonArray();
39 | var releases = new ReleaseBean[jsonArray.size()];
40 | for (int i = 0; i < releases.length; i++) {
41 | releases[i] = ReleaseBean.from(jsonArray.get(i).getAsJsonObject());
42 | }
43 | return releases;
44 | }
45 |
46 | public static @NotNull BuildBean getLatestBuild() throws IOException, InterruptedException {
47 | var client = HttpUtils.getClient();
48 | var request = HttpRequest.newBuilder(URI.create(getAPIUrl() + "/git/latest-build/PowerNukkitX/PowerNukkitX")).GET().build();
49 | var future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
50 | var result = HttpUtils.joinFutureWithPlaceholder(future).body();
51 | return BuildBean.from(JsonParser.parseString(result).getAsJsonObject());
52 | }
53 |
54 | public static @NotNull CompletableFuture