Tips for Increasing Version Number with Gulp Task

Looking to update the version number in a JavaScript file (myConstantsFile.js) with a new string. Currently, the version number is "01.11.15" and appears like this in myConstantsFile.js along with other constants:

.constant('productVersion', '1.11.15'); 

Currently, the task involves:

gulp.task('increment-version', function(){
    gulp.src(['./somedir/myConstantsFile.js'])
        .pipe(replace(/'productVersion', '(.*)'/g, '99.99.99'))
        .pipe(gulp.dest('./somedir/'));
});

Instead of using direct incrementation code, I am utilizing a constant value.

    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; 

Specifically, I require:

  1. A method to select the current version number in the file via regex.
  2. The location in the code block where the logic can be inserted to increment the number and generate the updated string.

Answer №1

Download and set up gulp-bump

npm install gulp-bump --save-dev

Get yargs

npm install yargs --save-dev

Utilize gulp-bump

var bump = require('gulp-bump');

Utilize yargs

var args = require('yargs').argv;

Create 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'));
});

Note: The following code edit the version number stored in a different location, like 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 details that format my constant in a readable way, but this is the core functionality and it works.

Answer №2

For the past 5 hours, I've been diving into the world of gulp to tackle a task that required my attention. As a complete newbie to gulp, I managed to come up with the following code that does not involve regex expressions. Huge thanks to @VSO and @Wilmer Saint for providing me with a quick starting point. It may seem like a small change, but it made a huge difference for 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
    });

Alternatively, the return code could be modified as follows to update the number in the 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'))) 

The content of my version.js file is simply:

versionBuild = '1.0.8'

In my main function (which loads when the app starts), I used the following code snippet:

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;
    }
}

Answer №3

Try out gulp-bump for an easy and delightful experience :)

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('./'));
  });

Remember to include async before a function, it's necessary.

Answer №4

task('updateVersion', function() {
    var version = JSON.parse(fs.readFileSync(__dirname + '/package.json')).version.split('.');
    var middleNum = parseInt(version[1]);
    var lastNum  = parseInt(version[2]);
    var config = { property: 'version' };

    if(lastNum == 9 && middleNum != 9) {
        lastNum = 0;
        config.updateType = 'minor';
    } else if (middleNum == 9 && lastNum == 9) {
        middleNum = 0;
        config.updateType = 'major';
    }

    gulp.src(__dirname + '/package.json')
    .pipe(updateVersion(config))
    .pipe(gulp.dest('./'));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic Filtering with Reactjs Autocomplete Component (Material UI) using API calls on each input modification

Just starting out with Reactjs and looking to build an Autocomplete component that fetches API data on every input change to update the options. I've been using the Autocomplete component from Material UI but struggling to get it working as expected. ...

Issue encountered while trying to pass updated values from an Angular UI modal back to the parent screen

When I click on an item in a list, I want to open an angularUI modal. I can successfully load the modal, make changes, and return to the main screen. However, I am struggling with updating the list on the main screen after closing the modal. I've trie ...

Iterating through elements with JavaScript and dynamically replacing them in the HTML code

I'm struggling with the code I found on CodePen and need some help with it since I'm not very good with JS. How can I prevent the items from repeating endlessly? Currently, they scroll indefinitely with 20 items per 'page' before the ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

Perform a series of observables from a dynamically generated array

Currently, I am in the midst of a project (Angular2) where I am dynamically creating Observables and storing them in an array. var ObservableArray : Observable<any>[] = []; //populating the Observable array dynamically for (var i = 0; i < this.ma ...

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...

What kind of information is revealed by passing `this` to a function within ng-click?

In a hypothetical scenario, imagine we have a button with an ng-click directive that triggers a function and passes this as an argument. Upon examination, the parameter type is determined to be an object without any element properties or being a jQuery sel ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

What is the process for accessing a website using Java programming language?

Currently, I have a jar file up for sale that requires users to sign up on a particular website in order to download it. My issue lies in wanting to verify if purchasers have a valid login for the site when they run the jar file. Despite my attempts with h ...

Karma test encountered a provider that could not be identified

I am working with a provider called $_ConfigProvider: (function (angular) { angular.module('app') .provider('$_Config', ConfigProvider); function ConfigProvider() { .... //routes definition } ConfigProvider.prot ...

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

The Position of the WebGL Globe Within the Environment

I've been experimenting with the WebGL Globe, and I have successfully made it rotate. However, I'm struggling to figure out how to adjust its position so that it's not centered in the scene. After making changes to the code found at https:/ ...

Inspect the JavaScript file for errors and find a solution to overcome them

Our website's select box has been updated to retrieve city options from a JavaScript array file using an ajax call request. This file is now dynamically created on a different server and then transferred to the static server where it is used to popula ...

What is the best way to navigate to the contact section after clicking on the "Contact Us" button within a modal?

I encountered a challenge in figuring out how to make it so that when I click "Contact us!" on my modal, it would not only close the modal but also scroll to the Contact Us part. However, with the method I currently have, it also scrolls when I press clo ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...

Uncovering design elements from Material UI components

The AppBar component applies certain styles to children of specific types, but only works on direct children. <AppBar title="first" iconElementRight={ <FlatButton label="first" /> }/> <AppBar title="second" iconElementRight={ <di ...

Creating a circular shape around a specific location on a map is a common task in Openlayers. Here's a

I have been attempting to create a circle based on the point/coordinate where a user clicks. While I know how to generate a point and found a function that can create a circle based on said point (similar to a buffer or range ring), it appears to only func ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

The choice between invoking a function within a route handler or employing a middleware for the task

I am currently exploring a potential difference in coding approaches. Let me illustrate this with an example excerpted from the express documentation: https://expressjs.com/en/guide/using-middleware.html function logOriginalUrl (req, res, next) { console ...