How to Increment Version Number via Gulp Task? - javascript

I would like to replace a string indicating version number in a javascript file (myConstantsFile.js), with another string. So, for example, my version number looks like this: "01.11.15", written like this in myConstantsFile.js with other constants:
.constant('productVersion', '1.11.15');
Right now, my task looks like this:
gulp.task('increment-version', function(){
gulp.src(['./somedir/myConstantsFile.js'])
.pipe(replace(/'productVersion', '(.*)'/g, '99.99.99'))
.pipe(gulp.dest('./somedir/'));
});
As you can see, I am using a constant, not running incrementation code, which would look like this:
var numberString = '0.0.1';
var versionParts = numberString.split('.');
var vArray = {
vMajor : versionParts[0],
vMinor : versionParts[1],
vPatch : versionParts[2]
}
vArray.vPatch = parseFloat(vArray.vPatch) + 1;
var periodString = ".";
var newVersionNumberString = vArray.vMajor + periodString +
vArray.vMinor+ periodString +
vArray.vPatch;
I need:
A way to select the current version number via regex via the file.
To know where I can put the logic in the last code block to increment the number and build the new string.

Install gulp-bump
npm install gulp-bump --save-dev
Install yargs
npm install yargs --save-dev
Require gulp-bump
var bump = require('gulp-bump');
Require yargs
var args = require('yargs').argv;
Your bump task
gulp.task('bump', function () {
/// <summary>
/// It bumps revisions
/// Usage:
/// 1. gulp bump : bumps the package.json and bower.json to the next minor revision.
/// i.e. from 0.1.1 to 0.1.2
/// 2. gulp bump --version 1.1.1 : bumps/sets the package.json and bower.json to the
/// specified revision.
/// 3. gulp bump --type major : bumps 1.0.0
/// gulp bump --type minor : bumps 0.1.0
/// gulp bump --type patch : bumps 0.0.2
/// gulp bump --type prerelease : bumps 0.0.1-2
/// </summary>
var type = args.type;
var version = args.version;
var options = {};
if (version) {
options.version = version;
msg += ' to ' + version;
} else {
options.type = type;
msg += ' for a ' + type;
}
return gulp
.src(['Path to your package.json', 'path to your bower.json'])
.pipe(bump(options))
.pipe(gulp.dest('path to your root directory'));
});
VSO Note: I believe a lot of people coming to this thread will be looking exactly for the answer above. The code below is to edit a version number stored somewhere BESIDES the npm/bower package files, such as in angular constants:
gulp.task('increment-version', function(){
//docString is the file from which you will get your constant string
var docString = fs.readFileSync('./someFolder/constants.js', 'utf8');
//The code below gets your semantic v# from docString
var versionNumPattern=/'someTextPreceedingVNumber', '(.*)'/; //This is just a regEx with a capture group for version number
var vNumRexEx = new RegExp(versionNumPattern);
var oldVersionNumber = (vNumRexEx.exec(docString))[1]; //This gets the captured group
//...Split the version number string into elements so you can bump the one you want
var versionParts = oldVersionNumber.split('.');
var vArray = {
vMajor : versionParts[0],
vMinor : versionParts[1],
vPatch : versionParts[2]
};
vArray.vPatch = parseFloat(vArray.vPatch) + 1;
var periodString = ".";
var newVersionNumber = vArray.vMajor + periodString +
vArray.vMinor+ periodString +
vArray.vPatch;
gulp.src(['./someFolder/constants.js'])
.pipe(replace(/'someTextPreceedingVNumber', '(.*)'/g, newVersionNumber))
.pipe(gulp.dest('./someFolder/'));
});
I ommitted some mumbo-jumbo that writes my constant in a pretty string, but that's the gist and it works.

