Skip to content

Commit

Permalink
feat: add cli
Browse files Browse the repository at this point in the history
  • Loading branch information
zyyv committed Feb 18, 2023
1 parent 23a80be commit b726e65
Show file tree
Hide file tree
Showing 20 changed files with 135 additions and 91 deletions.
3 changes: 3 additions & 0 deletions bin/untiny.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import('../dist/cli.mjs')
7 changes: 5 additions & 2 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
entries: [
'src/index',
'./src/index',
'./src/cli',
],
declaration: true,
clean: true,
declaration: true,
rollup: {
emitCJS: true,
inlineDependencies: true,
},
failOnWarn: false,
})
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "tiny-sdk",
"name": "untiny",
"type": "module",
"version": "0.0.0",
"description": "A sdk of tiny tools.",
Expand All @@ -14,8 +14,8 @@
"url": "https://github.com/zyyv/starter-ts/issues"
},
"keywords": [
"sdk",
"tiny",
"untiny",
"tinypng",
"tools"
],
"sideEffects": false,
Expand All @@ -41,7 +41,7 @@
"dist"
],
"scripts": {
"build": "rimraf dist && unbuild",
"build": "unbuild",
"dev": "unbuild --stub",
"prepublishOnly": "pnpm run build",
"release": "bumpp --commit --push --tag && pnpm publish",
Expand All @@ -67,6 +67,7 @@
"rimraf": "^4.1.2",
"typescript": "^4.8.4",
"unbuild": "^1.1.1",
"unconfig": "^0.3.7",
"vite": "^4.1.1",
"vitest": "^0.28.4"
}
Expand Down
14 changes: 14 additions & 0 deletions pnpm-lock.yaml

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

34 changes: 34 additions & 0 deletions src/cli-start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { loadConfig } from 'unconfig'
import { sourcePackageJsonFields } from 'unconfig/presets'
import type { Config } from './types'

export async function getConfig() {
const { config } = await loadConfig<Config>({
sources: [
{
files: 'untiny.config',
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json', ''],
},
sourcePackageJsonFields({
fields: 'untiny',
}),
],
defaults: {
untiny: {
apiKey: '',
},
},
merge: true,
})

return config
}

export async function startCli() {
const { untiny: { apiKey } } = await getConfig()

// eslint-disable-next-line no-console
console.log(apiKey)

// const tinifyIns = new TinifyCompressor(apiKey)
}
3 changes: 3 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { startCli } from './cli-start'

startCli()
2 changes: 0 additions & 2 deletions src/constant.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const API_KEY = 'RWDMNgkQJGldpgBVhn5MJ2944cHxN2CK'

export const IMG_EXT = ['.png', '.jpg', '.jpeg', '.webp']

export const separator = process.platform === 'win32' ? '\\' : '/'
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import consola from 'consola'
import { IMG_EXT, separator } from './constant'
import type { CompressOption } from './types'
import { formatFileName, formatFileSize, isPathValid } from './utils'
import { getConfig } from './cli-start'

export class TinifyCompressor {
private tinifyInstance: typeof tinify

constructor(key: string) {
if (!key)
throw new Error('Please enter your API key')

this.tinifyInstance = this.init(key)
}

Expand Down Expand Up @@ -121,3 +125,8 @@ export class TinifyCompressor {
await this.compressImages(imgFiles, option)
}
}

export async function createTinifyCompressor(key?: string) {
key = key ?? (await getConfig()).untiny.apiKey
return new TinifyCompressor(key)
}
10 changes: 0 additions & 10 deletions src/test.ts

This file was deleted.

10 changes: 10 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,13 @@ export interface CompressOption {
*/
debug?: boolean
}

export interface Config {
untiny: {
/**
* Your API key
* @default ''
*/
apiKey: string
}
}
21 changes: 0 additions & 21 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,6 @@
import path from 'path'
import os from 'os'
import fs from 'fs-extra'
import { IMG_EXT } from './constant'


