How to correctly get gulp.src globs from a variable? - variables

Given the following Gulp setup
const { src, dest } = require('gulp');
var zip = require('gulp-zip');
var pkgDist = 'packages/';
function pkg(done) {
src(['./**', '!node_modules/**', '!vendor/**', '!.gitignore', '!*.json', '!*.lock'], {base: '..'})
.pipe(zip('archive.zip'))
.pipe(dest(pkgDist))
done();
};
exports.pkg = pkg;
how can I modify it in order to get src globs from a variable, i.e. pkgSrc, something like this:
[...]
var pkgSrc = <what to put here?>;
[...]
src(pkgSrc)
[...]
I've tried to use this var pkgSrc = " ['./**', '!node_modules/**', '!vendor/**', '!.gitignore', '!*.json', '!*.lock'], {base: '..'} "; but it doesn't work.
If it's easier, I'm also open to solutions that result into this src([pkgSrc], {base: '..'})

You can go with just:
var pkgSrc = ['./**', '!node_modules/**', '!vendor/**', '!.gitignore', '!*.json', '!*.lock']
gulp.src first argument can be a string or an array, so now it is an array above.
The second argument is an object of options. Include the options sepearately: {base: '..'} so
src(pkgSrc, {base: '..'})

Related

Commands URIs pass parameters

The following example. How to pass parameters to the corresponding command?
const commentCommandUri = vscode.Uri.parse(`command:editor.action.addCommentLine`);
const contents = new vscode.MarkdownString(`[Add comment](${commentCommandUri})`);
contents.isTrusted = true;
The command editor.action.addCommentLine does not take any parameter. It simply comments the line that is selected currently in the editor (or the line where the cursor is positioned).
If you had another command that accepted arguments, then you could do something like this:
...
const arguments = [arg1, arg2];
const myCommandUri = Uri.parse(`command:myCommand?${encodeURIComponent(JSON.stringify(arguments))}`);
contents.appendMarkdown(`[Do something](${myCommandUri})`);

Getting error for variable does not exist in current context cshtml?

i have following code for getting error
$('#Template').click(function () {
var selectedTempleteType = $('#BulkLoadActionDropDownId option:selected').val();
var path = '#Url.Content("~/Upload/DownloadBulkLoadActionTemplate?templateType=" + selectedTempleteType)';
$(this).attr("href", path);
});
error showing for "selectedTempleteType".
selectedTempleteType is a client-side JS variable, you cannot use it inside #Url.Content() which runs server-side (and #Url.Content() is incorrect to map URL path with query string, use #Url.Action() instead). You should change from this:
var path = '#Url.Content("~/Upload/DownloadBulkLoadActionTemplate?templateType=" + selectedTempleteType)';
to this one:
var path = '#Url.Action("DownloadBulkLoadActionTemplate", "Upload")?templateType=' + selectedTempleteType;
Or using placeholder inside #Url.Action() with replace() in client-side:
var path = '#Url.Action("DownloadBulkLoadActionTemplate", "Upload", new { templateType = "xxxx" })';
path = path.replace("xxxx", selectedTempleteType);

Why does Ramda work in this example where native Array.map or Lodash do not?

In the process of writing an example for this SO question, this question came up:
Why does the native Array.map throw an error when used like this:
[tmp1, tmp2].map(fs.createReadStream)
.forEach(stream => stream.pipe(jsonStream));
fs.js:1664
throw new TypeError('"options" argument must be a string or an object');
^
TypeError: "options" argument must be a string or an object
at new ReadStream (fs.js:1664:11)
at fs.createReadStream (fs.js:1649:10)
at Array.map (native)
Similarly with lodash… but it works fine with ramda.
// Same error:
_.map([tmp1, tmp2], fs.createReadStream)
.forEach(stream => stream.pipe(jsonStream));
// Works fine:
R.map(fs.createReadStream, [tmp1, tmp2])
.forEach(stream => stream.pipe(jsonStream));
Note, this is the full code from referenced question:
var fs = require('fs');
var path = require('path');
var JSONStream = require('JSONStream');
var tmp1 = path.join(__dirname, 'data', 'tmp1.json');
var tmp2 = path.join(__dirname, 'data', 'tmp2.json');
var jsonStream = JSONStream.parse();
jsonStream.on('data', function (data) {
console.log('---\nFrom which file does this data come from?');
console.log(data);
});
[tmp1, tmp2].map(p => {
return fs.createReadStream(p);
}).forEach(stream => {
stream.pipe(jsonStream);
});
The second argument of fs.createReadStream should be undefined no?
This is most likely due to Array.prototype.map and _.map passing three arguments to the provided mapping function (the value, the index and the collection), while R.map only passes the value.
In your example, fs.createReadStream is being given the array index as its second argument where it expects an options object or string instead, causing the "options" argument must be a string or an object error. If you want to use Array.prototype.map or _.map in this way, you'll need to wrap the method call in a function to prevent the extra arguments:
[tmp1, tmp2].map(p => fs.createReadStream(p))

append (query string) parameters to the current url

In express,
Suppose I'm at http://localhost:3000/search?q=foo&sort=asc
In my template, how can I print a link (say a next pagination link) with additional parameters:
search.dust
<a rel="next" href="{! append page=2 !}">Next results</a>
--
Of course, I could:
<a rel="next" href="{currentUrl}&page=2">Next results</a>
but it would not work when I'm at http://localhost:3000/search, because of the ?/& issue.
Thank you
I made a dust helper for this. I called it {#query} and here is its signature:
{#query string="que=ry&str=ing"/}
It merges que=ry&str=ing with actual req.query parameters, thus in the previous example where we were on http://localhost:3000/search?q=foo&sort=asc:
<a rel="next" href="?{#query string="page=2"/}">Next</a>
will output:
<a rel="next" href="?q=foo&sort=asc&page=2">Next</a>
--
The implementation is as followed (inside a middleware to have access to req.query):
var dust = require('dustjs-linkedin');
var _ = require('underscore');
var qs = require('querystring');
app.use(function(req, res, next) {
//
// Query helper for dust
//
// Merge querystring parameters to the current req.query
//
// Suppose we are on localhost:3000/search?q=foo :
// - {#query string=""/} will output q=foo
// - {#query string="bar=baz"/} will output q=foo&bar=baz
// - {#query string="q=fooo&bar=baz"/} will output q=fooo&bar=baz (notice fooo takes precedence)
//
dust.helpers.query = function (chunk, ctx, bodies, params) {
var str = dust.helpers.tap(params.string, chunk, ctx);
// Parse string="" parameter
var o = qs.parse(str);
// Merge with req.query
o = _.extend({}, req.query, o);
return chunk.write(qs.stringify(o));
}
next();
});

Adobe AIR NativeProcess fails with spaces in arguments?

I have a problem running the NativeProcess if I put spaces in the arguments
if (Capabilities.os.toLowerCase().indexOf("win") > -1)
{
fPath = "C:\\Windows\\System32\\cmd.exe";
args.push("/c");
args.push(scriptDir.resolvePath("helloworld.bat").nativePath);
}
file = new File(fPath);
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = file;
args.push("blah");
nativeProcessStartupInfo.arguments = args;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
in the above code, if I use
args.push("blah") everything works fine
if I use
args.push("blah blah") the program breaks as if the file wasn't found.
Seems like I'm not the only one:
http://tech.groups.yahoo.com/group/flexcoders/message/159521
As one of the users their pointed out, it really seems like an awful limitation by a cutting edge SDK of 21st century. Even Alex Harui didn't have the answer there and he's known to workaround every Adobe bug:)
Any ideas?
I am using AIR 2.6 SDK in JavaScript like this, and it is working fine even for spaces.
please check your code with this one.
var file = air.File.applicationDirectory;
file = file.resolvePath("apps");
if (air.Capabilities.os.toLowerCase().indexOf("win") > -1)
{
file = file.resolvePath(appFile);
}
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = file;
var args =new air.Vector["<String>"]();
for(i=0; i<arguments.length; i++)
args.push(arguments[i]);
nativeProcessStartupInfo.arguments = args;
process = new air.NativeProcess();
process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(air.ProgressEvent.STANDARD_INPUT_PROGRESS, inputProgressListener);
process.start(nativeProcessStartupInfo);
To expand on this: The reason that this works (see post above):
var args =new air.Vector["<String>"]();
for(i=0; i<arguments.length; i++)
args.push(arguments[i]);
nativeProcessStartupInfo.arguments = args;
is that air expects that the arguments being passed to the nativeProcess are delimited by spaces. It chokes if you pass "C:\folder with spaces\myfile.doc" (and BTW for AIR a file path for windows needs to be "C:\\folder with spaces\\myfile.doc") you would need to do this:
args.push("C:\\folder");
args.push("with");
args.push("spaces\\myfile.doc");
Hence, something like this works:
var processArgs = new air.Vector["<String>"]();
var path = "C:\\folder with spaces\\myfile.doc"
var args = path.split(" ")
for (var i=0; i<args.length; i++) {
processArgs.push(args[i]);
};
UPDATE - SOLUTION
The string generated by the File object by either nativePath or resolvePath uses "\" for the path. Replace "\" with "/" and it works.
I'm having the same problem trying to call 7za.exe using NativeProcess. If you try to access various windows directories the whole thing fails horribly. Even trying to run command.exe and calling a batch file fails because you still have to try to pass a path with spaces through "arguments" on the NativeProcessStartupInfo object.
I've spent the better part of a day trying to get this to work and it will not work. Whatever happens to spaces in "arguments" totally destroys the path.
Example 7za.exe from command line:
7za.exe a MyZip.7z "D:\docs\My Games\Some Game Title\Maps\The Map.map"
This works fine. Now try that with Native Process in AIR. The AIR arguments sanitizer is FUBAR.
I have tried countless ways to put in arguments and it just fails. Interesting I can get it to spit out a zip file but with no content in the zip. I figure this is due to the first argument set finally working but then failing for the path argument.
For example:
processArgs[0] = 'a';
processArgs[1] = 'D:\apps\flash builder 4.5\project1\bin-debug\MyZip.7z';
processArgs[2] = 'D:\docs\My Games\Some Game Title\Maps\The Map.map';
For some reason this spits out a zip file named: bin-debugMyZip.7z But the zip is empty.
Whatever AIR is doing it is fraking up path strings. I've tried adding quotes around those paths in various ways. Nothing works.
I thought I could fall back on calling a batch file from this example:
http://technodesk.wordpress.com/2010/04/15/air-2-0-native-process-batch-file/
But it fails as well because it still requires the path to be passed through arguments.
Anyone have any luck calling 7z or dealing with full paths in the NativeProcess? All these little happy tutorials don't deal with real windows folder structure.
Solution that works for me - set path_with_space as "nativeProcessStartupInfo.workingDirectory" property. See example below:
public function openPdf(pathToPdf:String):void
}
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("C:\\Windows\\System32\\cmd.exe");
nativeProcessStartupInfo.executable = file;
if (Capabilities.os.toLowerCase().indexOf("win") > -1)
{
nativeProcessStartupInfo.workingDirectory = File.applicationDirectory.resolvePath(pathToPdf).parent;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "/k";
processArgs[1] = "start";
processArgs[2] = "test.pdf";
nativeProcessStartupInfo.arguments = processArgs;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
}
args.push( '"blah blah"' );
Command line after all supports spaces if they are nested whithin "".
So if lets say you have a file argument :
'test/folder with space/blah'
Convert it to the following
'test/"folder with space"/blah'
Optionally use a filter:
I once had a problem like this in AIR, i just simply filter the text before i push it into the array. My refrence use CASA lib though
import org.casalib.util.ArrayUtil;
http://casalib.org/
/**
* Filters a string input for 'safe handling', and returns it
**/
public function stringFilter(inString:String, addPermitArr:Array = null, permitedArr:Array = null):String {
var sourceArr:Array = inString.split(''); //Splits the string input up
var outArr:Array = new Array();
if(permitedArr == null) {
permitedArr = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" as String).split('');
}
if( addPermitArr != null ) {
permitedArr = permitedArr.concat( addPermitArr );
}
for(var i:int = 0; i < sourceArr.length; i++) {
if( ArrayUtil.contains( permitedArr, sourceArr[i] ) != 0 ) { //it is allowed
outArr.push( sourceArr[i] );
}
}
return (outArr.join('') as String);
}
And just filter it via
args.push( stringFilter( 'blah blah', new Array('.') ) );
Besides, it is really bad practice to use spaces in file names / arguments, use '_' instead. This seems to be originating from linux though. (The question of spaces in file names)
This works for me on Windws7:
var Xargs:Array = String("/C#echo#a trully hacky way to do this :)#>#C:\\Users\\Benjo\\AppData\\Roaming\\com.eblagajna.eBlagajna.POS\\Local Store\\a.a").split("#");
var args:Vector.<String> = new Vector.<String>();
for (var i:int=0; i<Xargs.length; i++) {
trace("Pushing: "+Xargs[i]);
args.push(Xargs[i]);
};
NPI.arguments = args;
If your application path or parameter contains spaces, make sure to wrap it in quotes. For example path of the application has spaces C:\Program Files (x86)\Camera\Camera.exe use quotes like:
"C:\Program Files (x86)\Camera\Camera.exe"