Skip to content

Commit

Permalink
feat!: setup oclif with a basic 'init' command
Browse files Browse the repository at this point in the history
  • Loading branch information
EmileRolley committed Sep 30, 2024
1 parent e3bd88f commit f81ac0c
Show file tree
Hide file tree
Showing 9 changed files with 327 additions and 12 deletions.
3 changes: 3 additions & 0 deletions bin/dev.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@echo off

node --loader ts-node/esm --no-warnings=ExperimentalWarning "%~dp0\dev" %*
7 changes: 7 additions & 0 deletions bin/dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env bun
// #!/usr/bin/env -S node --loader ts-node/esm --disable-warning=ExperimentalWarning

// eslint-disable-next-line n/shebang
import { execute } from '@oclif/core'

await execute({ development: true, dir: import.meta.url })
3 changes: 3 additions & 0 deletions bin/run.cmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@echo off

node "%~dp0\run" %*
6 changes: 6 additions & 0 deletions bin/run.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env node

import { execute } from '@oclif/core'

console.log('Running the CLI:', import.meta.url)
await execute({ dir: import.meta.url })
17 changes: 15 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@publicodes/tools",
"version": "1.2.5",
"description": "A set of utility functions to build tools around Publicodes models",
"description": "A CLI tool for Publicodes",
"type": "module",
"main": "dist/index.js",
"scripts": {
Expand Down Expand Up @@ -55,8 +55,14 @@
],
"author": "Emile Rolley <[email protected]>",
"license": "MIT",
"bin": {
"publicodes": "./bin/run.js"
},
"dependencies": {
"@clack/prompts": "^0.7.0",
"@oclif/core": "^4.0.23",
"@types/node": "^18.11.18",
"chalk": "^5.3.0",
"glob": "^10.4.1",
"path": "^0.12.7",
"publicodes": "^1.3.3",
Expand All @@ -79,7 +85,8 @@
"src/index.ts",
"src/optims/index.ts",
"src/compilation/index.ts",
"src/migration/index.ts"
"src/migration/index.ts",
"src/commands"
],
"format": [
"cjs",
Expand All @@ -90,6 +97,12 @@
"clean": true,
"cjsInterop": true
},
"oclif": {
"bin": "publicodes",
"commands": "./dist/commands",
"dirname": "publicodes",
"topicSeparator": ":"
},
"publishConfig": {
"access": "public"
}
Expand Down
83 changes: 83 additions & 0 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { Args, Command, Flags, ux } from '@oclif/core'
import { exec } from 'node:child_process'
import * as p from '@clack/prompts'
import chalk from 'chalk'
import fs from 'fs'
import path from 'path'
import { basePackageJson, getPackageJson, PackageJson } from '../utils/pjson'

export default class Init extends Command {
static override args = {}

static override description = 'initialize a new project'

static override examples = ['<%= command.id %>']

static override flags = {}

public async run(): Promise<void> {
p.intro(chalk.bgHex('#2975d1')(' publicodes init '))

const pjson = getPackageJson()

if (pjson) {
p.log.info(`Updating existing ${chalk.bold('package.json')} file`)
updatePackageJson(pjson)
} else {
p.log.step(`Creating a new ${chalk.bold('package.json')} file`)
const pjson = await askPackageJsonInfo()
updatePackageJson(pjson)
}

p.outro('🚀 publicodes is ready to use!')
}
}

function updatePackageJson(pjson: PackageJson): void {
const packageJsonPath = path.join(process.cwd(), 'package.json')
const fullPjson = { ...basePackageJson, ...pjson }
try {
fs.writeFileSync(packageJsonPath, JSON.stringify(fullPjson, null, 2))
p.log.success(`${chalk.bold('package.json')} file written`)
} catch (error) {
p.cancel(
`An error occurred while writing the ${chalk.magenta('package.json')} file`,
)
process.exit(1)
}
}

function askPackageJsonInfo(): Promise<PackageJson> {
const currentDir = path.basename(process.cwd())

return p.group(
{
name: () =>
p.text({
message: 'Name',
defaultValue: currentDir,
placeholder: currentDir,
}),
description: () => p.text({ message: 'Description', defaultValue: '' }),
version: () =>
p.text({
message: 'Version',
defaultValue: '1.0.0',
placeholder: '1.0.0',
}),
author: () => p.text({ message: 'Author', defaultValue: '' }),
license: () =>
p.text({
message: 'License',
defaultValue: 'MIT',
placeholder: 'MIT',
}),
},
{
onCancel: () => {
p.cancel('init cancelled')
process.exit(1)
},
},
)
}
47 changes: 47 additions & 0 deletions src/utils/pjson.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import fs from 'fs'

export type PackageJson = {
name: string
version: string
description: string
main?: string
type?: string
types?: string
files?: string[]
repository?: {
url: string
type: string
}
author: string
license: string
scripts?: {
[key: string]: string
}
peerDependencies?: {
[key: string]: string
}
}

export const basePackageJson: PackageJson = {
name: '',
version: '1.0.0',
description: '',
author: '',
type: 'module',
main: 'dist/index.js',
types: 'dist/index.d.ts',
license: 'MIT',
files: ['dist'],
peerDependencies: {
// TODO: how to get the latest version of publicodes?
publicodes: '^1.5.1',
},
}

export function getPackageJson(): PackageJson | undefined {
try {
return JSON.parse(fs.readFileSync('package.json', 'utf8'))
} catch (error) {
return undefined
}
}
7 changes: 5 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true
},
"include": ["src"],
"exclude": ["./node_modules/", "./dist/", "./jest.config.js", "./test/"]
"include": ["src/**/*"],
"exclude": ["./node_modules/", "./dist/", "./jest.config.js", "./test/"],
"ts-node": {
"esm": true
}
}
Loading

0 comments on commit f81ac0c

Please sign in to comment.