-
-
Save sdk-quadra/2f56adc364190c806cdff4c06181166c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
- インデントを整理しました。
- クラス名をCommonからCliEntry(コマンドライン項目)にしました。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
インデントされてないようです。
Commonだと抽象的すぎてほとんど何も表現してないことになってしまうので具体的な名前と機能を考えてみてください。