Skip to content

Commit

Permalink
feat: add tusken/dotenv
Browse files Browse the repository at this point in the history
…and inject a statement into the generated client (when "dotenv" is installed) that loads the .env file automatically
  • Loading branch information
aleclarson committed Sep 20, 2022
1 parent 4041f26 commit 5a58d14
Show file tree
Hide file tree
Showing 10 changed files with 89 additions and 34 deletions.
4 changes: 2 additions & 2 deletions packages/tusken-cli/package.json
Expand Up @@ -29,15 +29,15 @@
"misty": "^1.6.10",
"pg": "^8.8.0",
"tsup": "^6.2.2",
"tusken": "1.0.0-alpha.9",
"typescript": "^4.7.4"
},
"dependencies": {
"@cush/exec": "^1.8.0",
"@tusken/schema": "1.0.0-alpha.9",
"chokidar": "^3.5.3",
"dotenv": "^16.0.2",
"jiti": "^1.14.0"
"jiti": "^1.14.0",
"tusken": "1.0.0-alpha.9"
},
"peerDependencies": {
"pg": ">=8.0.0"
Expand Down
21 changes: 0 additions & 21 deletions packages/tusken-cli/src/dotenv.ts

This file was deleted.

5 changes: 3 additions & 2 deletions packages/tusken-cli/src/index.ts
Expand Up @@ -2,17 +2,18 @@ import exec from '@cush/exec'
import { getClientEnv } from '@tusken/schema'
import { cac } from 'cac'
import chokidar from 'chokidar'
import dotenv from 'dotenv'
import fs from 'fs'
import { blue, cyan, gray, green } from 'kleur/colors'
import { clear, success } from 'misty'
import { MistyTask, startTask } from 'misty/task'
import path from 'path'
import { Client } from 'pg'
import { findDotenvFile } from 'tusken/dotenv'
import { loadConfig } from './config'
import { toConnectionString } from './connectionString'
import { debounce } from './debounce'
import { defer, Deferred } from './defer'
import { dotenv } from './dotenv'
import { firstLine } from './firstline'

export default async function () {
Expand Down Expand Up @@ -248,7 +249,7 @@ export default async function () {

tusken.help()
try {
dotenv()
findDotenvFile(dotenv.config)
tusken.parse(process.argv, { run: false })
await tusken.runMatchedCommand()
} catch (e: any) {
Expand Down
24 changes: 17 additions & 7 deletions packages/tusken-schema/src/typescript/generateSchema.ts
Expand Up @@ -78,8 +78,8 @@ export function generateTypeSchema(
}

const header = [
`import { Database } from '${tuskenId}'`,
`import { Pool } from 'pg'`,
`import { Database } from "${tuskenId}"`,
`import { Pool } from "pg"`,
]
const databaseProps = [
`reserved: [${reservedWords
Expand All @@ -91,7 +91,7 @@ export function generateTypeSchema(
let configArgument: string
if (configPath) {
configPath = path.relative(outDir, configPath).replace(/\.ts$/, '')
header.push(`import config from '${configPath}'`)
header.push(`import config from "${configPath}"`)
configArgument = endent`
{ ...config.connection, ...config.pool }
`
Expand All @@ -108,14 +108,24 @@ export function generateTypeSchema(
: new Pool(${configArgument})
`)

if (isQueryStreamInstalled(outDir)) {
if (isPackageInstalled(outDir, 'pg-query-stream')) {
header.push('import QueryStream from "pg-query-stream"')
databaseProps.push('QueryStream')
}

let dotenvLoader = ''
if (isPackageInstalled(outDir, 'dotenv')) {
header.unshift(
`import dotenv from "dotenv"`,
`import { findDotenvFile } from "${tuskenId}/dotenv"`
)
dotenvLoader = 'process.env.CI || findDotenvFile(dotenv.config)'
dotenvLoader = '\n' + dotenvLoader + '\n'
}

const indexFile = endent`
${header.join('\n')}
${dotenvLoader}
export default new Database({
${databaseProps.join(',\n')},
})
Expand Down Expand Up @@ -166,10 +176,10 @@ function renderColumns(columns: TableColumn[], isType?: boolean) {
})
}

function isQueryStreamInstalled(outDir: string) {
function isPackageInstalled(outDir: string, pkgId: string) {
const indexRequire = Module.createRequire(path.join(outDir, 'index.ts'))
try {
if (indexRequire.resolve('pg-query-stream')) {
if (indexRequire.resolve(pkgId)) {
return true
}
} catch {}
Expand Down
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion src/build.config.ts
@@ -1,7 +1,13 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
entries: ['./tusken', './config', './constants', './postgres/array'],
entries: [
'./tusken',
'./config',
'./constants',
'./dotenv',
'./postgres/array',
],
externals: ['pg', 'callsites'],
declaration: true,
rollup: {
Expand Down
17 changes: 17 additions & 0 deletions src/dotenv.ts
@@ -0,0 +1,17 @@
import escalade from './utils/escalade/sync'

export function findDotenvFile(load: (options: { path: string }) => void) {
const envFiles = [
'.env.tusken',
'.env.' + (process.env.NODE_ENV || 'development'),
'.env',
]

const envFile = escalade(process.cwd(), (_, files) =>
envFiles.find(f => files.includes(f))
)

if (envFile) {
load({ path: envFile })
}
}
5 changes: 5 additions & 0 deletions src/package.json
Expand Up @@ -35,6 +35,11 @@
"import": "./dist/constants.mjs",
"default": "./dist/constants.cjs"
},
"./dotenv": {
"types": "./dist/dotenv.d.ts",
"import": "./dist/dotenv.mjs",
"default": "./dist/dotenv.cjs"
},
"./package.json": "./package.json"
},
"files": [
Expand Down
9 changes: 9 additions & 0 deletions src/utils/escalade/license.md
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 changes: 28 additions & 0 deletions src/utils/escalade/sync.ts
@@ -0,0 +1,28 @@
// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js
import { readdirSync, statSync } from 'fs'
import { dirname, resolve } from 'path'

export type Callback = (
directory: string,
files: string[]
) => string | false | void

export default function (
start: string,
callback: Callback
): string | undefined {
let dir = resolve('.', start)
let tmp,
stats = statSync(dir)

if (!stats.isDirectory()) {
dir = dirname(dir)
}

while (true) {
tmp = callback(dir, readdirSync(dir))
if (tmp) return resolve(dir, tmp)
dir = dirname((tmp = dir))
if (tmp === dir) break
}
}

0 comments on commit 5a58d14

Please sign in to comment.