Started looking into gulp since past 5 hours,as I had a task to fix the requirement. So, being a definite noob to gulp I came out with the below code which is without the regex expression. Thanks to #VSO and #Wilmer Saint for a quick start. Might be a tiny change, but this helped me.
gulp.task('version', function(){
var fs = require('fs');
//docString is the file from which you will get your constant string
var docString = fs.readFileSync('app/scripts/version/version.js', 'utf8'); //type of docString i an object here.
var versionParts = docString.split('.');
var vArray = {
vMajor : versionParts[0],
vMinor : versionParts[1],
vPatch : versionParts[2]
};
vArray.vPatch = parseFloat(vArray.vPatch) + 1;
var periodString = ".";
var newVersionNumber = vArray.vMajor + periodString +
vArray.vMinor+ periodString +
vArray.vPatch;
require('fs').writeFileSync('app/scripts/version/version.js', newVersionNumber + "'");
return gulp.src(['app/scripts/version/version.js'])
.pipe(gulp.dest('app/scripts/version/new_version'));//creates version.js file in the directory
});
or the return code could be as below to override the number in version.js file
return gulp.src(['app/scripts/version/version.js'],
{base: './app/scripts/version/version.js'})
.pipe((gulp.dest('./app/scripts/version/version.js')))
My version.js has only below code
versionBuild = '1.0.8'
I used the below in my main function(loads on loading the app)
var versionBuild=parseInt(1000*Math.random());
var random = function(digs){
var rndn;
if(window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
rndn = Math.random();
if(digs != undefined && !isNaN(digs)){
rndn = parseInt(Math.pow(10, digs)*rndn)
}
return rndn;
}
else {
return versionBuild;
}
}

you can use gulp-bump, it's very easy and sweet :)
npm install --save gulp-bump
const bump = require('gulp-bump');
gulp.task('bump', async () => {
gulp.src('./package.json')
.pipe(bump({key: "version"}))
.pipe(gulp.dest('./'));
});
Note: use async before a function. it's a requirement.

gulp.task('bump', function() {
var vers = JSON.parse(fs.readFileSync(__dirname + '/package.json')).version.split('.');
var second = parseInt(vers[1]);
var third = parseInt(vers[2]);
var options = { key: 'version' };
if(third == 9 && second != 9) {
third = 0;
options.type = 'minor';
} else if (second == 9 && third == 9) {
second = 0;
options.type = 'major';
}
gulp.src(__dirname + '/package.json')
.pipe(bump(options))
.pipe(gulp.dest('./'));
});

Related

I have a for with a gulp.watch, but it doesnt work correctly

I need help.
I have this code. I have many sources and i don't use n*source watchs.
I thinked that a for can be a solution, but the watch is instantiated and it dont read my source[i].
You can say some solutions.
Thnks!
var base_source = '../';
var source = ['dir1', 'dir2'];
var allFiles = '/**/*';
var dest = '../dist';
gulp.task('default', function () {
for(var i = 0; i < source.length ; i++) {
var watchW = base_source + source[i] + allFiles;
gulp.watch(watchW, function(obj){
copyFiles(watchW, dest , obj);
});
}
}
Edit: I need the source[i] in copyFiles function
Sorry for my english ^^"
It is difficult to explain why your code doesn't work. As you can see only the last index "i" is bound to all watch functions. This is known as the "reference problem". All your watch functions are using, by reference, the same index i. See, for example, referencing last index in loop.
Using #OverZealous's answer as guidance in creating gulp tasks in a loop here is a solution for you:
var gulp = require('gulp');
// changed to up one directory
var base_source = './';
// changed variable name slightly for clarity
var sources = ['dir1', 'dir2'];
var allFiles = '/**/*';
// changed to up one directory
var dest = './dist';
var watchSources = Object.keys(sources);
gulp.task('default', function () {
watchSources.forEach(function (index) {
var watchW = base_source + sources[index] + allFiles;
gulp.watch(watchW, function (obj) {
copyFiles(watchW, dest, obj);
});
});
});
function copyFiles(watched, to, obj) {
console.log("watched = " + watched);
}

Why would `node --inspect` not stop at a given Chrome DevTools breakpoint? (while `debugger;` works)

I am debugging a Webpack build by using node --inspect and Chrome DevTools.
I see that my output file contains a piece of code with the comment /* WEBPACK VAR INJECTION */. If I put a break point right at the Webpack code that generates that comment, the debugger won't stop at that breakpoint when running the build in debug mode, but it stops when I place debugger;. Why?
EDIT:
The (last version of the) code I am referring to can be seen in
https://github.com/webpack/webpack/blob/master/lib/NormalModule.js
Here I paste an extract. I expected the debugger to stop at any breakpoint I put inside this function (except inside places like the function passed to .map and .forEach). (This is the only piece of code in Webpack that writes /* WEBPACK VAR INJECTION */):
function doBlock(block) {
console.log("1 What the F*** is going on with this debugger?");
block.dependencies.forEach(doDep);
block.blocks.forEach(doBlock);
if(block.variables.length > 0) {
var vars = [];
block.variables.forEach(doVariable.bind(null, vars));
var varNames = [];
var varExpressions = [];
var varStartCode = "";
var varEndCode = "";
function emitFunction() {
console.log("2 Why the F*** is it that a breakpoint right here doesn't stop the debugger?");
if(varNames.length === 0) return;
varStartCode += "/* WEBPACK VAR INJECTION */(function(" + varNames.join(", ") + ") {";
// exports === this in the topLevelBlock, but exports do compress better...
varEndCode = (topLevelBlock === block ? "}.call(exports, " : "}.call(this, ") +
varExpressions.map(function(e) {
return e.source();
}).join(", ") + "))" + varEndCode;
varNames.length = 0;
varExpressions.length = 0;
}
vars.forEach(function(v) {
if(varNames.indexOf(v.name) >= 0) emitFunction();
varNames.push(v.name);
varExpressions.push(v.expression);
});
emitFunction();
console.log("3 Are you not gonna stop here, debugger? Are you F****** kidding me?");
var start = block.range ? block.range[0] : 0;
var end = block.range ? block.range[1] : _source.size();
if(varStartCode) source.insert(start + 0.5, varStartCode);
if(varEndCode) source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode);
}
}

