Skip to content

Create note with env EDITOR #68

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

Merged
merged 6 commits into from
Apr 28, 2023
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
2 changes: 1 addition & 1 deletion .github/workflows/config-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ jobs:

strategy:
matrix:
node-version: ['12', '14', '16']
node-version: ['18']

steps:
- name: Checkout repository
Expand Down
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
17
18
70 changes: 50 additions & 20 deletions src/commands/notes/create.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import {CommentPermissionType, CreateNoteOptions, NotePermissionRole} from '@hackmd/api/dist/type'
import {
CommentPermissionType,
CreateNoteOptions,
NotePermissionRole,
} from '@hackmd/api/dist/type'
import {CliUx, Flags} from '@oclif/core'
import * as fs from 'fs'

import HackMDCommand from '../../command'
import {commentPermission, noteContent, notePermission, noteTitle} from '../../flags'
import {safeStdinRead} from '../../utils'
import {
commentPermission,
noteContent,
notePermission,
noteTitle,
} from '../../flags'
import openEditor from '../../open-editor'
import {safeStdinRead, temporaryMD} from '../../utils'

export default class Create extends HackMDCommand {
export default class CreateCommand extends HackMDCommand {
static description = 'Create a note'

static examples = [
Expand All @@ -16,7 +27,7 @@ export default class Create extends HackMDCommand {
raUuSTetT5uQbqQfLnz9lA A new note gvfz2UB5THiKABQJQnLs6Q null`,

'Or you can pipe content via Unix pipeline:',
'cat README.md | hackmd-cli notes create'
'cat README.md | hackmd-cli notes create',
]

static flags = {
Expand All @@ -26,40 +37,59 @@ raUuSTetT5uQbqQfLnz9lA A new note gvfz2UB5THiKABQJQnLs6Q
readPermission: notePermission(),
writePermission: notePermission(),
commentPermission: commentPermission(),
editor: Flags.boolean({
char: 'e',
description: 'create note with $EDITOR',
}),
...CliUx.ux.table.flags(),
}

async run() {
const {flags} = await this.parse(Create)
const {flags} = await this.parse(CreateCommand)
const pipeString = safeStdinRead()

const options: CreateNoteOptions = {
title: flags.title,
content: pipeString || flags.content,
readPermission: flags.readPermission as NotePermissionRole,
writePermission: flags.writePermission as NotePermissionRole,
commentPermission: flags.commentPermission as CommentPermissionType
commentPermission: flags.commentPermission as CommentPermissionType,
}

if (flags.editor) {
try {
const mdFile = temporaryMD()
await openEditor(mdFile)

options.content = fs.readFileSync(mdFile).toString()
} catch (e) {
this.error(e as Error)
}
}

try {
const APIClient = await this.getAPIClient()
const note = await APIClient.createNote(options)

CliUx.ux.table([note], {
id: {
header: 'ID',
},
title: {},
userPath: {
header: 'User path'
CliUx.ux.table(
[note],
{
id: {
header: 'ID',
},
title: {},
userPath: {
header: 'User path',
},
teamPath: {
header: 'Team path',
},
},
teamPath: {
header: 'Team path'
{
printLine: this.log.bind(this),
...flags,
}
}, {
printLine: this.log.bind(this),
...flags
})
)
} catch (e) {
this.log('Create note failed')
this.error(e as Error)
Expand Down
43 changes: 43 additions & 0 deletions src/open-editor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {ChildProcess, spawn} from 'child_process'

interface EditorOptions {
editor?: string
}

export function openEditor(
file: string,
opts: EditorOptions = {}
): Promise<void> {
return new Promise((resolve, reject) => {
const editor = getEditor(opts.editor)
const args = editor.split(/\s+/)
const bin = args.shift()

if (!bin) {
reject(new Error('Editor binary not found'))
return
}

const ps: ChildProcess = spawn(bin, [...args, file], {stdio: 'inherit'})

ps.on('exit', () => {
resolve()
})

ps.on('error', (err: Error) => {
reject(err)
})
})
}

function getEditor(editor?: string): string {
return (
editor || process.env.VISUAL || process.env.EDITOR || getDefaultEditor()
)
}

function getDefaultEditor(): string {
return /^win/.test(process.platform) ? 'notepad' : 'vim'
}

export default openEditor
25 changes: 20 additions & 5 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs'
import {homedir} from 'os'
import fs from 'fs-extra'
import {homedir, tmpdir} from 'os'
import * as path from 'path'

export function getConfigFilePath() {
Expand All @@ -10,7 +10,14 @@ export function getConfigFilePath() {
configDir = path.join(homedir(), '.hackmd')
}

return path.join(configDir, 'config.json')
const configPath = path.join(configDir, 'config.json')

if (!fs.existsSync(configDir)) {
fs.ensureFileSync(configPath)
fs.writeFileSync(configPath, JSON.stringify({}))
}

return configPath
}

export function setAccessTokenConfig(token: string) {
Expand All @@ -26,9 +33,17 @@ export function setAccessTokenConfig(token: string) {

export function safeStdinRead() {
let result
const STDIN_FD = 0
try {
result = fs.readFileSync(STDIN_FD).toString()
result = fs.readFileSync(process.stdin.fd).toString()
} catch {}
return result
}

// generate temporary markdown file in /tmp directory
export function temporaryMD() {
const tmpDir = tmpdir()
const filename = `temp_${Math.random().toString(36).substring(2)}.md`
const filePath = path.join(tmpDir, filename)

return filePath
}