export async function getImgFiles(dir: string, extnames: string[] = IMG_EXT): Promise<string[]> {
if (!(await isPathValid(dir)))
throw new Error(`Path ${dir} is not valid.`)

const files = await fs.readdir(dir, { withFileTypes: true })
const imgFiles: string[] = []

for (const file of files) {
const filePath = path.join(dir, file.name)
if (file.isDirectory())
imgFiles.push(...await getImgFiles(filePath, extnames))

else if (file.isFile() && extnames.includes(path.extname(filePath)))
imgFiles.push(filePath)
}

return imgFiles
}

export async function isPathValid(filePath: string): Promise<boolean> {
return await fs.pathExists(filePath)
Expand Down
File renamed without changes
File renamed without changes
File renamed without changes.
5 changes: 5 additions & 0 deletions tests/fixtures/configs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"untiny": {
"apiKey": "111"
}
}
5 changes: 5 additions & 0 deletions tests/fixtures/configs/untiny.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
untiny: {
apiKey: '222',
},
}
5 changes: 5 additions & 0 deletions tests/fixtures/configs/untiny.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
untiny: {
apiKey: 'RWDMNgkQJGldpgBVhn5MJ2944cHxN2CK',
},
}
52 changes: 29 additions & 23 deletions test/index.test.ts → tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,11 @@
import path from 'path'
import { describe, expect, test } from 'vitest'
import { loadConfig } from 'unconfig'
import { sourcePackageJsonFields } from 'unconfig/presets'
import { formatFileName, formatFileSize } from '../src/utils'

// const __dirname = path.dirname(new URL(import.meta.url).pathname)
// const assetsDir = path.resolve(__dirname, './assets')
import type { Config } from '../src/types'

describe('Assets Imgs', () => {
// test('getImgFiles', async () => {
// const imgFiles = await getImgFiles(assetsDir)

// expect(imgFiles).toMatchInlineSnapshot(`
// [
// "/Users/chris/projects/fork/tiny-sdk/test/assets/imgs/WechatIMG99.jpeg",
// "/Users/chris/projects/fork/tiny-sdk/test/assets/imgs/avatar.png",
// "/Users/chris/projects/fork/tiny-sdk/test/assets/imgs/test/couple.webp",
// ]
// `)

// const tinifyIns = new TinifyCompressor(API_KEY)

// imgFiles.forEach((imgFile) => {
// tinifyIns.compressImage(imgFile, {
// handler: (_, imgName) => path.resolve(__dirname, `./output/${imgName}`),
// })
// })
// })

test('formatFileSize', () => {
expect(formatFileSize(1024)).toBe('1.00 KB')
expect(formatFileSize(1024 * 1024)).toBe('1.00 MB')
Expand Down Expand Up @@ -81,3 +61,29 @@ describe('Assets Imgs', () => {
`)
})
})

describe('Unconfigured', () => {
test('unconfigured', async () => {
const cwd = path.resolve(__dirname, './fixtures/configs')
const { config } = await loadConfig<Config>({
sources: [
{
files: 'untiny.config',
extensions: ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs', 'json', ''],
},
sourcePackageJsonFields({
fields: 'untiny',
}),
],
cwd,
})

expect(config).toMatchInlineSnapshot(`
{
"untiny": {
"apiKey": "222",
},
}
`)
})
})
27 changes: 8 additions & 19 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,16 @@
{
"compilerOptions": {
"composite": true,
"lib": ["esnext"],
"types": ["node"],
"target": "esnext",
"target": "es2021",
"module": "esnext",
"useDefineForClassFields": true,
"moduleResolution": "node",
"lib": ["es2019"],
"strict": true,
"sourceMap": false,
"allowJs": false,
"esModuleInterop": true,
"moduleResolution": "node",
"skipLibCheck": true,
"noUnusedLocals": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"removeComments": false,
"baseUrl": ".",
"rootDir": ".",
"outDir": "dist",
"paths": {
"@/*": [
"src/*"
]
}
"types": ["node"]
},
"exclude": ["packages/**/__test__", "packages/**/test"]
"include": ["src", "tests", "scripts"],
"exclude": ["tests/fixtures"]
}
10 changes: 0 additions & 10 deletions vitest.config.ts

This file was deleted.

0 comments on commit b726e65

Please sign in to comment.