events.js:142 error in node.js

I have a file , in javascript , that find all the directories that match the parameter.
And i got this error:
my code:
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
var home_path=getUserHome();
var findit = require('findit'),
path = require('path'),
finder = findit(path.resolve(home_path));
var myArgs = process.argv.slice(2)[0];
var filter1 = new RegExp(myArgs);
//This listens for directories found
finder.on('directory', function (dir) {
var directories = dir.split('\\');
var last= directories[directories.length-1].toLowerCase();
if(filter1.test(last)){
console.log('Directory: ' + dir );
}
});
(My code is a mess, i will clean it later)
How to fix that?
Why you didn't user the fs from Node, and look for dirs recursively? I think the error should be on the findit module...
That a look on https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback or try instead the https://www.npmjs.com/package/recursive-readdir that also does it. I think that the things you use from the module findit, will be available there (like ways to ignore files)...
EDIT1: Example using recursive-readdir:
var recursive = require('recursive-readdir');
var filter1 = new RegExp(myArgs);
function ignoreFunc(file, stats) {
return !(stats.isDirectory() && filter1.test(path.basename(file)));
}
recursive('directory', [ignoreFunc] ,function (err, files) {
// Files is an array of filename (only the ones that matched the condition)
console.log(files);
});
#Moran, can you add a console.log directly in the callback of you "directory" event ?
finder.on('directory', function (dir) {
// Here
console.log(dir);
var directories = dir.split('\\');
var last= directories[directories.length-1].toLowerCase();
if(filter1.test(last)){
console.log('Directory: ' + dir );
}
});
To see what directory is problematic ? Then compare the rights applied on this folder and a directory that work, as "comverse" for example. It would help to find your error

Windows Scripting to call other commands?

