├── .npmrc ├── bin └── cli.js ├── media ├── logo.png ├── logo.sketch └── screenshot.png ├── .prettierrc ├── src ├── package.ts ├── questions │ ├── index.ts │ ├── __tests__ │ │ ├── index.spec.ts │ │ ├── getSourceQuestion.spec.ts │ │ ├── getTitleQuestion.spec.ts │ │ └── searchSource.spec.ts │ ├── getSourceQuestion.ts │ ├── getTitleQuestion.ts │ └── searchSources.ts ├── utils │ ├── __tests__ │ │ ├── __snapshots__ │ │ │ └── checkSource.spec.ts.snap │ │ ├── checkSource.spec.ts │ │ ├── checkForUpdates.spec.ts │ │ ├── handleProcess.spec.ts │ │ └── log.spec.ts │ ├── checkSource.ts │ ├── handleEscKeypress.ts │ ├── log.ts │ ├── checkForUpdates.ts │ └── handleProcess.ts ├── cli.ts ├── opml.ts ├── __tests__ │ ├── help.spec.ts │ ├── __snapshots__ │ │ └── opml.spec.ts.snap │ ├── opml.spec.ts │ ├── readNews.spec.ts │ └── main.spec.ts ├── sources.opml ├── help.ts ├── main.ts └── readNews.ts ├── .travis.yml ├── jest.config.js ├── .editorconfig ├── .gitignore ├── tsconfig.json ├── LICENSE ├── .eslintrc ├── README.md └── package.json /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /bin/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require('../lib/cli'); 4 | -------------------------------------------------------------------------------- /media/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kpman/newsroom/HEAD/media/logo.png -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "es5" 4 | } 5 | -------------------------------------------------------------------------------- /media/logo.sketch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kpman/newsroom/HEAD/media/logo.sketch -------------------------------------------------------------------------------- /src/package.ts: -------------------------------------------------------------------------------- 1 | const pkg = require('../package.json'); 2 | 3 | export default pkg; 4 | -------------------------------------------------------------------------------- /media/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kpman/newsroom/HEAD/media/screenshot.png -------------------------------------------------------------------------------- /src/questions/index.ts: -------------------------------------------------------------------------------- 1 | import getSourceQuestion from './getSourceQuestion'; 2 | import getTitleQuestion from './getTitleQuestion'; 3 | 4 | export { getSourceQuestion, getTitleQuestion }; 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "9" 4 | - "6" 5 | cache: 6 | yarn: true 7 | directories: 8 | - "node_modules" 9 | notifications: 10 | email: 11 | on_success: never 12 | -------------------------------------------------------------------------------- /src/utils/__tests__/__snapshots__/checkSource.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`#checkSource should throw error 1`] = `"The source \`fb\` is not in the sources(.opml)!"`; 4 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | testMatch: ['/src/**/*.spec.ts'], 5 | collectCoverageFrom: ['src/**/*.ts'], 6 | coverageDirectory: './coverage/', 7 | }; 8 | -------------------------------------------------------------------------------- /src/questions/__tests__/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { getSourceQuestion, getTitleQuestion } from '..'; 2 | 3 | it('should export questions', () => { 4 | expect(getSourceQuestion).toBeDefined(); 5 | expect(getTitleQuestion).toBeDefined(); 6 | }); 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | indent_size = 2 10 | 11 | [*.md] 12 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /src/questions/getSourceQuestion.ts: -------------------------------------------------------------------------------- 1 | import searchSources from './searchSources'; 2 | 3 | export default (sources) => ({ 4 | type: 'autocomplete', 5 | name: 'source', 6 | message: 'Please choose a source:', 7 | source: searchSources(sources), 8 | }); 9 | -------------------------------------------------------------------------------- /src/questions/getTitleQuestion.ts: -------------------------------------------------------------------------------- 1 | export default (titles, pageSize = 5) => ({ 2 | type: 'checkbox', 3 | name: 'title', 4 | message: 'Please choose which title you want to open', 5 | choices: titles, 6 | filter: (val) => val, 7 | pageSize, 8 | }); 9 | -------------------------------------------------------------------------------- /src/utils/checkSource.ts: -------------------------------------------------------------------------------- 1 | import invariant from 'invariant'; 2 | 3 | export default (source, sourcesInfo) => { 4 | const result = sourcesInfo.some((sourceInfo) => sourceInfo.title === source); 5 | invariant(result, `The source \`${source}\` is not in the sources(.opml)!`); 6 | }; 7 | -------------------------------------------------------------------------------- /src/utils/handleEscKeypress.ts: -------------------------------------------------------------------------------- 1 | const handleEscKeypress = () => { 2 | process.stdin.setEncoding('utf8'); 3 | process.stdin.on('data', (chunk) => { 4 | if (chunk.toString() === '\u001b') { 5 | // ESC 6 | process.exit(0); 7 | } 8 | }); 9 | }; 10 | 11 | export default handleEscKeypress; 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependency 2 | node_modules 3 | package-lock.json 4 | 5 | # files 6 | .DS_Store 7 | .env 8 | 9 | # logs 10 | logs 11 | *.log 12 | npm-debug.log* 13 | yarn-debug.log* 14 | yarn-error.log* 15 | 16 | # test 17 | coverage 18 | junit.xml 19 | jest-report 20 | 21 | # build 22 | lib 23 | dist 24 | packed 25 | -------------------------------------------------------------------------------- /src/questions/searchSources.ts: -------------------------------------------------------------------------------- 1 | import fuzzy from 'fuzzy'; 2 | 3 | const searchSources = (sources) => (answers?: any, _input?: any) => { 4 | const input = _input || ''; 5 | return new Promise((resolve) => { 6 | const fuzzyResult = fuzzy.filter(input, sources); 7 | resolve(fuzzyResult.map((el) => el.original)); 8 | }); 9 | }; 10 | 11 | export default searchSources; 12 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import minimist from 'minimist'; 2 | 3 | import main from './main'; 4 | import { error } from './utils/log'; 5 | import handleEscKeypress from './utils/handleEscKeypress'; 6 | 7 | handleEscKeypress(); 8 | 9 | main(minimist(process.argv.slice(2))) 10 | .then(() => { 11 | process.exit(0); 12 | }) 13 | .catch((e) => { 14 | error(e); 15 | process.exit(1); 16 | }); 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2015", 4 | "lib": ["ES2022"], 5 | "module": "CommonJS", 6 | "allowJs": true, 7 | "checkJs": true, 8 | "esModuleInterop": true, 9 | "outDir": "lib", 10 | "noEmitOnError": false, 11 | "strict": false, 12 | "resolveJsonModule": true, 13 | "rootDir": "src" 14 | }, 15 | "include": ["src"], 16 | "exclude": ["node_modules"] 17 | } 18 | -------------------------------------------------------------------------------- /src/questions/__tests__/getSourceQuestion.spec.ts: -------------------------------------------------------------------------------- 1 | import getSourceQuestion from '../getSourceQuestion'; 2 | 3 | it('be defined', () => { 4 | expect(getSourceQuestion).toBeDefined(); 5 | }); 6 | 7 | describe('#getSourceQuestion', () => { 8 | it('should return a autocomplete type question', () => { 9 | const sources = []; 10 | const q = getSourceQuestion(sources); 11 | expect(q.type).toBe('autocomplete'); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/utils/log.ts: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk'; 2 | import figures from 'figures'; 3 | 4 | const log = (msg, { color = 'blue', icon = 'pointer' } = {}) => { 5 | console.log(`${chalk[color](figures[icon])} ${msg}`); 6 | }; 7 | 8 | const print = (msg) => log(msg, { color: 'green' }); 9 | 10 | const warn = (msg) => log(msg, { color: 'yellow', icon: 'warning' }); 11 | 12 | const error = (msg) => log(msg, { color: 'red', icon: 'cross' }); 13 | 14 | export { log, print, warn, error }; 15 | -------------------------------------------------------------------------------- /src/utils/checkForUpdates.ts: -------------------------------------------------------------------------------- 1 | import updateNotifier from 'update-notifier'; 2 | import chalk from 'chalk'; 3 | 4 | import pkg from '../package'; 5 | 6 | export default () => { 7 | const notifier = updateNotifier({ pkg }); 8 | const { update } = notifier; 9 | 10 | if (!update) { 11 | return; 12 | } 13 | 14 | let message = `Update available! ${chalk.red(update.current)} → ${chalk.green( 15 | update.latest 16 | )} \n`; 17 | 18 | message += `Run ${chalk.magenta('npm i -g newsroom-cli')} to update!`; 19 | 20 | notifier.notify({ message, defer: false }); 21 | }; 22 | -------------------------------------------------------------------------------- /src/utils/handleProcess.ts: -------------------------------------------------------------------------------- 1 | import { error } from './log'; 2 | 3 | const handleUnexpected = (err) => { 4 | error(`An unexpected error occurred!\n ${err.stack}`); 5 | process.exit(1); 6 | }; 7 | 8 | const handleRejection = (err?: any) => { 9 | if (err) { 10 | if (err instanceof Error) { 11 | handleUnexpected(err); 12 | } else { 13 | error(`An unexpected rejection occurred\n ${err}`); 14 | } 15 | } else { 16 | error('An unexpected empty rejection occurred'); 17 | } 18 | 19 | return process.exit(1); 20 | }; 21 | 22 | export { handleUnexpected, handleRejection }; 23 | -------------------------------------------------------------------------------- /src/opml.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | 4 | import thenify from 'thenify'; 5 | const parseOpml = thenify(require('node-opml-parser')); 6 | 7 | export default async (opmlPath?: any) => { 8 | let filePath; 9 | 10 | if (opmlPath) { 11 | if (fs.existsSync(opmlPath)) { 12 | filePath = opmlPath; 13 | } else { 14 | filePath = path.join(process.cwd(), opmlPath); 15 | } 16 | } else { 17 | // default sources 18 | filePath = path.join(__dirname, './sources.opml'); 19 | } 20 | 21 | const opmlFile = fs.readFileSync(filePath); 22 | const result = await parseOpml(opmlFile.toString()); 23 | 24 | return result; 25 | }; 26 | -------------------------------------------------------------------------------- /src/__tests__/help.spec.ts: -------------------------------------------------------------------------------- 1 | import help from '../help'; 2 | 3 | jest.mock('../opml'); 4 | 5 | let parseOpml; 6 | const consoleLog = console.log; 7 | 8 | beforeEach(async () => { 9 | parseOpml = (await import('../opml')).default; 10 | console.log = jest.fn(); 11 | }); 12 | 13 | afterEach(() => { 14 | console.log = consoleLog; 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(help).toBeDefined(); 19 | }); 20 | 21 | describe('#help', () => { 22 | it('should call console.log', async () => { 23 | const sources = [{ title: 'hackernews' }]; 24 | parseOpml.mockReturnValue(Promise.resolve(sources)); 25 | 26 | await help(); 27 | 28 | expect(console.log).toBeCalled(); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /src/utils/__tests__/checkSource.spec.ts: -------------------------------------------------------------------------------- 1 | import checkSource from '../checkSource'; 2 | 3 | it('should be defined', () => { 4 | expect(checkSource).toBeDefined(); 5 | }); 6 | 7 | describe('#checkSource', () => { 8 | it('should check the source in the sources', () => { 9 | const source = 'fb'; 10 | const sources = [ 11 | { 12 | title: 'fb', 13 | }, 14 | ]; 15 | expect(() => checkSource(source, sources)).not.toThrow(); 16 | }); 17 | 18 | it('should throw error', () => { 19 | const source = 'fb'; 20 | const sources = [ 21 | { 22 | title: 'snap', 23 | }, 24 | ]; 25 | expect(() => checkSource(source, sources)).toThrowErrorMatchingSnapshot(); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/opml.spec.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`#opml should parse correctly 1`] = `[]`; 4 | 5 | exports[`#opml should parse correctly with array 1`] = ` 6 | [ 7 | { 8 | "feedType": undefined, 9 | "feedUrl": "http://www.theverge.com/rss/index.xml", 10 | "title": undefined, 11 | "url": undefined, 12 | }, 13 | { 14 | "feedType": undefined, 15 | "feedUrl": "https://techcrunch.com/feed/", 16 | "title": undefined, 17 | "url": undefined, 18 | }, 19 | { 20 | "feedType": undefined, 21 | "feedUrl": "http://feeds.mashable.com/Mashable", 22 | "title": undefined, 23 | "url": undefined, 24 | }, 25 | { 26 | "feedType": undefined, 27 | "feedUrl": "http://www.engadget.com/rss.xml", 28 | "title": undefined, 29 | "url": undefined, 30 | }, 31 | ] 32 | `; 33 | -------------------------------------------------------------------------------- /src/sources.opml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Newsroom-cli default sources 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/questions/__tests__/getTitleQuestion.spec.ts: -------------------------------------------------------------------------------- 1 | import getTitleQuestion from '../getTitleQuestion'; 2 | 3 | it('should be defined', () => { 4 | expect(getTitleQuestion).toBeDefined(); 5 | }); 6 | 7 | describe('#getTitleQuestion', () => { 8 | it('should return a list type question', () => { 9 | const titles = []; 10 | const q = getTitleQuestion(titles); 11 | expect(q.type).toBe('checkbox'); 12 | }); 13 | 14 | it('should return a question object with name `title`', () => { 15 | const titles = []; 16 | const q = getTitleQuestion(titles); 17 | expect(q.name).toBe('title'); 18 | }); 19 | 20 | it('should return a object with choices passin', () => { 21 | const titles = ['cool', 'awesome']; 22 | const q = getTitleQuestion(titles); 23 | expect(q.choices).toEqual(['cool', 'awesome']); 24 | }); 25 | 26 | it('filter function will return parameter', () => { 27 | const titles = ['cool', 'awesome']; 28 | const q = getTitleQuestion(titles); 29 | expect(q.filter('yayaya')).toEqual('yayaya'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /src/questions/__tests__/searchSource.spec.ts: -------------------------------------------------------------------------------- 1 | import searchSource from '../searchSources'; 2 | 3 | it('should be defined', () => { 4 | expect(searchSource).toBeDefined(); 5 | }); 6 | 7 | describe('#searchSource', () => { 8 | it('should be a curry function', () => { 9 | const sources = []; 10 | const func = searchSource(sources); 11 | expect(func).toBeInstanceOf(Function); 12 | }); 13 | 14 | it('should return empty array', async () => { 15 | const sources = []; 16 | const func = searchSource(sources); 17 | const result = await func(); 18 | expect(result).toEqual([]); 19 | }); 20 | 21 | it('should return empty array', async () => { 22 | const sources = ['hackernews']; 23 | const func = searchSource(sources); 24 | const result = await func(undefined, 'reddit'); 25 | expect(result).toEqual([]); 26 | }); 27 | 28 | it('should return match array', async () => { 29 | const sources = ['hackernews', 'techcrunch']; 30 | const func = searchSource(sources); 31 | const result = await func(undefined, 'tech'); 32 | expect(result).toEqual(['techcrunch']); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Daniel Tseng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "node": true, 4 | "jest": true 5 | }, 6 | "extends": [ 7 | "eslint:recommended", 8 | "plugin:@typescript-eslint/recommended", 9 | "prettier" 10 | ], 11 | "parser": "@typescript-eslint/parser", 12 | "plugins": ["@typescript-eslint", "import", "prettier"], 13 | "rules": { 14 | "arrow-parens": "off", 15 | "consistent-return": "off", 16 | "global-require": "off", 17 | "prefer-destructuring": "off", 18 | 19 | "no-underscore-dangle": "off", 20 | "no-loop-func": "off", 21 | 22 | "prettier/prettier": "warn", 23 | 24 | "import/order": [ 25 | "error", 26 | { 27 | "groups": [ 28 | "builtin", 29 | "external", 30 | "internal", 31 | "parent", 32 | "sibling", 33 | "index" 34 | ], 35 | "newlines-between": "always" 36 | } 37 | ], 38 | 39 | // remove this rule after migrate to import statement for all files 40 | "@typescript-eslint/no-var-requires": "off" 41 | }, 42 | "settings": { 43 | "import/resolver": { 44 | "typescript": {} 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/help.ts: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk'; 2 | 3 | import parseOpml from './opml'; 4 | 5 | export default async () => { 6 | const sources = await parseOpml(); 7 | const sourcesTitle = sources.map((s) => s.title); 8 | 9 | console.log(` 10 | ${chalk.cyan('$ newsroom')} 11 | 12 | Enter an interactive mode to choose your source. 13 | 14 | ${chalk.cyan('$ newsroom ')} 15 | 16 | ${chalk.dim('Source:')} 17 | 18 | Choose one of the following source: 19 | ${sourcesTitle.join(', ')} 20 | 21 | ${chalk.dim('Number:')} 22 | 23 | The amount you want to see at a time. The default is 5. 24 | 25 | ${chalk.dim('Options:')} 26 | 27 | -o The path of your own OPML file. More about OPML format -> http://dev.opml.org/ 28 | 29 | ${chalk.dim('Examples:')} 30 | 31 | ${chalk.dim('-')} Get hackernews 32 | 33 | ${chalk.cyan('$ newsroom hackernews')} 34 | 35 | ${chalk.dim('-')} Get 10 latest TechCrunch news 36 | 37 | ${chalk.cyan('$ newsroom techcrunch 10')} 38 | 39 | ${chalk.dim('-')} Use my own OPML file 40 | 41 | ${chalk.cyan('$ newsroom -o ./my-awesome-list.opml')} 42 | `); 43 | }; 44 | -------------------------------------------------------------------------------- /src/utils/__tests__/checkForUpdates.spec.ts: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk'; 2 | 3 | import checkForUpdates from '../checkForUpdates'; 4 | 5 | let updateNotifier; 6 | 7 | jest.mock('update-notifier'); 8 | 9 | beforeEach(() => { 10 | updateNotifier = require('update-notifier'); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(checkForUpdates).toBeDefined(); 15 | }); 16 | 17 | describe('#checkForUpdates', () => { 18 | it('should return when no need to update', () => { 19 | const mockNotifier = jest.fn(); 20 | updateNotifier.mockReturnValue({ 21 | update: undefined, 22 | notifier: mockNotifier, 23 | }); 24 | checkForUpdates(); 25 | expect(mockNotifier).not.toBeCalled(); 26 | }); 27 | 28 | it('should call #notify when need to update', () => { 29 | const mockNotify = jest.fn(); 30 | updateNotifier.mockReturnValue({ 31 | update: { 32 | latest: '1.0.1', 33 | current: '1.0.0', 34 | type: 'patch', 35 | name: 'pageres', 36 | }, 37 | notify: mockNotify, 38 | }); 39 | checkForUpdates(); 40 | expect(mockNotify).toBeCalledWith({ 41 | message: `Update available! ${chalk.red('1.0.0')} → ${chalk.green( 42 | '1.0.1' 43 | )} \nRun ${chalk.magenta('npm i -g newsroom-cli')} to update!`, 44 | defer: false, 45 | }); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import inquirer from 'inquirer'; 2 | 3 | import pkg from './package'; 4 | import checkForUpdates from './utils/checkForUpdates'; 5 | import checkSource from './utils/checkSource'; 6 | import { getSourceQuestion } from './questions'; 7 | import help from './help'; 8 | import getSourcesInfo from './opml'; 9 | import readNews from './readNews'; 10 | 11 | const main = async (argv) => { 12 | checkForUpdates(); 13 | 14 | if (argv.v || argv.version || argv._[0] === 'version') { 15 | console.log(pkg.version); 16 | return process.exit(0); 17 | } 18 | 19 | if (argv.h || argv.help || argv._[0] === 'help') { 20 | await help(); 21 | return process.exit(0); 22 | } 23 | 24 | const sourcePath = argv.o; 25 | const sourcesInfo = await getSourcesInfo(sourcePath); 26 | 27 | let source; 28 | let pageSize; 29 | let loop = true; 30 | 31 | while (loop) { 32 | if (argv._[0]) { 33 | [source, pageSize] = argv._; 34 | } else { 35 | inquirer.registerPrompt( 36 | 'autocomplete', 37 | require('inquirer-autocomplete-prompt') 38 | ); 39 | 40 | const sourcesTitle = sourcesInfo.map((sourceInfo) => sourceInfo.title); 41 | const answer = await inquirer.prompt([getSourceQuestion(sourcesTitle)]); 42 | source = answer.source; 43 | } 44 | 45 | checkSource(source, sourcesInfo); 46 | 47 | const targetSourceInfo = sourcesInfo.find( 48 | (sourceInfo) => sourceInfo.title === source 49 | ); 50 | 51 | loop = await readNews(targetSourceInfo, pageSize); 52 | } 53 | }; 54 | 55 | export default main; 56 | -------------------------------------------------------------------------------- /src/utils/__tests__/handleProcess.spec.ts: -------------------------------------------------------------------------------- 1 | import { handleUnexpected, handleRejection } from '../handleProcess'; 2 | 3 | jest.mock('../log'); 4 | const processExit = process.exit; 5 | let error; 6 | 7 | beforeEach(() => { 8 | error = require('../log').error; 9 | 10 | process.exit = jest.fn() as any; 11 | }); 12 | 13 | afterEach(() => { 14 | process.exit = processExit; 15 | }); 16 | 17 | it('should be defined', () => { 18 | expect(handleUnexpected).toBeDefined(); 19 | expect(handleRejection).toBeDefined(); 20 | }); 21 | 22 | describe('#handleUnexpected', () => { 23 | it('should call error and exit', () => { 24 | const err = new Error('gg'); 25 | handleUnexpected(err); 26 | expect(process.exit).toBeCalledWith(1); 27 | expect(error).toBeCalledWith( 28 | `An unexpected error occurred!\n ${err.stack}` 29 | ); 30 | }); 31 | }); 32 | 33 | describe('#handleRejection', () => { 34 | it('should call handleUnexpected when error is an Error type', () => { 35 | const err = new Error('G.G'); 36 | handleRejection(err); 37 | expect(process.exit).toBeCalledWith(1); 38 | }); 39 | 40 | it('should call error when error is NOT an Error type', () => { 41 | const err = 'G.G'; 42 | handleRejection(err); 43 | expect(error).toBeCalledWith(`An unexpected rejection occurred\n G.G`); 44 | expect(process.exit).toBeCalledWith(1); 45 | }); 46 | 47 | it('should call error when error is NOT defined', () => { 48 | handleRejection(); 49 | expect(error).toBeCalledWith(`An unexpected empty rejection occurred`); 50 | expect(process.exit).toBeCalledWith(1); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

3 |
4 | newsroom 5 |
6 |
7 |

8 | 9 | > 💻 A modern CLI to get your favorite news. 📰 10 | 11 | [![npm version](https://img.shields.io/npm/v/newsroom-cli.svg?style=flat)](https://www.npmjs.com/package/newsroom-cli) [![Build Status](https://img.shields.io/travis/kpman/newsroom.svg?branch=master)](https://travis-ci.org/kpman/newsroom) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing) 12 | 13 | ## Install 14 | 15 | ```shell 16 | npm install -g newsroom-cli 17 | ``` 18 | 19 | The CLI will register `newsroom` and `nr` in your shell. 20 | 21 | ## Usage 22 | 23 | ```shell 24 | $ newsroom 25 | ``` 26 | 27 | ![](https://user-images.githubusercontent.com/2382594/33028798-c8a6fb7c-ce51-11e7-98ae-671c1136bbcf.gif) 28 | 29 | or with your own awesome [OPML](http://dev.opml.org/) file 30 | 31 | ```shell 32 | $ newsroom -o 33 | ``` 34 | 35 | ![](https://user-images.githubusercontent.com/2382594/32977243-606733d6-cc64-11e7-8f2e-8df4058bbdc8.gif) 36 | 37 | You will enter a interactive command line interface. 38 | Type the source you want to receive and press enter. 39 | 40 | 41 | 42 | ```shell 43 | $ newsroom [source] [number] 44 | ``` 45 | 46 | You can see the latest news from source. 47 | 48 | screenshot 49 | 50 | ## Help 51 | 52 | ```shell 53 | $ newsroom --help 54 | ``` 55 | 56 | ## Contributing 57 | 58 | ### Make the change 59 | 60 | - Modify the source code in `src` folder. 61 | - Run `npm run test` from the project root. Make sure it pass the check. 62 | 63 | ### Push it 64 | 65 | - Make a Pull-request directly on `master` branch 66 | 67 | ## Related Repos 68 | 69 | - [haxor-news](https://github.com/donnemartin/haxor-news) 70 | 71 | ## Maintainers 72 | 73 | - [Daniel Tseng](https://github.com/kpman) 74 | - Waiting for you 🤘 75 | 76 | ## License 77 | 78 | MIT 79 | -------------------------------------------------------------------------------- /src/utils/__tests__/log.spec.ts: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk'; 2 | import figures from 'figures'; 3 | 4 | import { log, print, warn, error } from '../log'; 5 | 6 | const consoleLog = console.log; 7 | 8 | beforeEach(() => { 9 | console.log = jest.fn(); 10 | }); 11 | 12 | afterEach(() => { 13 | console.log = consoleLog; 14 | }); 15 | 16 | it('should be defined', () => { 17 | expect(log).toBeDefined(); 18 | expect(print).toBeDefined(); 19 | expect(warn).toBeDefined(); 20 | expect(error).toBeDefined(); 21 | }); 22 | 23 | describe('#log', () => { 24 | it('should call console.log with default color blue & icon pointer', () => { 25 | log('hi'); 26 | expect(console.log).toBeCalledWith(`${chalk.blue(figures.pointer)} hi`); 27 | }); 28 | 29 | it('should call console.log with custom color', () => { 30 | log('hi', { color: 'red' }); 31 | expect(console.log).toBeCalledWith(`${chalk.red(figures.pointer)} hi`); 32 | }); 33 | 34 | it('should call console.log with custom icon', () => { 35 | log('hi', { icon: 'cross' }); 36 | expect(console.log).toBeCalledWith(`${chalk.blue(figures.cross)} hi`); 37 | }); 38 | 39 | it('should call console.log with custom color & icon', () => { 40 | log('hi', { color: 'red', icon: 'warning' }); 41 | expect(console.log).toBeCalledWith(`${chalk.red(figures.warning)} hi`); 42 | }); 43 | }); 44 | 45 | describe('#print', () => { 46 | it('should call console.log with green color and default icon as `pointer`', () => { 47 | print('I am Van Gogh'); 48 | expect(console.log).toBeCalledWith( 49 | `${chalk.green(figures.pointer)} I am Van Gogh` 50 | ); 51 | }); 52 | }); 53 | 54 | describe('#warn', () => { 55 | it('should call console.log with yellow color and icon as `warning`', () => { 56 | warn('I want to play a game'); 57 | expect(console.log).toBeCalledWith( 58 | `${chalk.yellow(figures.warning)} I want to play a game` 59 | ); 60 | }); 61 | }); 62 | 63 | describe('#error', () => { 64 | it('should call console.log with red color and icon as `cross`', () => { 65 | error('trick or treat'); 66 | expect(console.log).toBeCalledWith( 67 | `${chalk.red(figures.cross)} trick or treat` 68 | ); 69 | }); 70 | }); 71 | -------------------------------------------------------------------------------- /src/__tests__/opml.spec.ts: -------------------------------------------------------------------------------- 1 | import path from 'path'; 2 | 3 | import opml from '../opml'; 4 | 5 | jest.mock('fs'); 6 | 7 | let fs; 8 | 9 | beforeEach(() => { 10 | fs = require('fs'); 11 | fs.readFileSync = jest.fn(); 12 | fs.readFileSync.mockReturnValue({ toString: () => '' }); 13 | fs.existsSync = jest.fn(); 14 | }); 15 | 16 | it('should be defined', () => { 17 | expect(opml).toBeDefined(); 18 | }); 19 | 20 | describe('#opml', () => { 21 | it('should use absolute file path when file exists', async () => { 22 | fs.existsSync.mockReturnValue(true); 23 | const opmlpath = '/User/awesome.opml'; 24 | await opml(opmlpath); 25 | expect(fs.readFileSync).toBeCalledWith('/User/awesome.opml'); 26 | }); 27 | 28 | it('should use relative file path', async () => { 29 | fs.existsSync.mockReturnValue(false); 30 | process.cwd = jest.fn(() => '/testonly'); 31 | const opmlpath = './awesome.opml'; 32 | await opml(opmlpath); 33 | expect(fs.readFileSync).toBeCalledWith('/testonly/awesome.opml'); 34 | }); 35 | 36 | it('should use default file path', async () => { 37 | fs.existsSync.mockReturnValue(false); 38 | const opmlpath = undefined; 39 | await opml(opmlpath); 40 | expect(fs.readFileSync).toBeCalledWith( 41 | path.join(__dirname, '..', './sources.opml') 42 | ); 43 | }); 44 | 45 | it('should parse correctly', async () => { 46 | const opmlpath = 'awesome.opml'; 47 | const result = await opml(opmlpath); 48 | expect(result).toMatchSnapshot(); 49 | }); 50 | 51 | it('should parse correctly with array', async () => { 52 | const opmlpath = 'awesome.opml'; 53 | fs.readFileSync.mockReturnValue({ 54 | toString: () => ` 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | `, 65 | }); 66 | const result = await opml(opmlpath); 67 | expect(result).toMatchSnapshot(); 68 | }); 69 | }); 70 | -------------------------------------------------------------------------------- /src/readNews.ts: -------------------------------------------------------------------------------- 1 | import thenify from 'thenify'; 2 | import open from 'open'; 3 | import inquirer from 'inquirer'; 4 | const feed = thenify(require('feed-read-parser')); 5 | import cheerio from 'cheerio'; 6 | import ora from 'ora'; 7 | 8 | import { getTitleQuestion } from './questions'; 9 | 10 | const getCommonPrefixIndex = (articles, maxCommonPrefixLength = 80) => { 11 | const commonPrefixIndex = articles.reduce((prefixIndex, article, idx) => { 12 | if (idx !== 0) { 13 | const currentStr = article.title; 14 | const prevStr = articles[idx - 1].title; 15 | for (let j = 0; j < prefixIndex; j += 1) { 16 | if (prevStr[j] !== currentStr[j]) { 17 | return j; 18 | } 19 | } 20 | } 21 | return prefixIndex; 22 | }, maxCommonPrefixLength); 23 | 24 | return commonPrefixIndex; 25 | }; 26 | 27 | export default async (sourceInfo, pageSize = 10) => { 28 | const spinner = ora( 29 | `Trying to fetch the ${sourceInfo.title}'s latest news...` 30 | ).start(); 31 | 32 | const articles = (await feed(sourceInfo.feedUrl)).slice(0, pageSize); 33 | 34 | const commonPrefixIndex = getCommonPrefixIndex(articles); 35 | 36 | // { 37 | // title1: url1, 38 | // title2: url2, 39 | // } 40 | let articleMap = {}; 41 | 42 | articles.forEach((article) => { 43 | const { title, link } = article; 44 | articleMap[title.slice(commonPrefixIndex)] = link; 45 | }); 46 | 47 | spinner.succeed(); 48 | 49 | let titleAnswer = await inquirer.prompt([ 50 | getTitleQuestion(Object.keys(articleMap), pageSize), 51 | ]); 52 | 53 | // check the feed is made by https://curated.co 54 | const isCuratedCo = /issues\.rss/.test(sourceInfo.feedUrl); 55 | if (isCuratedCo) { 56 | articleMap = {}; 57 | const regex = new RegExp(titleAnswer.title); 58 | 59 | articles.forEach((article) => { 60 | if (regex.test(article.title)) { 61 | const $ = cheerio.load(article.content); 62 | // eslint-disable-next-line func-names 63 | $('h4 a').each(function () { 64 | const title = $(this).text(); 65 | const url = $(this).attr('href'); 66 | articleMap[title] = url; 67 | }); 68 | } 69 | }); 70 | 71 | titleAnswer = await inquirer.prompt([ 72 | getTitleQuestion(Object.keys(articleMap), pageSize), 73 | ]); 74 | } 75 | 76 | titleAnswer.title.forEach((title) => { 77 | open(articleMap[title]); 78 | }); 79 | 80 | return true; 81 | }; 82 | -------------------------------------------------------------------------------- /src/__tests__/readNews.spec.ts: -------------------------------------------------------------------------------- 1 | const setup = () => { 2 | const sourceInfo = { 3 | title: 'hackernews', 4 | url: undefined, 5 | feedUrl: 'https://news.ycombinator.com/rss', 6 | feedType: 'rss', 7 | }; 8 | return { sourceInfo }; 9 | }; 10 | 11 | let thenify; 12 | let inquirer; 13 | let openFn; 14 | let ora; 15 | let readNews; 16 | let succeed; 17 | 18 | jest.mock('thenify'); 19 | jest.mock('inquirer'); 20 | jest.mock('open'); 21 | jest.mock('ora'); 22 | jest.mock('../utils/log'); 23 | 24 | beforeEach(async () => { 25 | inquirer = await import('inquirer'); 26 | inquirer.prompt.mockReturnValue( 27 | Promise.resolve({ 28 | title: ['NBA-GO'], 29 | }) 30 | ); 31 | 32 | thenify = await import('thenify'); 33 | thenify.mockReturnValue(() => 34 | Promise.resolve([ 35 | { 36 | title: 'NBA-GO', 37 | link: 'https://news.ycombinator.com/item?id=15642276', 38 | }, 39 | { 40 | title: 'newsroom', 41 | link: 'https://github.com/kpman/newsroom', 42 | }, 43 | ]) 44 | ); 45 | 46 | ora = await import('ora'); 47 | ora.mockReturnValue({ 48 | start: jest.fn(() => ({ 49 | succeed, 50 | })), 51 | }); 52 | 53 | openFn = (await import('open')).default; 54 | readNews = (await import('../readNews')).default; 55 | succeed = jest.fn(); 56 | }); 57 | 58 | it('should be defined', () => { 59 | expect(readNews).toBeDefined(); 60 | }); 61 | 62 | describe('#readNews', () => { 63 | it('should call ora to add spinner', async () => { 64 | const { sourceInfo } = setup(); 65 | await readNews(sourceInfo); 66 | expect(ora).toBeCalledWith( 67 | `Trying to fetch the ${sourceInfo.title}'s latest news...` 68 | ); 69 | }); 70 | 71 | it('should call spinner succeed', async () => { 72 | const { sourceInfo } = setup(); 73 | await readNews(sourceInfo); 74 | expect(succeed).toBeCalled(); 75 | }); 76 | 77 | it('should call inquirer.prompt', async () => { 78 | const { sourceInfo } = setup(); 79 | await readNews(sourceInfo); 80 | expect(inquirer.prompt.mock.calls[0][0][0].choices).toEqual([ 81 | 'NBA-GO', 82 | 'newsroom', 83 | ]); 84 | expect(inquirer.prompt.mock.calls[0][0][0].pageSize).toBe(10); 85 | expect(inquirer.prompt.mock.calls[0][0][0].type).toBe('checkbox'); 86 | }); 87 | 88 | it('should call open', async () => { 89 | const { sourceInfo } = setup(); 90 | await readNews(sourceInfo); 91 | expect(openFn).toBeCalledWith( 92 | 'https://news.ycombinator.com/item?id=15642276' 93 | ); 94 | }); 95 | }); 96 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "newsroom-cli", 3 | "description": "A modern CLI to get your favorite news.", 4 | "license": "MIT", 5 | "author": "kpman", 6 | "homepage": "https://github.com/kpman/newsroom/#readme", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/kpman/newsroom.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/kpman/newsroom/issues" 13 | }, 14 | "version": "0.1.11", 15 | "main": "bin/cli.js", 16 | "bin": { 17 | "newsroom": "bin/cli.js", 18 | "nr": "bin/cli.js" 19 | }, 20 | "files": [ 21 | "bin", 22 | "lib" 23 | ], 24 | "scripts": { 25 | "build": "npm run clean && tsc && cp src/sources.opml lib/sources.opml", 26 | "clean": "rimraf dist packed", 27 | "lint": "eslint 'src/**/*.{js,ts}'", 28 | "lint:fix": "npm run lint -- --fix", 29 | "pkg": "npm run build && pkg . --out-path packed", 30 | "prepublishOnly": "npm run lint && npm run build", 31 | "test": "npm run lint && jest", 32 | "testonly": "jest", 33 | "testonly:cov": "jest --coverage --runInBand --forceExit", 34 | "testonly:watch": "jest --watch", 35 | "version": "rimraf package-lock.json && git add -A" 36 | }, 37 | "dependencies": { 38 | "chalk": "^2.4.1", 39 | "cheerio": "^1.0.0-rc.2", 40 | "feed-read-parser": "^0.0.6", 41 | "figures": "^2.0.0", 42 | "fuzzy": "^0.1.3", 43 | "inquirer": "^6.2.0", 44 | "inquirer-autocomplete-prompt": "^1.0.1", 45 | "invariant": "^2.2.4", 46 | "minimist": "^1.2.0", 47 | "node-opml-parser": "^1.0.0", 48 | "open": "^0.0.5", 49 | "ora": "^3.0.0", 50 | "sane": "^2.5.1", 51 | "thenify": "^3.3.0", 52 | "update-notifier": "^2.5.0" 53 | }, 54 | "devDependencies": { 55 | "@types/jest": "^29.5.1", 56 | "@types/node": "^18.15.13", 57 | "@typescript-eslint/eslint-plugin": "^5.59.0", 58 | "@typescript-eslint/parser": "^5.59.0", 59 | "eslint": "^8.38.0", 60 | "eslint-config-airbnb-base": "^15.0.0", 61 | "eslint-config-prettier": "^3.1.0", 62 | "eslint-import-resolver-typescript": "^3.5.5", 63 | "eslint-plugin-import": "^2.27.5", 64 | "eslint-plugin-prettier": "^4.2.1", 65 | "husky": "^1.1.2", 66 | "jest": "^29.5.0", 67 | "lint-staged": "^8.0.4", 68 | "pkg": "^5.8.1", 69 | "prettier": "^2.8.7", 70 | "prettier-package-json": "^2.0.1", 71 | "rimraf": "^5.0.0", 72 | "ts-jest": "^29.1.0", 73 | "ts-node": "^10.9.1", 74 | "typescript": "^5.0.4" 75 | }, 76 | "keywords": [ 77 | "newsletter" 78 | ], 79 | "engines": { 80 | "node": ">=4" 81 | }, 82 | "husky": { 83 | "hooks": { 84 | "pre-commit": "lint-staged" 85 | } 86 | }, 87 | "lint-staged": { 88 | "*.js": [ 89 | "eslint --fix", 90 | "git add" 91 | ], 92 | "package.json": [ 93 | "prettier-package-json --write", 94 | "git add" 95 | ] 96 | }, 97 | "pkg": { 98 | "scripts": "lib/**/*.js", 99 | "assets": "lib/sources.opml", 100 | "targets": [ 101 | "node14-macos", 102 | "node14-linux", 103 | "node14-win" 104 | ] 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/__tests__/main.spec.ts: -------------------------------------------------------------------------------- 1 | jest.mock('inquirer'); 2 | jest.mock('../utils/checkForUpdates'); 3 | jest.mock('../opml'); 4 | jest.mock('../readNews'); 5 | jest.mock('../help'); 6 | 7 | import minimist from 'minimist'; 8 | 9 | import main from '../main'; 10 | import pkg from '../package'; 11 | 12 | let inquirer; 13 | let checkForUpdates; 14 | let parseOpml; 15 | let readNews; 16 | let help; 17 | 18 | const _processExit = process.exit; 19 | const _consoleLog = console.log; 20 | 21 | beforeEach(async () => { 22 | checkForUpdates = (await import('../utils/checkForUpdates')).default; 23 | readNews = (await import('../readNews')).default; 24 | help = (await import('../help')).default; 25 | 26 | inquirer = await import('inquirer'); 27 | parseOpml = (await import('../opml')).default; 28 | 29 | inquirer.prompt.mockReturnValue(Promise.resolve({ source: 'hackernews' })); 30 | parseOpml.mockImplementation(() => 31 | Promise.resolve([{ title: 'hackernews' }]) 32 | ); 33 | 34 | process.exit = jest.fn() as any; 35 | console.log = jest.fn(); 36 | }); 37 | 38 | afterEach(() => { 39 | process.exit = _processExit; 40 | console.log = _consoleLog; 41 | }); 42 | 43 | describe('#main', () => { 44 | describe('check for update', () => { 45 | it('should work fine', async () => { 46 | process.argv = ['node', 'bin/cli.js']; 47 | await main(minimist(process.argv.slice(2))); 48 | expect(checkForUpdates).toBeCalled(); 49 | }); 50 | }); 51 | 52 | describe('version', () => { 53 | it('exit after call `--version`', async () => { 54 | process.argv = ['node', 'bin/cli.js', '--version']; 55 | await main(minimist(process.argv.slice(2))); 56 | expect(console.log).toBeCalledWith(pkg.version); 57 | expect(process.exit).toBeCalledWith(0); 58 | }); 59 | 60 | it('exit after call `-v`', async () => { 61 | process.argv = ['node', 'bin/cli.js', '-v']; 62 | await main(minimist(process.argv.slice(2))); 63 | expect(console.log).toBeCalledWith(pkg.version); 64 | expect(process.exit).toBeCalledWith(0); 65 | }); 66 | 67 | it('exit after call `version`', async () => { 68 | process.argv = ['node', 'bin/cli.js', 'version']; 69 | const argv = minimist(process.argv.slice(2)); 70 | await main(argv); 71 | expect(console.log).toBeCalledWith(pkg.version); 72 | expect(process.exit).toBeCalledWith(0); 73 | }); 74 | }); 75 | 76 | describe('help', () => { 77 | it('exit after call --help', async () => { 78 | process.argv = ['node', 'bin/cli.js', '--help']; 79 | await main(minimist(process.argv.slice(2))); 80 | expect(help).toBeCalled(); 81 | expect(process.exit).toBeCalledWith(0); 82 | }); 83 | 84 | it('exit after call -h', async () => { 85 | process.argv = ['node', 'bin/cli.js', '-h']; 86 | await main(minimist(process.argv.slice(2))); 87 | expect(help).toBeCalled(); 88 | expect(process.exit).toBeCalledWith(0); 89 | }); 90 | 91 | it('exit after call help', async () => { 92 | process.argv = ['node', 'bin/cli.js', 'help']; 93 | await main(minimist(process.argv.slice(2))); 94 | expect(help).toBeCalled(); 95 | expect(process.exit).toBeCalledWith(0); 96 | }); 97 | }); 98 | 99 | describe('#parseOpml', () => { 100 | it('should parse -o option', async () => { 101 | process.argv = ['node', 'bin/cli.js', '-o', './test.opml']; 102 | await main(minimist(process.argv.slice(2))); 103 | expect(parseOpml).toBeCalledWith('./test.opml'); 104 | }); 105 | }); 106 | 107 | describe('#readNews', () => { 108 | it('should parse source', async () => { 109 | let pageSize; 110 | readNews.mockImplementation(() => Promise.resolve()); 111 | process.argv = ['node', 'bin/cli.js', 'hackernews']; 112 | 113 | await main(minimist(process.argv.slice(2))); 114 | 115 | expect(readNews).toBeCalledWith({ title: 'hackernews' }, pageSize); 116 | }); 117 | }); 118 | }); 119 | --------------------------------------------------------------------------------