19

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:

  1. A way to select the current version number via regex via the file.
  2. To know where I can put the logic in the last code block to increment the number and build the new string.
VSO
  • 11,546
  • 25
  • 99
  • 187
  • 1
    What about gulp-bump ? https://www.npmjs.com/package/gulp-bump – cl3m Mar 31 '16 at 17:17
  • From past experience, keep your build number in its own file (in this case, maybe even JSON). When sed replacements in a code file eventually cause a problem, it will be damn near impossible to figure out. – ssube Mar 31 '16 at 17:17
  • @cl3m Looks good, I am looking over the functionality. My main problems are the basic selection of the data via regex to work with and where to put my vars/functions. This is my first time doing anything with gulp, other than running browser-sync and such. ssube - that's a good idea, but the problem is that angular constants need to pull from it. – VSO Mar 31 '16 at 17:22
  • 1
    we do a very similar thing with grunt. version is stored on package.json, and increment in a grunt task file. *Not sure how this translates to Gulp.* I will say that this has proved somewhat fragile because multiple developers can each perform an increment on a build, and because package.json is not (in our case) version controlled, it can easily get out of sync. So - the takeaway is : version control your build number source. – Bosworth99 Mar 31 '16 at 17:23
  • 1
    @Bosworth99 Noted. This whole thing is a pain, we increment version number in SQL during the build as well, but not via gulp, then check if versions line up to see if user refreshed browser after update (in case API calls changed or something). I am yet to see a proper way to do it, but that's a different question altogether. – VSO Mar 31 '16 at 17:27

4 Answers4

26

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.

VSO
  • 11,546
  • 25
  • 99
  • 187
Wilmer SH
  • 1,417
  • 12
  • 20
  • 1
    I appreciate the reply, upvoted, and will probably end up accepting and asking another question, but I am not looking to bump package.json, I am looking to change a string in a different file. Maybe I am misunderstanding the limitations of gulp. – VSO Mar 31 '16 at 18:39
  • 1
    Gulp is pretty awesome. Expect anything. You may want to look into this: http://stackoverflow.com/a/36335869/4775223 – Wilmer SH Mar 31 '16 at 18:41
  • Thanks - is there some easy way to get the result of my regex - /'productVersion', '(.*)'/g into a var and then work on it? Or does that end up being a plugin? – VSO Mar 31 '16 at 18:45
  • 1
    Here is an idea. Since your package.json is yours, maybe you can have gulp-replace use the package.json version to update your string somewhere else, and still use bump to control your versions. Is not that round about. It would mean adding a pipe to the bump task. – Wilmer SH Mar 31 '16 at 18:45
  • To your last question, maybe this will work: http://stackoverflow.com/q/29770191/4775223 – Wilmer SH Mar 31 '16 at 18:48
  • Thanks, looking through the solutions now. If that works, I might add it to the bottom of your answer before accepting, if you don't mind. The first one is a good idea, but I would rather not go through the package file if I can help it simply because it seems convoluted, though in practice it probably is simpler than what I am trying to do. – VSO Mar 31 '16 at 18:49
  • 1
    Good point. Feel free to edit and add value to the post. I look forward to seeing what you end up with. – Wilmer SH Mar 31 '16 at 18:55
  • I added some stuff, feel free to edit as well if you would like. It's your answer, and it definitely helped a ton. – VSO Mar 31 '16 at 19:42
  • ReferenceError: fs is not defined also ReferenceError: msg is not defined – saber tabatabaee yazdi May 02 '18 at 19:08
4

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;
    }
}
saber tabatabaee yazdi
  • 4,404
  • 3
  • 42
  • 58
Rahul Reddy
  • 695
  • 1
  • 8
  • 14
3

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.

Aras
  • 1,599
  • 15
  • 25
0
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('./'));
});
Michal S.
  • 385
  • 4
  • 6