Skip to content

Instantly share code, notes, and snippets.

@sdk-quadra
Last active June 11, 2020 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdk-quadra/2f56adc364190c806cdff4c06181166c to your computer and use it in GitHub Desktop.
Save sdk-quadra/2f56adc364190c806cdff4c06181166c to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
class CliEntry {
'use strict'
constructor () {
this.argv = require('minimist')(process.argv.slice(2))
}
stdin () {
if (!process.stdin.isTTY) {
process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin.on('data', (text) => {
this.insertRow(text)
})
}
}
selectMemo (rows) {
const cliSelect = require('cli-select')
const chalk = require('chalk')
cliSelect({
values: rows,
selected: '(○)',
unselected: '( )',
valueRenderer: (value, selected) => {
const firstLine = value.split('\\n')[0]
if (selected) {
return chalk.blue(firstLine)
}
return firstLine
}
}).then((response) => {
console.log(response.value.replace(/\\n/g, '\n').replace(/\n$/, ''))
if (this.argv.d) {
this.deleteMemo(response, rows)
}
}).catch(() => {
console.log('キャンセルされました')
})
}
}
class MemoFile extends CliEntry {
'use strict'
constructor () {
super()
this.fs = require('fs')
this.fileName = 'memo.txt'
}
insertRow (text) {
try {
this.fs.appendFileSync(this.fileName, text.replace(/\n/g, '\\n').replace(/\\n$/, '\n'))
} catch (e) {
console.log(e)
}
}
isExistRows () {
try {
var allRows = this.fs.readFileSync(
this.fileName, { encoding: 'utf-8' }).replace(/\n$/, '')
if (allRows.length < 1) {
throw new Error()
}
return allRows
} catch (err) {
console.log('メモがありません')
return false
}
}
readAllRows () {
var allRows = this.isExistRows()
if (!allRows) return false
const rows = allRows.split('\n')
if (this.argv.r || this.argv.d) {
this.selectMemo(rows)
} else {
for (const key of rows) {
console.log(key.split('\\n')[0])
}
}
}
deleteMemo (response, rows) {
const fd = this.fs.openSync(this.fileName, 'w')
for (const [index, row] of rows.entries()) {
if (response.id !== index) {
this.fs.writeSync(fd, row + '\n')
}
}
this.fs.closeSync(fd)
}
runMemo () {
if (this.argv.l || this.argv.r || this.argv.d) {
this.readAllRows()
} else {
this.stdin()
}
}
}
const memo = new MemoFile()
memo.runMemo()
@komagata
Copy link

https://gist.github.com/sdk-quadra/2f56adc364190c806cdff4c06181166c#file-memo_file-js-L5

インデントされてないようです。

https://gist.github.com/sdk-quadra/2f56adc364190c806cdff4c06181166c#file-memo_file-js-L3

Commonだと抽象的すぎてほとんど何も表現してないことになってしまうので具体的な名前と機能を考えてみてください。

@sdk-quadra
Copy link
Author

  • インデントを整理しました。
  • クラス名をCommonからCliEntry(コマンドライン項目)にしました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment