cli (2611B)
1 #!/usr/bin/env node 2 3 /** 4 * @license Apache-2.0 5 * 6 * Copyright (c) 2020 The Stdlib Authors. 7 * 8 * Licensed under the Apache License, Version 2.0 (the "License"); 9 * you may not use this file except in compliance with the License. 10 * You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, software 15 * distributed under the License is distributed on an "AS IS" BASIS, 16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 * See the License for the specific language governing permissions and 18 * limitations under the License. 19 */ 20 21 'use strict'; 22 23 // MODULES // 24 25 var resolve = require( 'path' ).resolve; 26 var readFileSync = require( '@stdlib/fs/read-file' ).sync; 27 var CLI = require( '@stdlib/cli/ctor' ); 28 var stdin = require( '@stdlib/process/read-stdin' ); 29 var stdinStream = require( '@stdlib/streams/node/stdin' ); 30 var RE_EOL = require( '@stdlib/regexp/eol' ).REGEXP; 31 var numGraphemeClusters = require( './../lib' ); 32 33 34 // MAIN // 35 36 /** 37 * Main execution sequence. 38 * 39 * @private 40 * @returns {void} 41 */ 42 function main() { 43 var flags; 44 var lines; 45 var args; 46 var cli; 47 var i; 48 49 // Create a command-line interface: 50 cli = new CLI({ 51 'pkg': require( './../package.json' ), 52 'options': require( './../etc/cli_opts.json' ), 53 'help': readFileSync( resolve( __dirname, '..', 'docs', 'usage.txt' ), { 54 'encoding': 'utf8' 55 }) 56 }); 57 58 // Get any provided command-line options: 59 flags = cli.flags(); 60 if ( flags.help || flags.version ) { 61 return; 62 } 63 64 // Get any provided command-line arguments: 65 args = cli.args(); 66 67 // Check if we are receiving data from `stdin`... 68 if ( !stdinStream.isTTY ) { 69 return stdin( onRead ); 70 } 71 if ( flags.lines ) { 72 lines = args[ 0 ].split( RE_EOL ); 73 for ( i = 0; i < lines.length; i++ ) { 74 console.log( numGraphemeClusters( lines[ i ] ) ); // eslint-disable-line no-console 75 } 76 } else { 77 console.log( numGraphemeClusters( args[ 0 ] ) ); // eslint-disable-line no-console 78 } 79 80 /** 81 * Callback invoked upon reading from `stdin`. 82 * 83 * @private 84 * @param {(Error|null)} error - error object 85 * @param {Buffer} data - data 86 * @returns {void} 87 */ 88 function onRead( error, data ) { 89 var lines; 90 var i; 91 if ( error ) { 92 return cli.error( error ); 93 } 94 data = data.toString(); 95 if ( flags.lines ) { 96 lines = data.split( RE_EOL ); 97 for ( i = 0; i < lines.length; i++ ) { 98 console.log( numGraphemeClusters( lines[ i ] ) ); // eslint-disable-line no-console 99 } 100 } else { 101 console.log( numGraphemeClusters( data ) ); // eslint-disable-line no-console 102 } 103 } 104 } 105 106 main();