Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support --no-output option #69

Merged
merged 6 commits into from
Feb 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@
### Added

- Make the first slide convertible into PNG and JPEG image by `--image` option ([#68](https://github.com/marp-team/marp-cli/pull/68))
- Support `--no-output` option ([#69](https://github.com/marp-team/marp-cli/pull/69))

### Fixed

- Fix wrong MIME type when opening preview of converted file outputted to stdout ([#68](https://github.com/marp-team/marp-cli/pull/68))
- Improved log message when processed Markdown in server mode ([#69](https://github.com/marp-team/marp-cli/pull/69))

## v0.5.0 - 2019-01-31

Expand Down
21 changes: 11 additions & 10 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ interface IMarpCLIBaseArguments {
inputDir?: string
jpegQuality?: number
ogImage?: string
output?: string
output?: string | false
pdf?: boolean
preview?: boolean
server?: boolean
Expand Down Expand Up @@ -91,16 +91,17 @@ export class MarpCLIConfig {

async converterOption(): Promise<ConverterOption> {
const inputDir = await this.inputDir()
const output =
this.args.output ||
(this.conf.output
? (() => {
if (this.conf.output === '-') return '-'
return path.resolve(path.dirname(this.confPath!), this.conf.output)
})()
: undefined)

const server = this.pickDefined(this.args.server, this.conf.server) || false
const output = (() => {
if (server) return false
if (this.args.output !== undefined) return this.args.output
if (this.conf.output !== undefined)
return this.conf.output === '-' || this.conf.output === false
? this.conf.output
: path.resolve(path.dirname(this.confPath!), this.conf.output)

return undefined
})()

const template = this.args.template || this.conf.template || 'bespoke'
const templateOption: TemplateOption = (() => {
Expand Down
63 changes: 29 additions & 34 deletions src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export interface ConverterOption {
inputDir?: string
lang: string
options: MarpitOptions
output?: string
output?: string | false
preview?: boolean
jpegQuality?: number
readyScript?: string
Expand All @@ -44,8 +44,8 @@ export interface ConverterOption {
}

export interface ConvertFileOption {
initial?: boolean
onConverted?: ConvertedCallback
onlyScanning?: boolean
}

export interface ConvertResult {
Expand Down Expand Up @@ -121,48 +121,43 @@ export class Converter {
}

async convertFile(file: File, opts: ConvertFileOption = {}) {
const emit = !(this.options.server && opts.initial)
let result: ConvertResult

try {
silence(!!opts.onlyScanning)

const convert = async (): Promise<ConvertResult> => {
const template = await this.convert((await file.load()).toString(), file)
const newFile = file.convert(this.options.output, this.options.type)
newFile.buffer = Buffer.from(template.result)

return { file, newFile, template }
}

let result: ConvertResult

try {
silence(!emit)
result = await convert()
newFile.buffer = Buffer.from(template.result)
result = { file, newFile, template }
} finally {
silence(false)
}

if (emit) {
switch (this.options.type) {
case ConvertType.pdf:
await this.convertFileToPDF(result.newFile)
break
case ConvertType.png:
await this.convertFileToImage(result.newFile, {
size: result.template.size,
type: 'png',
})
break
case ConvertType.jpeg:
await this.convertFileToImage(result.newFile, {
quality: this.options.jpegQuality,
size: result.template.size,
type: 'jpeg',
})
}

if (!this.options.server) await result.newFile.save()
if (opts.onConverted) opts.onConverted(result)
if (opts.onlyScanning) return result

switch (this.options.type) {
case ConvertType.pdf:
await this.convertFileToPDF(result.newFile)
break
case ConvertType.png:
await this.convertFileToImage(result.newFile, {
size: result.template.size,
type: 'png',
})
break
case ConvertType.jpeg:
await this.convertFileToImage(result.newFile, {
quality: this.options.jpegQuality,
size: result.template.size,
type: 'jpeg',
})
}

await result.newFile.save()
if (opts.onConverted) opts.onConverted(result)

return result
}

Expand Down
22 changes: 13 additions & 9 deletions src/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const markdownExtensions = ['md', 'mdown', 'markdown', 'markdn']
export enum FileType {
File,
StandardIO,
Null,
}

export class File {
Expand All @@ -33,15 +34,18 @@ export class File {
return path.resolve(this.path)
}

convert(output: string | undefined, extension: string): File {
if (output === undefined)
return File.initialize(
this.convertExtension(extension),
f => (f.type = this.type)
)

if (output === '-')
return File.initialize('-', f => (f.type = FileType.StandardIO))
convert(output: string | false | undefined, extension: string): File {
switch (output) {
case undefined:
return File.initialize(
this.convertExtension(extension),
f => (f.type = this.type)
)
case false:
return File.initialize(this.path, f => (f.type = FileType.Null))
case '-':
return File.initialize('-', f => (f.type = FileType.StandardIO))
}

if (this.inputDir)
return File.initialize(
Expand Down
30 changes: 17 additions & 13 deletions src/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,22 +216,28 @@ export default async function(argv: string[] = []): Promise<number> {
return config.files.length > 0 ? 1 : 0
}

if (!cvtOpts.server)
cli.info(`Converting ${length} markdown${length > 1 ? 's' : ''}...`)

// Convert markdown into HTML
const convertedFiles: File[] = []
const onConverted: ConvertedCallback = ret => {
const { file, newFile } = ret
const output = (f: File, io: string) =>
f.type === FileType.StandardIO ? `<${io}>` : f.relativePath()
const { file: i, newFile: o } = ret
const fn = (f: File, stdio: string) =>
f.type === FileType.StandardIO ? stdio : f.relativePath()

convertedFiles.push(newFile)
cli.info(`${output(file, 'stdin')} => ${output(newFile, 'stdout')}`)
convertedFiles.push(o)
cli.info(
`${fn(i, '<stdin>')} ${
o.type === FileType.Null ? 'processed.' : `=> ${fn(o, '<stdout>')}`
}`
)
}

try {
await converter.convertFiles(foundFiles, { onConverted, initial: true })
if (cvtOpts.server) {
await converter.convertFiles(foundFiles, { onlyScanning: true })
} else {
cli.info(`Converting ${length} markdown${length > 1 ? 's' : ''}...`)
await converter.convertFiles(foundFiles, { onConverted })
}
} catch (e) {
error(`Failed converting Markdown. (${e.message})`, e.errorCode)
}
Expand Down Expand Up @@ -281,11 +287,9 @@ export default async function(argv: string[] = []): Promise<number> {
} else {
cli.info(chalk.green('[Watch mode] Start watching...'))

if (cvtOpts.preview) {
for (const file of convertedFiles) {
if (cvtOpts.preview)
for (const file of convertedFiles)
await preview.open(fileToURI(file, cvtOpts.type))
}
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export function fileToURI(file: File, type: ConvertType) {
return encodeURI(`file://${uri.startsWith('/') ? '' : '/'}${uri}`)
}

if (file.type === FileType.StandardIO && file.buffer) {
if (file.buffer) {
// Convert to data scheme URI
return `data:${mimeTypes[type]};base64,${file.buffer.toString('base64')}`
}
Expand Down
1 change: 1 addition & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export class Server {
) {
const file = new File(filename)

this.converter.options.output = false
this.converter.options.type = ((): ConvertType => {
const queryKeys = Object.keys(query)

Expand Down
47 changes: 32 additions & 15 deletions test/cli.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,57 @@
import chalk from 'chalk'
import { error, info, warn } from '../src/cli'
import { error, info, silence, warn } from '../src/cli'

afterEach(() => jest.restoreAllMocks())
afterEach(() => {
jest.restoreAllMocks()
silence(false)
})

describe('CLI helpers', () => {
let spy: jest.SpyInstance

describe('#error', () => {
beforeEach(() => (spy = jest.spyOn(console, 'error').mockImplementation()))

it('passes message with colored header to console.error', () => {
const errSpy = jest.spyOn(console, 'error').mockImplementation()
error('cli-helper')
expect(spy).toBeCalledWith(chalk`{bgRed.white [ ERROR ]} cli-helper`)
})

it('calls console.error even if silenced', () => {
silence(true)
error('cli-helper')
expect(errSpy).toHaveBeenCalledWith(
chalk`{bgRed.white [ ERROR ]} cli-helper`
)
expect(spy).toBeCalled()
})
})

describe('#info', () => {
// Use console.warn to output into stderr
beforeEach(() => (spy = jest.spyOn(console, 'warn').mockImplementation()))

it('passes message with colored header to console.warn', () => {
// Use console.warn to output into stderr
const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
info('cli-helper')
expect(spy).toBeCalledWith(chalk`{bgCyan.black [ INFO ]} cli-helper`)
})

it('does not call console.warn when silenced', () => {
silence(true)
info('cli-helper')
expect(warnSpy).toHaveBeenCalledWith(
chalk`{bgCyan.black [ INFO ]} cli-helper`
)
expect(spy).not.toBeCalled()
})
})

describe('#warn', () => {
beforeEach(() => (spy = jest.spyOn(console, 'warn').mockImplementation()))

it('passes message with colored header to console.warn', () => {
const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
warn('cli-helper')
expect(spy).toBeCalledWith(chalk`{bgYellow.black [ WARN ]} cli-helper`)
})

it('does not call console.warn when silenced', () => {
silence(true)
warn('cli-helper')
expect(warnSpy).toHaveBeenCalledWith(
chalk`{bgYellow.black [ WARN ]} cli-helper`
)
expect(spy).not.toBeCalled()
})
})
})
17 changes: 7 additions & 10 deletions test/marp-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -642,14 +642,13 @@ describe('Marp CLI', () => {
})

it('allows custom engine function specified in js config', async () => {
jest.spyOn(process.stdout, 'write').mockImplementation()
jest.spyOn(console, 'warn').mockImplementation()

const conf = assetFn('_configs/custom-engine/anonymous.js')
const md = assetFn('_configs/custom-engine/md.md')
const { engine } = require(conf)

expect(await marpCli(['-c', conf, md, '-o', '-'])).toBe(0)
expect(await marpCli(['-c', conf, md, '--no-output'])).toBe(0)
expect(engine).toBeCalledWith(
expect.objectContaining({ customOption: true })
)
Expand All @@ -660,13 +659,12 @@ describe('Marp CLI', () => {
context('with --preview / -p option', () => {
let warn: jest.SpyInstance<Console['warn']>

beforeEach(() => {
warn = jest.spyOn(console, 'warn').mockImplementation()
jest.spyOn(process.stdout, 'write').mockImplementation()
})
beforeEach(
() => (warn = jest.spyOn(console, 'warn').mockImplementation())
)

it('opens preview window through Preview.open()', async () => {
await marpCli([onePath, '-p', '-o', '-'])
await marpCli([onePath, '-p', '--no-output'])
expect(Preview.prototype.open).toBeCalledTimes(1)

// Simualte opening event
Expand All @@ -681,7 +679,7 @@ describe('Marp CLI', () => {
afterEach(() => delete process.env.IS_DOCKER)

it('ignores --preview option with warning', async () => {
await marpCli([onePath, '--preview', '-o', '-'])
await marpCli([onePath, '--preview', '--no-output'])
expect(Preview.prototype.open).not.toBeCalled()
expect(warn).toBeCalledWith(
expect.stringContaining('Preview option was ignored')
Expand Down Expand Up @@ -752,9 +750,8 @@ describe('Marp CLI', () => {
context('with --preview option', () => {
it('opens 2 preview windows through Preview.open()', async () => {
jest.spyOn(console, 'warn').mockImplementation()
jest.spyOn(process.stdout, 'write').mockImplementation()

await marpCli([...baseArgs, '--preview', '-o', '-'])
await marpCli([...baseArgs, '--preview', '--no-output'])
expect(Preview.prototype.open).toBeCalledTimes(2)
})
})
Expand Down