How should I move or delete files in a Yeoman Generator? - yeoman

I'm building a generator that in part includes scaffolding from another project created with exec. Depending on user input I need to move or delete parts of this scaffolding.
Right now I'm doing it with node's fs.child_process.spawn and shelljs, but seeing as the Yo generator has mkdir, write, template, and copy, I'm wondering if there's a Yo way to move or delete files and directories.

I just use rimraf like this:
MyGenerator.prototype.removeDir = function removeDir () {
var cb = this.async(),
self = this;
rimraf('path/to/dir', function () {
self.log.info('Removing dir');
cb();
});
};
Remember to add rimraf as a dependency in your package.json file. Not sure if there's a built-in function for this but this one's been working fine for me so far.

Yeoman now supports this via the fs API, which is an in memory filesystem implementation.
this.fs.move('source/file', 'dest/file');
this.fs.copy('source', 'dest');
File System Docs

Still not documented, but this is the delete method (works for me):
this.fs.delete('file/to/delete');
Link: Yeoman issue 1505

Related

Flutter ZipFile.extractToDirectory doesn't overwrite existing files on iOS

I am using flutter_archive 4.0.1 (just updated to 4.1.1) and attempting to unzip a file into an existing directory.
My scenario is that I am backing up this folder, sending to a web server, then at some point, I will want to restore into the same folder. This folder will have many files that are the same filenames as in the zip. I need to overwrite the local files with the ones in the zip.
This works perfect on Android. iOS has always had problems when it comes to working with Zip files.
The extractToDirectory does not have an overwrite switch, so I attempted to use the onExtracting, to check if the file already exists locally, delete the local one, then allow the zip one to take its place.
The problem I am experiencing is that to check if it exists, and to delete, I have to use a Future, but as they are async, I cannot get them to synchronise.
Here is what I have tried.
if (Platform.isIOS) {
await ZipFile.extractToDirectory(
zipFile: zipFile,
destinationDir: destinationDir,
onExtracting: (zipEntry, progress) {
exists(zipEntry.name).then((value) {
if (value) {
deleteFile(zipEntry.name).then((value) {
return ZipFileOperation.includeItem;
});
} else {
return ZipFileOperation.includeItem;
}
});
return ZipFileOperation.includeItem;
}
);
}
Both exists and deleteFile are local Futures, that uses the File functionality.
What I have tried, is that the zipEntry.name will be the same as the file I need to overwrite, so this aspect should work fine. It is now just trying to make things work in order.
The Android version is the same, apart from it does not have the onExtracting functionality.
Not sure if you have found the answer or even if there is a good answer. I ran into this issue myself, and it seems the alternative is delete the target dir before unzipping. There seems no override option for unzip. Here is some snip bits about deletion (as also suggested by the package's unit test code):
final _appDataDir = Directory.systemTemp; //from dart.io
final destinationDir = Directory("${_appDataDir.path}/unzip");
if (destinationDir.existsSync()) {
print("Deleting existing unzip directory: ${destinationDir.path}");
destinationDir.deleteSync(recursive: true);
}
Hope this solution helps others who may have similar issues.

Using NPM/Bower over Nuget MVC Site with bundling

I am trying to train myself on the new preferred way of referencing Front-end libraries in .Net Applications, so I have started to read into doing this with Gulp. I have read this article on replacing the Nuget packages with ones from bower
https://blogs.msdn.microsoft.com/cdndevs/2015/02/17/using-bower-with-visual-studio/
And this one to use Gulp
http://www.davepaquette.com/archive/2014/10/08/how-to-use-gulp-in-visual-studio.aspx
However I am having some trouble putting it all together. I want together some process that will not only replace all the Pre-Installed Nuget packages with bower packages, but also minify and bundle them with gulp instead of using the Web.Optimization library. The first link walks through doing that, but the gulp script is not providing the output I would expect (no dist folders for instance). This SO question has some good answers, but I am not seeing how I bundle all the libraries from bower (I read through all the comments and answers).
Using Grunt, Bower, Gulp, NPM with Visual Studio 2015 for a ASP.NET 4.5 Project
Obviously this stuff is new to me so I will get confused, but I want to make sure I do it the right way.
I am using Visual Studio 2015 and am creating a new MVC 4.5.2 Application, and I want to have all front-end libraries referenced and bundled/minified without using any .Net libraries. It seems at this point far easier to do it the old way
The question is a little broad but Ill hit on the key points since I've been doing this exact thing for a few weeks now.
Break what you are doing into two phases - replacing packages from nuget as phase one and replacing the .net bundling as the other.
Phase one - pretty simple actually, remove (uninstall) all the packages you have from nuget that have bower equivalents, then add those packages via the bower commands (don't forget to --save and --save-dev where needed). Then replace your script locations in the .net bundling with the new locations in bower_components. Once you can confirm your site works under this new layout while still using .net bundling you are ready for phase two.
Now for phase two, first and formost you need to learn the concept of 'globs' which are basically wild card based include and excludes for files in gulp. Probably the single most helpful thing I've found to help with this is the gulp plugin main-bower-files. So to create a good glob to start with I had this...
var paths = {};
paths.baseReleaseFolder = "app";
paths.baseJSReleaseFile = "site.min.js";
paths.jsSource = mainBowerFiles();//this gets all your bower scripts in an array
.concat([
"node_modules/angular/angular.js",//my angular is loaded via npm not bower because the bower version was giving me dependency issues (bug)
"node_modules/angular-route/angular-route.js",
"Source/output.js",//generated by MY typescript compiler
"!/Scripts", //this is an exclude
"!**/*.min.js" //also an exclude
]);
This is basically saying I want to select all the DISTRO bower plugins files needed to run whatever, include my angular js, and exclude anything in my scripts folder (typescript files and outputs) and exclude any ALREADY minified files (I want to do it all myself as one concatenated file).
Now I separate the js and css operations and wrap another event to call both so I end up with
gulp.task("min", ["min:js", "min:css"]);
gulp.task("min:js", function () {});
gulp.task("min:css", function () {});
Now as an example of how that works I have the following in my min:js
gulp.task("min:js", function () {
var jsFilter = filter('**/*.js', { restore: true });//extra file safty incase my glob is getting non js files somehow
return gulp
.src(paths.jsSource) //this is the 'glob' IE the file selector
.pipe(jsFilter) //enforce my filter from above (gulp-filter)
//.pipe(debug()) //useful to output what files are in use (gulp-debug)
.pipe(sourcemaps.init({loadMaps:true})) //create sourcemaps for final output(gulp-sourcemaps)
.pipe(uglify()) //min and ugilfy files on the way to next step (gulp-uglify)
.pipe(concat(paths.baseReleaseFolder + "/" + paths.baseJSReleaseFile)) //this takes all the files in the glob and creates a single file out of them in app/site.min.js
.pipe(rev()) //ignore this, cache-busting but requires work on the .net side to load the files, basically adds the file hash to the file name in the output
.pipe(sourcemaps.write(".")) //actually write my .map.js file to the final destination
.pipe(gulp.dest(".")) //write the final site.min.js to its location
.pipe(jsFilter.restore); //not sure but all filter examples do this.
});
So when this is all said and done I end up with a single site.min.js file in the 'app' folder that is the concatenated, minified, uglified version off all my bower components (and whatever else the glob hit). Now just to give you an idea on how plugin intensive using gulp is this is the declaration of all plugins I load into my main gulp script to do bascailly what .net bundling does for you....
var gulp = require('gulp'),
rimraf = require("gulp-rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
debug = require("gulp-debug"),
uglify = require("gulp-uglify"),
filter = require("gulp-filter"),
rename = require("gulp-rename"),
rev = require('gulp-rev'),
sourcemaps = require('gulp-sourcemaps'),
csslint = require('gulp-csslint'),
jslint = require('gulp-jslint'),
typescript = require("gulp-typescript"),
tslint = require("gulp-tslint"),
runSequence = require('run-sequence'),
mainNodeFiles = require("npm-main-files"),
mainBowerFiles = require('main-bower-files');
You probably don't need all of these (some are typescript, some are linters)
Edit: Heres my css function
gulp.task("min:css", function () {
var cssFilter = filter('**/*.css', { restore: true });
return gulp
.src(paths.cssSource)
.pipe(cssFilter)
//.pipe(debug())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(concat(paths.baseReleaseFolder + "/" + paths.baseCSReleaseFile))
.pipe(cssmin())
.pipe(rev())
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("."))
.pipe(cssFilter.restore);
});

Grep a file and save the result to variable synchronously using Gulp

I have this case. I need to grep a file for some RegEx and the result string (or array of strings) I need to save to variable for later use. And this has to be achieved using Gulp.
It should look like this in my idea:
var line;
gulp.task('grep', function(callback) {
line = someCoolSyncFunction('/needle/', './haystack.txt');
callback();
});
gulp.task('useIt', ['grep'], function() {
console.log(line);
});
Important is this someCoolSyncFunction to be synchronous and to handle file on physical/virtual file system, not the Vinyl file.
Is there a way to do this using Gulp? Or any other approach to achieve similar effect?
PS: to explain the reason, I need to extract version number from Debian package changelog and insert it to configuration file inside the package during the build process.
Thanks a lot.
Vit

casperjs: how to include other javascript files during unit tests in tests themselves?

I am doing some unit test in casperjs and I got stuck: how do include dependency file from the test itself? Included javascript file can be just a bunch of functions, and does not declare any interface (module.exports = ... etc).
I know I can include from the command line
$ casperjs test --include=./my-mock.js mytest.js
but how can I include files from the test itself?
Putting following on the top does not work for me... my_mock is undefined
casper.options.clientScripts = ["./my-mock.js"]; //push() does not help either
//mytest.js is below
// ------------------------------------------
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
test.assertEquals( ......);
test.done();
});
// ------------------------------------------
CasperJS version 1.1.0-DEV using phantomjs version 1.9.1
Using phantom.injectJs method is the best option I've found so far. E.g. you're having two files in your directory: "tests.js" and "settings.js". You want to include "settings.js" into "test.js". The first thing you should do with your "test.js" is write the following:
phantom.injectJs('settings.js');
casper.test.begin(...
...
The reason that clientScripts isn't working is that it is loaded on each page load, so you don't have access to the objects/functions defined in the file outside of a casper.evaluate() call.
You can use require() to pull in modules, however you may need to modify your included script to work with this method.
Here is what I changed your mytest.js to:
var my_mock = require('my-mock');
casper.test.begin('ajax mock test', function suite(test) {
my_mock.setFetchedData("bla");
my_mock.doRequest();
//test.assertEquals( ... );
test.done();
});
And this is a quick script (my-mock.js) that I threw together to print out when you use the functions you provided.
module.exports = {
setFetchedData: function(a) {
console.log('setFetchedData: ' + a);
},
doRequest: function() {
console.log('doRequest');
}
};
I found useful this sample demonstrating --includes option:
$ casperjs test tests/ --pre=pre.js --includes=inc.js --post=post.js
to load functions that you often use in your tests.

how to set the path to where aapt add command adds the file

I'm using aapt tool to remove some files from different folders of my apk. This works fine.
But when I want to add files to the apk, the aapt tool add command doesn't let me specify the path to where I want the file to be added, therefore I can add files only to the root folder of the apk.
This is strange because I don't think that developers would never want to add files to a subfolder of the apk (res folder for example). Is this possible with aapt or any other method? Cause removing files from any folder works fine, and adding file works only for the root folder of the apk. Can't use it for any other folder.
Thanks
The aapt tool retains the directory structure specified in the add command, if you want to add something to an existing folder in an apk you simply must have a similar folder on your system and must specify each file to add fully listing the directory. Example
$ aapt list test.apk
res/drawable-hdpi/pic1.png
res/drawable-hdpi/pic2.png
AndroidManifest.xml
$ aapt remove test.apk res/drawable-hdpi/pic1.png
$ aapt add test.apk res/drawable-hdpi/pic1.png
The pic1.png that will is added resides in a folder in the current working directory of the terminal res/drawable-hdpi/ , hope this answered your question
There is actually a bug in aapt that will make this randomly impossible. The way it is supposed to work is as the other answer claims: paths are kept, unless you pass -k. Let's see how this is implemented:
The flag that controls whether the path is ignored is mJunkPath:
bool mJunkPath;
This variable is in a class called Bundle, and is controlled by two accessors:
bool getJunkPath(void) const { return mJunkPath; }
void setJunkPath(bool val) { mJunkPath = val; }
If the user specified -k at the command line, it is set to true:
case 'k':
bundle.setJunkPath(true);
break;
And, when the data is being added to the file, it is checked:
if (bundle->getJunkPath()) {
String8 storageName = String8(fileName).getPathLeaf();
printf(" '%s' as '%s'...\n", fileName, storageName.string());
result = zip->add(fileName, storageName.string(),
bundle->getCompressionMethod(), NULL);
} else {
printf(" '%s'...\n", fileName);
result = zip->add(fileName, bundle->getCompressionMethod(), NULL);
}
Unfortunately, the one instance of Bundle used by the application is allocated in main on the stack, and there is no initialization of mJunkPath in the constructor, so the value of the variable is random; without a way to explicitly set it to false, on my system I (seemingly deterministically) am unable to add files at specified paths.
However, you can also just use zip, as an APK is simply a Zip file, and the zip tool works fine.
(For the record, I have not submitted the trivial fix for this as a patch to Android yet, if someone else wants to the world would likely be a better place. My experience with the Android code submission process was having to put up with an incredibly complex submission mechanism that in the end took six months for someone to get back to me, in some cases with minor modifications that could have just been made on their end were their submission process not so horribly complex. Given that there is a really easy workaround to this problem, I do not consider it important enough to bother with all of that again.)

Resources