Skip to content

Commit

Permalink
Merge pull request #1 from kevinbarz/master
Browse files Browse the repository at this point in the history
feat(option to save git.properties to a specific directory)
  • Loading branch information
rcruzper authored Nov 24, 2016
2 parents b4eac18 + fa69100 commit 3998d48
Show file tree
Hide file tree
Showing 9 changed files with 223 additions and 61 deletions.
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"extends": "eslint:recommended",
"env": {
"node": true
"node": true,
"es6": true
},
"rules": {
"no-console": 0,
Expand Down
1 change: 1 addition & 0 deletions .istanbul.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ instrumentation:
excludes:
- '.idea/**'
- 'build/**'
- 'index.js'
embed-source: false
complete-copy: false
include-all-sources: true
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ Node module that creates a git.properties file with information about the curren

```sh
$ npm install -g node-git-info
$ node-git-info
$ node-git-info [options]

-d, --directory Directory to save git.properties file to (directory must already exist).
```
it will returns a file named ```git.properties```:
It will save a file named ```git.properties```. If the directory option isn't passed, then default location for saving the git.properties file will be the current working directory of the Node.js process.

Example output:
```ini
git.commit.id.abbrev=42954d1
git.commit.user.email[email protected]
Expand All @@ -23,4 +27,4 @@ git.commit.message.short=first commit
git.commit.user.name=User Name
git.branch=master
git.commit.time=2016-11-20T11:48:42.000Z
```
```
2 changes: 1 addition & 1 deletion bin/node-git-info
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/usr/bin/env node

require('../lib/gitProperties');
require('../index');
33 changes: 33 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';
var gitProperties = require('./lib/gitProperties');
var commandLineArgs = require('command-line-args')

// library's entry point
var execute = function () {

// define allows command line arguments when calling library
const optionDefinitions = [
{name: 'directory', alias: 'd', type: String}
]

// convert command line arguments to object
const options = commandLineArgs(optionDefinitions);

// define callback function to call when git.properties file has been written or when an error doing so occurs.
var callback = function (writeSuccess) {
if (writeSuccess) {
//exit with a 'success' code
process.exit(0);
} else {
//exit with a 'failure' code
process.exit(1);
}
}

// write git.properties file
gitProperties.write(options.directory, callback);
}

execute();

module.exports = execute;
100 changes: 62 additions & 38 deletions lib/gitProperties.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,69 @@ var fs = require('fs');
var Promise = require('bluebird');
var gitCommand = require('./gitCommands');

var gitProperties = function() {
var gitPromises = {
branch: gitCommand.getBranch(),
commitId: gitCommand.getCommitId(),
commitUserName: gitCommand.getCommitUserName(),
commitUserEmail: gitCommand.getCommitUserEmail(),
commitMessageFull: gitCommand.getCommitMessageFull(),
commitMessageShort: gitCommand.getCommitMessageShort(),
commitTime: gitCommand.getCommitTime()
};

Promise.props(gitPromises).then(function(git) {
var gitProperties = {
'git.commit.id.abbrev': git.commitId.substring(0,7),
'git.commit.user.email': git.commitUserEmail,
'git.commit.message.full': git.commitMessageFull,
'git.commit.id': git.commitId,
'git.commit.message.short': git.commitMessageShort,
'git.commit.user.name': git.commitUserName,
'git.branch': git.branch,
'git.commit.time': git.commitTime
module.exports = {


/**
* @param destinationPath Directory to save git.properties file to (directory must already exist).
* @param callback Function to call when git.properties file has been written or when an error doing so occurs.
*/
write: function (destinationPath, callback) {

destinationPath = destinationPath || process.cwd(); // default location for saving the git.properties file
// will be the current working directory of the Node.js process.

var gitPromises = {
branch: gitCommand.getBranch(),
commitId: gitCommand.getCommitId(),
commitUserName: gitCommand.getCommitUserName(),
commitUserEmail: gitCommand.getCommitUserEmail(),
commitMessageFull: gitCommand.getCommitMessageFull(),
commitMessageShort: gitCommand.getCommitMessageShort(),
commitTime: gitCommand.getCommitTime()
};

var returnInfo = Object.keys(gitProperties).map(function(key){
return key + '=' + gitProperties[key] + '\n';
})

// Generate git.properties file
fs.writeFile('git.properties', returnInfo.join(''), function(err) {
if(err) {
console.log('[node-git-properties][ERROR]: can\'t create git.properties file.');
}
else{
console.log('[node-git-properties] git.properties has successfully created.');
}
});
});
}
Promise.props(gitPromises).then(function (git) {
var gitProperties = {
'git.commit.id.abbrev': git.commitId.substring(0, 7),
'git.commit.user.email': git.commitUserEmail,
'git.commit.message.full': git.commitMessageFull,
'git.commit.id': git.commitId,
'git.commit.message.short': git.commitMessageShort,
'git.commit.user.name': git.commitUserName,
'git.branch': git.branch,
'git.commit.time': git.commitTime
};

var returnInfo = Object.keys(gitProperties).map(function (key) {
return key + '=' + gitProperties[key] + '\n';
})

gitProperties();
var gitPropertiesFormatted = returnInfo.join(''); // format git properties for marshalling to file

module.exports = gitProperties;
var destinationPathCleaned = destinationPath.replace(/\/?$/, '/'); // make sure destination path ends
// with '/'

var writeSuccess; // placeholder for storing save operation success status

// Generate git.properties file
fs.writeFile(destinationPathCleaned + 'git.properties', gitPropertiesFormatted, function (err) {
if (err) {
// error has occured saving git.properties
console.log('[node-git-properties][ERROR]: can\'t create git.properties file.');
writeSuccess = false;
}
else {
// saving git.properties was a success
console.log('[node-git-properties] git.properties has successfully created.');
writeSuccess = true;
}

if (callback){
callback(writeSuccess);
}

});
});
}
}
8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@
"LICENSE",
"README.md"
],
"main": "lib/gitProperties.js",
"main": "index.js",
"bin": {
"node-git-info": "bin/node-git-info"
},
"devDependencies": {
"app-root-dir": "^1.0.2",
"chai": "3.5.0",
"coveralls": "2.11.15",
"eslint": "3.10.2",
"istanbul": "0.4.5",
"mocha": "3.1.2",
"mock-fs": "^3.12.1",
"sinon": "1.17.6",
"sinon-chai": "2.8.0",
"tmp": "0.0.31",
"utils-fs-read-properties": "1.0.0"
},
"scripts": {
"start": "node lib/gitProperties",
"start": "node index.js",
"test:unit": "istanbul test _mocha -- test/unit --reporter spec --recursive",
"pretest": "eslint .",
"test": "npm run test:unit --coverage",
Expand All @@ -36,6 +39,7 @@
"dependencies": {
"bluebird": "3.4.6",
"child-process-promise": "2.2.0",
"command-line-args": "^3.0.3",
"moment": "2.16.0"
},
"repository": {
Expand Down
116 changes: 100 additions & 16 deletions test/unit/lib/gitProperties.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,111 @@
'use strict'

var fs = require('fs');
var properties = require('../../../lib/gitProperties');
var expect = require('chai').expect;
var read = require( 'utils-fs-read-properties' );
var read = require('utils-fs-read-properties');
var appRootDir = require('app-root-dir').get();
var tmp = require('tmp');
var utils = require('./utils');
var mock = require('mock-fs');

function checkGitPropertiesFileHasExpectedData(filePath, done) {

expect(fs.existsSync(filePath)).to.be.true;

read(filePath, function (error, data) {
expect(data['git.commit.id.abbrev']).to.not.be.undefined;
expect(data['git.commit.user.email']).to.not.be.undefined;
expect(data['git.commit.message.full']).to.not.be.undefined;
expect(data['git.commit.id']).to.not.be.undefined;
expect(data['git.commit.message.short']).to.not.be.undefined;
expect(data['git.commit.user.name']).to.not.be.undefined;
expect(data['git.branch']).to.not.be.undefined;
expect(data['git.commit.time']).to.not.be.undefined;

done();
});
}


describe('executing write method', function () {

describe('gitProperties', function() {
const testSuiteLevelTimeout = 30 * 1000;
const gitPropertiesFileName = 'git.properties';
// set higher than default test suite-level timeout in case of large files being writen/read.
this.timeout(testSuiteLevelTimeout);

it ('should creates a git.properties file', function() {
properties();
var tmpTestOutputFolder; // tempory folder for writing git.properties file to.
var gitPropertiesExpectedDefaultFileName = appRootDir + '/' + gitPropertiesFileName;

expect(fs.existsSync('git.properties')).to.be.true;
before(function (done) {

read('git.properties', function(error, data) {
expect(data['git.commit.id.abbrev']).to.not.be.undefined;
expect(data['git.commit.user.email']).to.not.be.undefined;
expect(data['git.commit.message.full']).to.not.be.undefined;
expect(data['git.commit.id']).to.not.be.undefined;
expect(data['git.commit.message.short']).to.not.be.undefined;
expect(data['git.commit.user.name']).to.not.be.undefined;
expect(data['git.branch']).to.not.be.undefined;
expect(data['git.commit.time']).to.not.be.undefined;
// runs before any tests are executed in this block

tmp.setGracefulCleanup(); // cleanup the temporary files even when an uncaught exception occurs.

tmp.dir({dir: appRootDir, unsafeCleanup : true}, function _tempDirCreated(err, path) {
if (err) throw err;
tmpTestOutputFolder = path;

// now mock fs library
const mockedGitProperties = "git.branch=master\ngit.commit.id.abbrev=1324324\ngit.commit.time=2016-11-18T13:16:39.000Z";
const mockedGitPropertiesPath = tmpTestOutputFolder + '/' + gitPropertiesFileName;
var mockFileSystem = {};
mockFileSystem[gitPropertiesExpectedDefaultFileName] = mockedGitProperties;
mockFileSystem[mockedGitPropertiesPath] = mockedGitProperties;
mock(mockFileSystem);
done()
});
})

beforeEach(function () {
// runs after each test in this block
utils.deleteFilesRecursivelyByName(gitPropertiesFileName); // delete test generated files
});

after(function () {
// runs after all tests have executed in this block
utils.deleteFilesRecursivelyByName(appRootDir, gitPropertiesFileName); // delete test generated files
});

afterEach(function () {
// restore the fs module (so that it is backed by the real file system)
mock.restore();
});

it('should create a git.properties file', function (done) {

var callback = function () {

checkGitPropertiesFileHasExpectedData(gitPropertiesExpectedDefaultFileName, done);
}

properties.write(undefined, callback);
});

});
it('should create a git.properties file in the destination directory given ', function (done) {

properties.write(tmpTestOutputFolder);

var callback = function () {
var gitPropertiesDestination = tmpTestOutputFolder + '/' + gitPropertiesFileName;
checkGitPropertiesFileHasExpectedData(gitPropertiesDestination, done);
};

properties.write(tmpTestOutputFolder, callback);
});

it('should return an error status if destination directory given does not exist', function (done) {

var destinationPath = tmpTestOutputFolder + '/i_am_a_directory_that_does_not_exist';

var callback = function (writeSuccess) {
expect(writeSuccess).to.be.false;
var gitPropertiesDestination = destinationPath + '/' + gitPropertiesFileName;
expect(fs.existsSync(gitPropertiesDestination)).to.be.false;
done();
};

properties.write(destinationPath, callback);
});
});
11 changes: 11 additions & 0 deletions test/unit/lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict'
var spawn = require('child_process').spawn;

/* test utility methods */

exports.deleteFilesRecursivelyByName = function(appRootDir, fileName) {
var shellSyntaxCommand = 'find ' + appRootDir + ' -name ' + fileName + ' -type f|xargs rm -f';
spawn('sh', ['-c', shellSyntaxCommand], {stdio: 'inherit'});
}

/* end test utility methods */

0 comments on commit 3998d48

Please sign in to comment.