Using an variable object inside a Gruntfile - gulp

I'm trying to avoid duplicate code by using a variable object inside a Gruntfile with a set of specified parameters. I apologize if this is declared incorrectly, as I'm not entirely sure how to create an object variable in gruntjs. The goal is to use sonarProperties inside the sonarRunner config. In the if block, add some additional lines, and the else block, just use sonarProperties. Unfortunately my syntax is incorrect. Is this even possible? I'm basing it off of a gulpfile and would like to do something similar.
Sample gulpfile:
const packageName = require('./package.json').name;
gulp.task('sonar', callback => {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
'sonar.projectKey': `microservice:${packageName}`,
'sonar.sourceEncoding': 'UTF-8',
'sonar.login': process.env.SONAR_TOKEN,
// #################################################
// # Javascript Configuration
// #################################################
'sonar.language': 'javascript',
'sonar.sources': 'src',
'sonar.tests': 'test',
'sonar.javascript.lcov.reportPaths': 'coverage/lcov.info',
'sonar.coverage.exclusions': 'src/**/*.spec.js',
};
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
sonarProperties = {
...sonarProperties, // #################################################
// # Github Configuration
// #################################################
'sonar.pullrequest.provider': 'github',
'sonar.pullrequest.branch': process.env.branch,
'sonar.pullrequest.key': process.env.pr_numbers,
'sonar.pullrequest.base': process.env.base_branch,
'sonar.pullrequest.github.repository': process.env.repo,
'sonar.scm.revision': process.env.sha,
};
}
Here's the pertinent points of my gruntfile:
sonarProperties: [{
projectKey: 'microservice:<%= pkg.name %>',
projectName: 'Microservice - <%= pkg.name %>',
sourceEncoding: 'UTF-8',
login: 'admin',
password: 'admin',
host: {
url: 'http://localhost:9000/'
},
language: 'js',
sources: 'js',
tests: 'test',
testExecutionReportPaths: 'test_coverage_reporter/report.xml',
javascript: {
lcov: {
reportPaths: 'test_coverage/lcov.info'
}
},
}],
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sonarRunner: {
analysis: {
options: {
debug: true,
separator: '\n',
sonar: (function() {
if (process.env.SONAR_ANALYSIS_TYPE === 'pr') {
return {
...sonarProperties
moreParams: someData,
};
} else {
return {
// use just sonarProperties
};
}
}())
}
}
}
});

