Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1c3b54c

Browse files
committed
feat: add javaProjectBase option for specifying Java project root path
1 parent e316c09 commit 1c3b54c

File tree

7 files changed

+158
-53
lines changed

7 files changed

+158
-53
lines changed

packages/vite-plugin-java/src/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ export interface VitePluginJavaConfig {
5252
*/
5353
hotFile?: string
5454

55+
/**
56+
* The path to the Java project root.
57+
*/
58+
javaProjectBase?: string
59+
5560
/**
5661
* Transform the code while serving.
5762
*/

packages/vite-plugin-java/src/utils.ts

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,17 +90,25 @@ export function dirname(): string {
9090
*
9191
* @returns True if the current project is a Maven project, false otherwise.
9292
*/
93-
export function isMavenProject(): boolean {
94-
return fs.existsSync(path.join(process.cwd(), 'pom.xml'))
93+
export function isMavenProject(projectRoot: string = ''): boolean {
94+
return fs.existsSync(path.join(projectRoot || process.cwd(), 'pom.xml'))
9595
}
9696

9797
/**
9898
* Checks if the current project is a Gradle project.
9999
*
100100
* @returns True if the current project is a Gradle project, false otherwise.
101101
*/
102-
export function isGradleProject(): boolean {
103-
return fs.existsSync(path.join(process.cwd(), 'build.gradle'))
102+
export function isGradleProject(projectRoot: string = ''): boolean {
103+
return fs.existsSync(path.join(projectRoot || process.cwd(), 'build.gradle'))
104+
}
105+
106+
/**
107+
* Checks if the current project is a Kotlin DSL project.
108+
* @returns True if the current project is a Kotlin DSL project, false otherwise.
109+
*/
110+
export function isKotlinDSLProject(projectRoot: string = ''): boolean {
111+
return fs.existsSync(path.join(projectRoot || process.cwd(), 'build.gradle.kts'))
104112
}
105113

106114
/**
@@ -125,3 +133,54 @@ export function readPropertiesFile(pattern?: string | string[], options?: GlobOp
125133

126134
return properties
127135
}
136+
137+
/**
138+
* The version of Java being run.
139+
*
140+
* @param projectRoot - The root directory of the Java project.
141+
*/
142+
export function javaVersion(projectRoot: string = '.'): string {
143+
try {
144+
let version: string | undefined
145+
146+
if (isMavenProject(projectRoot)) {
147+
const pom = fs.readFileSync(path.join(projectRoot, 'pom.xml')).toString()
148+
version = pom.match(/<java.version>(.*)<\/java.version>/)?.[1]
149+
}
150+
151+
if (isGradleProject(projectRoot)) {
152+
const gradle = fs.readFileSync(path.join(projectRoot, 'build.gradle')).toString()
153+
version = gradle.match(/sourceCompatibility\s*=\s*['"]?(\d+(\.\d+)?)['"]?/i)?.[1]
154+
155+
if (!version) {
156+
version = gradle.match(/sourceCompatibility\s*=\s*JavaVersion\.VERSION_(\d+(_\d+)?)/i)?.[1]?.replace('_', '.')
157+
}
158+
}
159+
160+
if (isKotlinDSLProject(projectRoot)) {
161+
const gradleKts = fs.readFileSync(path.join(projectRoot, 'build.gradle.kts')).toString()
162+
version = gradleKts.match(/sourceCompatibility\s*=\s*JavaVersion\.VERSION_(\d+(_\d+)?)/i)?.[1]?.replace('_', '.')
163+
164+
if (!version) {
165+
version = gradleKts.match(/java\.sourceCompatibility\s*=\s*JavaVersion\.VERSION_(\d+(_\d+)?)/i)?.[1]?.replace('_', '.')
166+
}
167+
}
168+
169+
return version || ''
170+
}
171+
catch {
172+
return ''
173+
}
174+
}
175+
176+
/**
177+
* The version of the Vite plugin Java being run.
178+
*/
179+
export function pluginVersion(): string {
180+
try {
181+
return JSON.parse(fs.readFileSync(path.join(dirname(), '../package.json')).toString())?.version
182+
}
183+
catch {
184+
return ''
185+
}
186+
}

packages/vite-plugin-java/src/vite-plugin-java.ts

Lines changed: 3 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { loadEnv } from 'vite'
88
import { merge } from 'smob'
99
import colors from 'picocolors'
1010
import swc from '@rollup/plugin-swc'
11-
import { PLUGIN_NAME, createDebugger, dirname, isGradleProject, isIpv6, isMavenProject, readPropertiesFile } from './utils'
11+
import { PLUGIN_NAME, createDebugger, dirname, isIpv6, javaVersion, pluginVersion, readPropertiesFile } from './utils'
1212
import type { DevServerUrl, VitePluginJavaConfig } from '.'
1313

1414
const debug = createDebugger(`${PLUGIN_NAME}`)
@@ -136,7 +136,7 @@ function resolveJavaPlugin(pluginConfig: Required<VitePluginJavaConfig>): [JavaP
136136
fs.writeFileSync(pluginConfig.hotFile, `${viteDevServerUrl}${server.config.base.replace(/\/$/, '')}`)
137137

138138
setTimeout(() => {
139-
server.config.logger.info(`\n ${colors.red(`${colors.bold('JAVA')} ${javaVersion()}`)} ${colors.dim('plugin')} ${colors.bold(`v${pluginVersion()}`)}`)
139+
server.config.logger.info(`\n ${colors.red(`${colors.bold('JAVA')} ${javaVersion(pluginConfig.javaProjectBase)}`)} ${colors.dim('plugin')} ${colors.bold(`v${pluginVersion()}`)}`)
140140
server.config.logger.info('')
141141

142142
if (appUrl !== 'undefined') {
@@ -188,42 +188,6 @@ function resolveJavaPlugin(pluginConfig: Required<VitePluginJavaConfig>): [JavaP
188188
return plugins
189189
}
190190

191-
/**
192-
* The version of Java being run.
193-
*/
194-
function javaVersion(): string {
195-
try {
196-
let version: string | undefined
197-
198-
if (isMavenProject()) {
199-
const pom = fs.readFileSync('pom.xml').toString()
200-
version = pom.match(/<java.version>(.*)<\/java.version>/)?.[1]
201-
}
202-
203-
if (isGradleProject()) {
204-
const gradle = fs.readFileSync('build.gradle').toString()
205-
version = gradle.match(/sourceCompatibility = '(.*)'/)?.[1]
206-
}
207-
208-
return version || ''
209-
}
210-
catch {
211-
return ''
212-
}
213-
}
214-
215-
/**
216-
* The version of the Vite plugin Java being run.
217-
*/
218-
function pluginVersion(): string {
219-
try {
220-
return JSON.parse(fs.readFileSync(path.join(dirname(), '../package.json')).toString())?.version
221-
}
222-
catch {
223-
return ''
224-
}
225-
}
226-
227191
function resolvePluginConfig(config: string | string[] | VitePluginJavaConfig): Required<VitePluginJavaConfig> {
228192
if (typeof config === 'undefined') {
229193
throw new PluginError(`missing configuration.`)
@@ -265,6 +229,7 @@ function resolvePluginConfig(config: string | string[] | VitePluginJavaConfig):
265229
tsCompiler: config.tsCompiler ?? 'esbuild',
266230
swcOptions: config.swcOptions ?? {},
267231
hotFile: config.hotFile ?? path.join((config.publicDirectory ?? 'public'), 'hot'),
232+
javaProjectBase: config.javaProjectBase ?? '.',
268233
transformOnServe: config.transformOnServe ?? (code => code),
269234
}
270235
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
description = "This is a test project for vite-plugin-java"
2+
3+
plugin {
4+
id 'java'
5+
}
6+
7+
Java {
8+
sourceCompatibility = JavaVersion.VERSION_1_8
9+
targetCompatibility = JavaVersion.VERSION_1_8
10+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
description = "This is a test project"
2+
3+
plugin {
4+
"java"
5+
}
6+
7+
java.sourceCompatibility = JavaVersion.VERSION_21
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.example</groupId>
8+
<artifactId>my-spring-mvc-app</artifactId>
9+
<version>1.0.0</version>
10+
11+
<properties>
12+
<java.version>11</java.version>
13+
</properties>
14+
15+
<dependencies>
16+
<!-- Add Spring MVC dependencies here -->
17+
</dependencies>
18+
19+
<build>
20+
<plugins>
21+
<!-- Add Maven plugins here -->
22+
</plugins>
23+
</build>
24+
25+
</project>

packages/vite-plugin-java/test/utils.test.ts

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
33
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
4-
import { createRollupInputConfig, readPropertiesFile } from '../src/utils'
4+
import { createRollupInputConfig, javaVersion, readPropertiesFile } from '../src/utils'
55

66
const files = [
77
'src/main.ts',
@@ -10,6 +10,7 @@ const files = [
1010
'src/nested/main.ts',
1111
'src/nested/other.ts',
1212
]
13+
const TEMP_FIXTURES_FOLDER = '__fixtures__'
1314

1415
function getAbsolutePath(filepath: string) {
1516
return path.normalize(path.resolve(process.cwd(), filepath))
@@ -18,30 +19,30 @@ function getAbsolutePath(filepath: string) {
1819
describe('vite-plugin-java - utils', () => {
1920
beforeAll(() => {
2021
for (const file of files) {
21-
const filePath = path.join('fixtures', file)
22+
const filePath = path.join(TEMP_FIXTURES_FOLDER, file)
2223
fs.mkdirSync(path.dirname(filePath), { recursive: true })
2324
fs.writeFileSync(filePath, '/** I love Java! **/')
2425
}
2526
})
2627

2728
afterAll(() => {
28-
fs.rmSync('fixtures', { recursive: true, force: true })
29+
fs.rmSync(TEMP_FIXTURES_FOLDER, { recursive: true, force: true })
2930
})
3031

3132
it('should find all the entry files', () => {
32-
const inputs = createRollupInputConfig('fixtures/src/**/*.ts', 'fixtures/src')
33+
const inputs = createRollupInputConfig(`${TEMP_FIXTURES_FOLDER}/src/**/*.ts`, `${TEMP_FIXTURES_FOLDER}/src`)
3334

3435
expect(inputs).toEqual({
35-
main: getAbsolutePath('fixtures/src/main.ts'),
36-
other: getAbsolutePath('fixtures/src/other.ts'),
37-
another: getAbsolutePath('fixtures/src/another.ts'),
38-
[path.normalize('nested/main')]: getAbsolutePath('fixtures/src/nested/main.ts'),
39-
[path.normalize('nested/other')]: getAbsolutePath('fixtures/src/nested/other.ts'),
36+
main: getAbsolutePath(`${TEMP_FIXTURES_FOLDER}/src/main.ts`),
37+
other: getAbsolutePath(`${TEMP_FIXTURES_FOLDER}/src/other.ts`),
38+
another: getAbsolutePath(`${TEMP_FIXTURES_FOLDER}/src/another.ts`),
39+
[path.normalize('nested/main')]: getAbsolutePath(`${TEMP_FIXTURES_FOLDER}/src/nested/main.ts`),
40+
[path.normalize('nested/other')]: getAbsolutePath(`${TEMP_FIXTURES_FOLDER}/src/nested/other.ts`),
4041
})
4142
})
4243

4344
it('should find all the entry files with cwd setup', () => {
44-
const inputs = createRollupInputConfig('src/**/main.ts', 'src', { cwd: 'fixtures' })
45+
const inputs = createRollupInputConfig('src/**/main.ts', 'src', { cwd: TEMP_FIXTURES_FOLDER })
4546

4647
expect(inputs).toEqual({
4748
main: getAbsolutePath('src/main.ts'),
@@ -61,9 +62,42 @@ describe('vite-plugin-java - utils', () => {
6162
for (const [key, value] of expectedProperties.entries()) {
6263
content += `${key}=${value}\n`
6364
}
64-
fs.writeFileSync('fixtures/application.properties', content)
65+
fs.writeFileSync(`${TEMP_FIXTURES_FOLDER}/application.properties`, content)
6566

6667
const propertiesMap = readPropertiesFile()
6768
expect(propertiesMap).toEqual(expectedProperties)
6869
})
70+
71+
it('should read the Java version from a Maven project', () => {
72+
// set up as a Maven project
73+
fs.copyFileSync(path.resolve(__dirname, 'fixtures/pom.xml'), `${TEMP_FIXTURES_FOLDER}/pom.xml`)
74+
75+
const expectedVersion = '11'
76+
const version = javaVersion(TEMP_FIXTURES_FOLDER)
77+
expect(version).toBe(expectedVersion)
78+
79+
fs.rmSync(`${TEMP_FIXTURES_FOLDER}/pom.xml`)
80+
})
81+
82+
it('should read the Java version from a Gradle project', () => {
83+
// set up as a Gradle project
84+
fs.copyFileSync(path.resolve(__dirname, 'fixtures/build.gradle'), `${TEMP_FIXTURES_FOLDER}/build.gradle`)
85+
86+
const expectedVersion = '1.8'
87+
const version = javaVersion(TEMP_FIXTURES_FOLDER)
88+
expect(version).toBe(expectedVersion)
89+
90+
fs.rmSync(`${TEMP_FIXTURES_FOLDER}/build.gradle`)
91+
})
92+
93+
it('should read the Java version from a Kotlin DSL project', () => {
94+
// set up as a Kotlin DSL project
95+
fs.copyFileSync(path.resolve(__dirname, 'fixtures/build.gradle.kts'), `${TEMP_FIXTURES_FOLDER}/build.gradle.kts`)
96+
97+
const expectedVersion = '21'
98+
const version = javaVersion(TEMP_FIXTURES_FOLDER)
99+
expect(version).toBe(expectedVersion)
100+
101+
fs.rmSync(`${TEMP_FIXTURES_FOLDER}/build.gradle.kts`)
102+
})
69103
})

0 commit comments

Comments
 (0)