Skip to content
Open
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
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Build a JavaScript Command Line Interface (CLI) with Node.js

Node is a great choice for building command line tools.
In this tutorial, James Hibbard and Lukas White show you how to build a Node CLI which interacts with the GitHub API.

Article URL: https://www.sitepoint.com/javascript-command-line-interface-cli-node-js/

## Requirements

* [Node.js](http://nodejs.org/)
* [Git](https://git-scm.com/)
* [GitHub account](https://github.com/)

## Installation Steps (if applicable)

1. Clone repo
2. Run `npm install`
3. Install the module globally with `npm install -g` from within the project directory
4. Run `ginit <repo-name> <longer repo description>`

## License

The MIT License (MIT)

Copyright (c) 2020 SitePoint

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
330 changes: 62 additions & 268 deletions index.js
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,275 +1,69 @@
var clear = require('clear');
var chalk = require('chalk');
var figlet = require('figlet');
var inquirer = require('inquirer');
var GitHubApi = require('github');
var Preferences = require('preferences');
var CLI = require('clui');
var Spinner = CLI.Spinner;
var git = require('simple-git')();
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var touch = require('touch');
var files = require('./lib/files');
#!/usr/bin/env node

/**************************************************
* Display message
*************************************************/
clear();
console.log(chalk.yellow(figlet.textSync('Ginit', {
horizontalLayout: 'full'
})));

/**************************************************
* Check that this isn't already a Git repo
*************************************************/
if (files.directoryExists('.git')) {
console.log(chalk.red( 'Already a git repository!'));
process.exit();
}

var github = new GitHubApi({
version: '3.0.0'
});

function createGitignore( callback ) {

var filelist = _.without(fs.readdirSync('.'), '.git', '.gitignore');

if ( filelist.length ) {

inquirer.prompt(
[
{
type: 'checkbox',
name: 'ignore',
message: 'Select the files and/or folders you wish to ignore:',
choices: filelist,
default: [ 'node_modules', 'bower_components' ]
}
],
function( answers ) {

if ( answers.ignore.length ) {

fs.writeFileSync( '.gitignore', answers.ignore.join( '\n' ) );

} else {

touch( '.gitignore' );

}

return callback();

}
);

} else {
touch( '.gitignore' );
return callback();
}

}

function getGithubCredentials( callback ) {

var questions = [
{
type: 'input',
name: 'username',
message: 'Enter your Github username or e-mail address:',
validate: function( value ) {
if ( value.length ) {
return true;
} else {
return 'Please enter your username or e-mail address';
}
}
},
{
type: 'password',
name: 'password',
message: 'Enter your password:',
validate: function( value ) {
if ( value.length ) {
return true;
} else {
return 'Please enter your password';
}
}
}
];

inquirer.prompt( questions, callback );
}

function getGithubToken( callback ) {

var prefs = new Preferences('ginit');
const chalk = require('chalk');
const clear = require('clear');
const figlet = require('figlet');

if ( prefs.github && prefs.github.token ) {
return callback( null, prefs.github.token );
}

getGithubCredentials( function( credentials ) {

var status = new Spinner('Authenticating you, please wait...');
status.start();

github.authenticate(
_.extend(
{
type: 'basic',
},
credentials
)
);

github.authorization.create({
scopes: [ 'user', 'public_repo', 'repo', 'repo:status' ],
note: 'ginit, the command-line tool for initalizing Git repos'
}, function(err, res) {
status.stop();
if ( err ) {
return callback( err );
}
console.log( res );
if ( res.token ) {
prefs.github = {
token : res.token
};
return callback( null, res.token );
}
return callback();
});

});

}

function githubAuth( callback ) {

getGithubToken( function( err, token ){
if ( err ) {
return callback( err );
}
github.authenticate({
type : 'oauth',
token : token
});
return callback( null, token );
})

}

function createRepo( callback ) {

var questions = [
{
type: 'input',
name: 'name',
message: 'Enter a name for the repository:',
default: path.basename( process.cwd() ),
validate: function( value ) {
if ( value.length ) {
return true;
} else {
return 'Please enter a name for the repository';
}
}
},
{
type: 'input',
name: 'description',
message: 'Optionally enter a description of the repository:'
},
{
type: 'list',
name: 'visibility',
message: 'Public or private:',
choices: [ 'public', 'private' ],
default: 'public'
}
];


inquirer.prompt( questions, function( answers ) {

var status = new Spinner('Creating repository...');
status.start();

var data = {
name : answers.name,
description : answers.description,
private : ( answers.visibility === 'private' )
};

github.repos.create(
data,
function( err, res ) {
status.stop();
if ( err ) {
return callback( err );
}
return callback( null, res.ssh_url );
}
);

});

}
const files = require('./lib/files');
const github = require('./lib/github');
const repo = require('./lib/repo');

clear();

function setupRepo( url, callback ) {

var status = new Spinner('Setting up the repository...');
status.start();
console.log(
chalk.yellow(
figlet.textSync('Ginit', { horizontalLayout: 'full' })
)
);

git
.init()
.add('.gitignore')
.add('./*')
.commit('Initial commit')
.addRemote( 'origin', url )
.push('origin', 'master')
.then(function(){
status.stop();
return callback();
});
if (files.directoryExists('.git')) {
console.log(chalk.red('Already a Git repository!'));
process.exit();
}

/**************************************************
* The main app code; start by seeing whether we have
* a pre-existing Github OAuth code.
*************************************************/
githubAuth( function( err, authed ) {
if ( err ) {
switch ( err.code ) {
case 401:
console.log( chalk.red('Couldn\'t log you in. Please try again.') );
break;
case 422:
console.log( chalk.red('You already have an access token.') );
break;
}
}
if ( authed ) {
console.log( chalk.green('Sucessfully authenticated!') );
createRepo( function( err, url ){
if ( err ) {
console.log('An error has occured');
}
if ( url ) {
createGitignore( function() {
setupRepo( url, function( err ) {
if ( !err ) {
console.log(chalk.green('All done!'));
}
});
});
}
});
}
});
const getGithubToken = async () => {
// Fetch token from config store
let token = github.getStoredGithubToken();
if(token) {
return token;
}

// No token found, use credentials to access GitHub account
token = await github.getPersonalAccesToken();

return token;
};

const run = async () => {
try {
// Retrieve & Set Authentication Token
const token = await getGithubToken();
github.githubAuth(token);

// Create remote repository
const url = await repo.createRemoteRepo();

// Create .gitignore file
await repo.createGitignore();

// Set up local repository and push to remote
await repo.setupRepo(url);

console.log(chalk.green('All done!'));
} catch(err) {
if (err) {
switch (err.status) {
case 401:
console.log(chalk.red('Couldn\'t log you in. Please provide correct credentials/token.'));
break;
case 422:
console.log(chalk.red('There is already a remote repository or token with the same name'));
break;
default:
console.log(chalk.red(err));
}
}
}
};

run();
Loading