Skip to content

Commit

Permalink
fix: read properties files to get APP_URL
Browse files Browse the repository at this point in the history
  • Loading branch information
benny123tw committed Jun 7, 2024
1 parent 96e91f8 commit 5aabaf8
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 12 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,8 @@ dist-ssr
*.sw?

# Plugin hot file
hot
hot

# Java
target/
build/
3 changes: 0 additions & 3 deletions examples/vanilla/.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
# Custom app url
# APP_URL=

# Filter debug logs
# VITE_DEBUG_FILTER=
2 changes: 2 additions & 0 deletions examples/vanilla/src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
app.url=http://localhost:8080
app.name=Vite Java App
4 changes: 2 additions & 2 deletions examples/vanilla/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { defineConfig } from 'vite'
import java, { createRollupInputConfig } from 'vite-plugin-java'

export default defineConfig(() => ({
export default defineConfig({
plugins: [java({
input: createRollupInputConfig(),
})],
}))
})
2 changes: 1 addition & 1 deletion packages/vite-plugin-java/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ export interface VitePluginJavaConfig {

export type DevServerUrl = `${'http' | 'https'}://${string}:${number}`

export { PLUGIN_NAME, createRollupInputConfig } from './utils'
export { PLUGIN_NAME, createRollupInputConfig, readPropertiesFile } from './utils'
export { java }
export default java
24 changes: 24 additions & 0 deletions packages/vite-plugin-java/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import type { AddressInfo } from 'node:net'
import debug from 'debug'
import type { GlobOptions } from 'glob'
import { globSync } from 'glob'
import 'dotenv/config'
import { merge } from 'smob'
Expand Down Expand Up @@ -101,3 +102,26 @@ export function isMavenProject(): boolean {
export function isGradleProject(): boolean {
return fs.existsSync(path.join(process.cwd(), 'build.gradle'))
}

/**
* Reads the properties from the project files.
*
* @returns A map containing the key-value pairs of the properties.
*/
export function readPropertiesFile(pattern?: string | string[], options?: GlobOptions): Map<string, string> {
const properties: Map<string, string> = new Map()
const _pattern = pattern || '**/*.properties'
const _options = merge({}, options || {}, { cwd: process.cwd() })

globSync(_pattern, _options).forEach((file) => {
const _file = typeof file === 'string' ? file : file.path
const content = fs.readFileSync(_file, 'utf-8')
content.split('\n').filter(c => !c?.trim().startsWith('#')).forEach((line) => {
const [key, value] = line.split('=')
if (key)
properties.set(key?.trim(), value?.trim())
})
})

return properties
}
12 changes: 8 additions & 4 deletions packages/vite-plugin-java/src/vite-plugin-java.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { loadEnv } from 'vite'
import { merge } from 'smob'
import colors from 'picocolors'
import swc from '@rollup/plugin-swc'
import { PLUGIN_NAME, createDebugger, dirname, isGradleProject, isIpv6, isMavenProject } from './utils'
import { PLUGIN_NAME, createDebugger, dirname, isGradleProject, isIpv6, isMavenProject, readPropertiesFile } from './utils'
import type { DevServerUrl, VitePluginJavaConfig } from '.'

const debug = createDebugger(`${PLUGIN_NAME}`)
Expand Down Expand Up @@ -120,8 +120,9 @@ function resolveJavaPlugin(pluginConfig: Required<VitePluginJavaConfig>): [JavaP
}
},
configureServer(server) {
const envDir = resolvedConfig.envDir || process.cwd()
const appUrl = loadEnv(resolvedConfig.mode, envDir, 'APP_URL').APP_URL ?? 'undefined'
// TODO: Add support for reading yaml files.
const properties = readPropertiesFile()
const appUrl = properties.get('app.url') ?? 'undefined'

server.httpServer?.once('listening', () => {
debug?.('server listening.')
Expand All @@ -136,7 +137,10 @@ function resolveJavaPlugin(pluginConfig: Required<VitePluginJavaConfig>): [JavaP
setTimeout(() => {
server.config.logger.info(`\n ${colors.red(`${colors.bold('JAVA')} ${javaVersion()}`)} ${colors.dim('plugin')} ${colors.bold(`v${pluginVersion()}`)}`)
server.config.logger.info('')
server.config.logger.info(` ${colors.green('➜')} ${colors.bold('APP_URL')}: ${colors.cyan(appUrl.replace(/:(\d+)/, (_, port) => `:${colors.bold(port)}`))}`)

if (appUrl !== 'undefined') {
server.config.logger.info(` ${colors.green('➜')} ${colors.bold('APP_URL')}: ${colors.cyan(appUrl.replace(/:(\d+)/, (_, port) => `:${colors.bold(port)}`))}`)
}
}, 100)
}
})
Expand Down
20 changes: 19 additions & 1 deletion packages/vite-plugin-java/test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { createRollupInputConfig } from '../src/utils'
import { createRollupInputConfig, readPropertiesFile } from '../src/utils'

const files = [
'src/main.ts',
Expand Down Expand Up @@ -48,4 +48,22 @@ describe('vite-plugin-java - utils', () => {
[path.normalize('nested/main')]: getAbsolutePath('src/nested/main.ts'),
})
})

it('should read properties and return mapped entries', () => {
const expectedProperties = new Map(
[
['app.url', 'http://localhost:8080'],
['app.name', 'Vite Java App'],
],
)
let content = ''

for (const [key, value] of expectedProperties.entries()) {
content += `${key}=${value}\n`
}
fs.writeFileSync('fixtures/application.properties', content)

const propertiesMap = readPropertiesFile()
expect(propertiesMap).toEqual(expectedProperties)
})
})

0 comments on commit 5aabaf8

Please sign in to comment.