I was trying my hand at Windows shell scripting using cscript and Javascript. The idea was to take a really long Python command that I was tired of typing into the command line over and over. What I wanted to do was write a script that is much shorter to write the whole Python command into a Windows script and just call the Windows script, which would be a lot less to type. I just don't know how I would go about calling a "command within a command" if that makes sense.
This is probably an easy thing, but I'm an newbie at this so please bear with me!
The idea:
Example original command: python do <something really complicated with a long filepath>
Windows Script: cscript easycommand
<package id = "easycommand">
<job id = "main" >
<script type="text/javascript">
// WHAT GOES HERE TO CALL python do <something really complicated>
WScript.Echo("Success!");
</script>
</job>
</package>
Thanks for all your help!
Here's what I use
function logMessage(msg) {
if (typeof wantLogging != "undefined" && wantLogging) {
WScript.Echo(msg);
}
}
// http://msdn.microsoft.com/en-us/library/d5fk67ky(VS.85).aspx
var windowStyle = {
hidden : 0,
minimized : 1,
maximized : 2
};
// http://msdn.microsoft.com/en-us/library/a72y2t1c(v=VS.85).aspx
var specialFolders = {
windowsFolder : 0,
systemFolder : 1,
temporaryFolder : 2
};
function runShellCmd(command, deleteOutput) {
deleteOutput = deleteOutput || false;
logMessage("RunAppCmd("+command+") ENTER");
var shell = new ActiveXObject("WScript.Shell"),
fso = new ActiveXObject("Scripting.FileSystemObject"),
tmpdir = fso.GetSpecialFolder(specialFolders.temporaryFolder),
tmpFileName = fso.BuildPath(tmpdir, fso.GetTempName()),
rc;
logMessage("shell.Run("+command+")");
// use cmd.exe to redirect the output
rc = shell.Run("%comspec% /c " + command + "> " + tmpFileName,
windowStyle.Hidden, true);
logMessage("shell.Run rc = " + rc);
if (deleteOutput) {
fso.DeleteFile(tmpFileName);
}
return {
rc : rc,
outputfile : (deleteOutput) ? null : tmpFileName
};
}
Here's an example of how to use the above to list the Sites defined in IIS with Appcmd.exe:
var
fso = new ActiveXObject("Scripting.FileSystemObject"),
windir = fso.GetSpecialFolder(specialFolders.WindowsFolder),
r = runShellCmd("%windir%\\system32\\inetsrv\\appcmd.exe list sites");
if (r.rc !== 0) {
// 0x80004005 == E_FAIL
throw {error: "ApplicationException",
message: "shell.run returned nonzero rc ("+r.rc+")",
code: 0x80004005};
}
// results are in r.outputfile
var
textStream = fso.OpenTextFile(r.outputfile, OpenMode.ForReading),
sites = [], item,
re = new RegExp('^SITE "([^"]+)" \\((.+)\\) *$'),
parseOneLine = function(oneLine) {
// each line is like this: APP "kjsksj" (dkjsdkjd)
var tokens = re.exec(oneLine), parts;
if (tokens === null) {
return null;
}
// return the object describing the website
return {
name : tokens[1]
};
};
// Read from the file and parse the results.
while (!textStream.AtEndOfStream) {
item = parseOneLine(textStream.ReadLine()); // you create this...
logMessage(" site: " + item.name);
sites.push(item);
}
textStream.Close();
fso.DeleteFile(r.outputfile);
Well, basically:
Obtain a handle to the shell so you can execute your script
Create the command you want to execute (parameters and all) as a string
Call the Run method on the shell handle, and figure out which window mode you want and also whether you want to wait until the spawned process finishes (probably) or not.
Error handling because Run throws exceptions
At this point it's worth writing a lot of utility functions if ever you need to do it more than once:
// run a command, call: run('C:\Python27\python.exe', 'path/to/script.py', 'arg1', 'arg2') etc.
function run() {
try {
var cmd = "\"" + arguments[0] + "\"";
var arg;
for(var i=1; i< arguments.length; ++i) {
arg = "" + arguments[i];
if(arg.length > 0) {
cmd += arg.charAt(0) == "/" ? (" " + arg) : (" \"" + arg + "\"");
}
}
return getShell().Run(cmd, 1, true); // show window, wait until done
}
catch(oops) {
WScript.Echo("Error: unable to execute shell command:\n"+cmd+
"\nInside directory:\n" + pwd()+
"\nReason:\n"+err_message(oops)+
"\nThis script will exit.");
exit(121);
}
}
// utility which makes an attempt at retrieving error messages from JScript exceptions
function err_message(err_object) {
if(typeof(err_object.message) != 'undefined') {
return err_object.message;
}
if(typeof(err_object.description) != 'undefined') {
return err_object.description;
}
return err_object.name;
}
// don't create new Shell objects each time you call run()
function getShell() {
var sh = WScript.CreateObject("WScript.Shell");
getShell = function() {
return sh;
};
return getShell();
}
For your use case this may be sufficient, but you might want to extend this with routines to change working directory and so on.

javascript to stop specific service

I have the following code in a script.
The problem is That I want to get information of scripts that starts in a specific name and are in a specific startmode.
var e = new Enumerator(GetObject("winmgmts:").InstancesOf("Win32_Service"))
var WSHShell = new ActiveXObject ("WScript.Shell");
var strPrefix = "TTTT";
for(;!e.atEnd(); e.moveNext()){
var Service = e.item();
var strName = Service.Name;
if (strName.substr (0, strPrefix.length) == strPrefix) {
if(Service.StartMode == 'mmManual') {
WScript.Echo("Yes");
}
if(e.StartMode == 'Manual') {
WScript.Echo("Yes");
}
}
}
In the above script I tried to know the start mode but it always return true.
McDowell is right, but note that you can get rid of prefix and start mode checks in your loop if you make them part of the WMI query:
SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'
Using this query, your script could look like this:
var strComputer = ".";
var oWMI = GetObject("winmgmts://" + strComputer + "/root/CIMV2");
var colServices = oWMI.ExecQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'");
var enumServices = new Enumerator(colServices);
for(; !enumServices.atEnd(); enumServices.moveNext())
{
var oService = enumServices.item();
WScript.Echo(oService.Name);
}
I'm not sure exactly what you're asking, but this...
if(Service.StartMode = 'mmManual')
...will always evaluate to true. You are missing an =. It should be:
if(Service.StartMode == 'mmManual')

Categories

Resources