0

I want to append data to a js file at specific location using ant build

Here is the js file

fun1= function(){
    var data="data1";
}

I want to append one line only if this does not exist in file

data =data+"data2";

inside the fun1. Is there any way to do so as xmltask is specific to XML files only?

2 Answers 2

1

I would use a token replacement. in JS format your string as:

fun1= function(){
    var data="data1 @@@@";
}

and then in ant you can say:

<replace file="script.js" token="@@@@" value="data2"/>

and it will replace the symbols @@@@ with the value data2

just be careful, the replacement is done in place, so don't perform it on your original source code but on a compiled version or, at least, a copy. Otherwise you'll be able to perform the replacement just once.

Sign up to request clarification or add additional context in comments.

2 Comments

but token (say @@@) can occur at multiple places in file. thats why I am appending the js code that is data =data+"data2";
well i guess it's your job to pick the right token. it doesn't have to be a meaningless series of symbols, you can get specific and use something like ${injected.data2} as a token. Very little chance of that being used elsewhere by mistake ...
0

I have solved this using condition

<condition property="pluginEntryExists">
    <resourcecontains resource="js_file_location" substring="data =data+'data2';"/>
</condition>

and based on property set target will be executed

<target name="append-data" unless="${pluginEntryExists}">
    <!-- to support propertyregex include antcontrib.jar -->
    <taskdef resource="net/sf/antcontrib/antcontrib.properties">
        <classpath>
            <pathelement location="./lib/ant-contrib-1.0b3.jar" />
        </classpath>
    </taskdef>

    <loadfile property="configFileData" srcFile="js_file_location" />
    <propertyregex property="pluginList" input="${configFileData}" regexp='var data=".*;' select="\0" />

    <replaceregexp file="js_file_location" match='var data=".*;' replace="${pluginList}data+='data2';" />
</target>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.