I was able to create the function with the following:
grunt.registerTask('sonar', function () {
let sonarProperties = {
// #################################################
// # General Configuration
// #################################################
..
}
And declaring it as a callback from the beginning as a grunt task.

Related

Merge mixin in vue

I'm working in vue/quasar application.
I've my mixin like this in my view.cshtml
var mixin1 = {
data: function () {
return { data1:0,data2:'' }
}
,
beforeCreate: async function () {
...}
},
methods: {
addformulaire(url) {
},
Kilometrique() { }
}
}
And I want merge with my content in js file (it's to centralize same action an severals cshtml)
const nomeMixins = {
data: function () {
return { loadingcdt: false, lstclt: [], filterclient: [], loadingdoc: false, lstdoc: [], filterdoc: [] }
},
computed: {
libmntpiece(v) { return "toto"; }
},
methods: {
findinfcomplemtX3(cdecltx3, cdedocx3) {
},
preremplissagex3: async function (cdecltx3, cdedocx3) {
}
}
}
};
I want merge this 2 miwin in one. But when I try assign or var mixin = { ...mixin1, ...nomeMixins };
I've only mixin1 nothing about methods,data from my js file nomeMixins but merging failed cause I've same key in my json object. I'm trying to make a foreach but failed too
Someone try to merge to mixin / json object with same key in the case you've no double child property ?
You cant merge mixins in that way. the spread syntax will overwrite keys e.g data, computed, methods etc and final result will not be suitable for your purpose.
refer documentation for adding mixins in your component. Also note that You can easily add multiple mixins in any component, so I don't think combination of two mixins will be any useful.
UPDATE
reply to YannickIngenierie answer and pointing out mistakes in this article
Global Mixins are not declared like this
// not global mixin; on contrary MyMixin is local
// and only available in one component.
new Vue({
el: '#demo',
mixins: [MyMixin]
});
Local Mixins are not declared like this
// NOT local mixin; on contrary its global Mixin
// and available to all components
const DataLoader = Vue.mixin({....}}
Vue.component("article-card", {
mixins: [DataLoader], // no need of this
template: "#article-card-template",
created() {
this.load("https://jsonplaceholder.typicode.com/posts/1")
}
});
Point is refer documentation first before reading any article written by some random guy, including me. Do slight comparison what he is saying whats in documentation.
After working and searching... I find this one And understand that I can add directly mixin in my compoment (don't laught I'm begging with vue few months ago)
my custommiwin.js
const DataLoader = Vue.mixin({
data: function () {
return { loadingcdt: false, lstclt: [], filterclient: [], loadingdoc: false, lstdoc: [], filterdoc: [] }
},
methods: {
filterClt: async function (val, update, abort) {
if (val.length < 3) { abort(); return; }
else {//recherche
this.loadingcdt = true;
let res = await axios...
this.loadingcdt = false;
}
update(() => {
const needle = val.toLowerCase();
this.filterclient = this.lstclt.filter(v => v.libelle.toLowerCase().indexOf(needle) > -1 || v.id.toLowerCase().indexOf(needle) > -1);
})
},
filterDocument: async function (val, update, abort, cdecltx3) {
if (!cdecltx3 || val.length < 3) { abort(); return; }
else {//recherche
this.loadingdoc = true;
let res = await axios({ ...) }
this.loadingdoc = false;
}
update(() => {
const needle = val.toLowerCase();
this.filterdoc = this.lstdoc.filter(v => v.id.toLowerCase().indexOf(needle) > -1);
})
},
}
});
and in my compoment.js I add this
mixins: [DataLoader],
I include all my js file in my cshtml file

typeahead / filter / JSON parse?

Trying to 'parse/read' an external .json file on my typeahead code, but the .json file (which I cannot modify) looks like:
{"**cms_countries**":
[{"**cms_country**":
[{"**countrydisplayname**":"Afghanistan"}
,{"countrydisplayname":"Albania"} ,{"countrydisplayname":"Algeria"}
... ... ... ,{"countrydisplayname":"Zimbabwe"} ] } ,{"TotalRecords":
[ {"TotalRecords":"246"} ] } ] }
So, I think my problem is to know how to parse/read/assimilate/integrate/adopt this .json file, having
cms_countries ,
cms_country ,
and then, my countrydisplayname field on it. (have you seen the tree here ?)
This is my code:
$(document).ready(function() {
var searchablePlaces = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace("countrydisplayname"),
queryTokenizer : Bloodhound.tokenizers.whitespace,
prefetch : 'countries.json',
remote : {
url : 'countries/%QUERY.json',
wildcard : '%QUERY',
filter : function(response) { return response.cms_country; }
},
limit : 10
});
searchablePlaces.initialize();
$('#remote .typeahead').typeahead(
{
hint : true,
highlight : true,
minLength : 2
},
{
name : 'countrydisplayname',
displayKey : "countrydisplayname",
source : searchablePlaces.ttAdapter()
})
});
But of course, it is not working:
ANY hint on how to organize my filter... ? or how to do to overcome my nested .json wrappers....
OK, I've got my code working now:
$(window).load(function(){
var movies = new Bloodhound({
limit: 10,
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'countries.json',
filter: function (movies) {
return $.map(movies.cms_countries[0].cms_country, function (paises) {
return {
value: paises.countrydisplayname
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
//displayKey: 'value',
displayKey: function (toto) {
return toto.value;
},
source: movies.ttAdapter()
});
});

Create a dynamic array for use in grunt concat

I need to concatenate a set files based on variables I have defined my package.json.
// package.json
...
"layouts": [
{
"page": "home",
"version": "a"
},
{
"page": "about",
"version": "a"
},
{
"page": "contact",
"version": "b"
}
]
...
In grunt I am then building these into a JSON array and pumping it into the src parameter in my grunt-concat-contrib task.
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
var paths = JSON.stringify(paths);
grunt.log.write(paths); // Writing this to console for debugging
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...
My issue is that the paths variable is not working inside of the initConfig when it is assigned to JSON.stringify(paths).
If I manually input the array like the following that I copied from where I logged the paths variable to the console, it works!
var paths = ["layouts/home/a/*.php","layouts/about/a/*.php","layouts/contact/b/*.php"];
What am I missing?
Derp. I fixed it, I didn't need to JSON.stringify() the array.
Final working gruntfile is below:
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...

Compressing class names and ids in HTML with Grunt

<div class="aAA J-KU-Jg J-KU-Jg-K9" ></div>
What is the name of this compression method being used by Gmail, and is there a grunt module for it?
This method scans each js, css, and html file, and shortens the class names and ids.
You can give grunt-class-id-minifier a go:
grunt.initConfig({
class-id-minifier: {
simple: {
options: {
jsMapFile: 'tmp/simple/map.js',
jsMapDevFile: 'tmp/simple/map.dev.js',
minifyFilter: function (k, type) {
// type.id type.className
// J_ ignored in minified html
return /^J_/.test(k) ? false : true;
},
jsMapFilter: function (k, type) {
// className ignored in js map
return !!type.id;
}
},
files: [
{
expand: true,
cwd: 'test/fixtures/simple/',
src: '*.{html,css}',
dest: 'tmp/simple/'
}
]
}
}
});
https://www.npmjs.com/package/grunt-class-id-minifier

yeoman generator : repeat a prompt

i'm create a custom yeoman generator, i need create an array base on user responses :
How can i repeat a question and push answer to an array ?
ex :
Add a value ? Y/n
if yes
Value = ?
Add a value ? Y/n
...
for the moment, i have this code :
MyGenerator.prototype.askFor = function askFor() {
var cb = this.async();
console.log(this.yeoman);
var prompts = [
{
type: 'confirm',
name: 'addvalue',
message: 'Add value ?',
default: true
},
{
name: 'myarray',
message: 'Value =',
}
];
this.prompt(prompts, function (props) {
this.addvalue = props.addvalue;
cb();
}.bind(this));
};
Just use a recursive function.
example (won't work as is because of this context):
function askSomething() {
this.prompt({ /* some prompts */ }, function (answers) {
// call the function back if needed
askSomething();
});
}