iamricard / gulp-cordova

[UNMAINTAINED] Very simple plugin to run cordova commands with a simple interface from gulp
http://npm.im/gulp-cordova
MIT License
23 stars 8 forks source link

pain if you need to run in different cwd #4

Closed aintnorest closed 9 years ago

aintnorest commented 9 years ago

So I use the non json way to run commands. First the commands trigger done when they aren't done which isn't a huge deal i use set timeouts to deal with that although not ideal it works. My biggest problem is i have to change the current working directory to do my builds and emulates but then it doesn't tell me when its done so i can properly set it back. What I have here works but only if I don't save twice within 12 seconds of each other, really not optimal. Thanks for any help.

var gulp = require('gulp');
/* UTILITY REQUIRES */
var notify      = require('gulp-notify');
var runSequence = require('run-sequence');
var watchGlob   = require('watch-glob');
var browserSync = require('browser-sync');
var changed     = require('gulp-changed');
var webpack     = require('webpack');
var git         = require('gulp-git');
var cordova     = require('gulp-cordovacli');
/* HTML, SASS, & CSS REQUIRES */
var minifyHTML = require('gulp-minify-html');
var sass       = require('gulp-sass');
var csso       = require('gulp-csso');
var prefix     = require('gulp-autoprefixer');
var concatCss  = require('gulp-concat-css');
//SOURCE LOCATIONS
var rootSRC = 'src/';
var htmlSRC = 'src/index.html';
var sassSRC = 'src/styles/scss/*.scss';
var cssSRC  = 'src/styles/css';
//BUILD LOCATIONS
var rootBLD = "wearshare/www";
var cssBLD = "wearshare/www/styles";

//AUTOPREFIXER SET YOUR BROWSER REQ.
var AUTOPREFIXER_BROWSERS = [
    'last 2 versions'
];

/* Function to Handle Errors Using Notify */
function handleError(err) {
    console.log(err.toString());
    notify().write(err);
    if(this.emit)this.emit('end');
};

/* TASKS TO MOVE FILES */
gulp.task('copyImages', function () {
  return gulp.src('src/imgs/*.*')
    .pipe(gulp.dest(rootBLD + '/imgs'));
});
gulp.task('copyFonts', function () {
  return gulp.src("src/styles/fonts/**/*.*")
    .pipe(gulp.dest(cssBLD));
});
/* MINIFY HTML */
gulp.task("htmlMin", function () {
     return gulp.src(htmlSRC)
        .pipe(minifyHTML({conditionals:true,comments:true}))
        .on('error', handleError)
        .pipe(gulp.dest(rootBLD))
});

/* SASS TO CSS, IMPORT ALL MODULES FROM FOLDERS INTO A SCSS FILE AT THE BASE LEVEL. */
gulp.task("sass", function () {
    return gulp.src(sassSRC)
      .pipe(changed(cssSRC))
      .pipe(sass({
            errLogToConsole: false,
            onError: function(err) {
                return notify().write(err);
            }
        }))
        .pipe(gulp.dest(cssSRC))
        .pipe(notify({ message: 'Sass Compiled! File:<%= file.relative %>'}));
});
/* TAKES THE CSS CONCATS, THEN UNCSS, THEN AUTOPREFIXES, LASTLY USES CSSO TO MINIFY. */
gulp.task("css", function () {
    return gulp.src(cssSRC + '/*.css')
        .pipe(concatCss("main.min.css"))
        .on('error', handleError)
        .pipe(prefix(AUTOPREFIXER_BROWSERS))
        .on('error', handleError)
        .pipe(csso())
        .on('error', handleError)
        .pipe(gulp.dest(cssBLD));
});

/* WEBPACK */
gulp.task('bundle', function(){
    var compiler = webpack({
      entry: "./src/js/main.js",
      devtool: "source-map",
      output: {
          path: "./wearshare/www/js/",
          filename: "main.min.js"
      }
    });

    compiler.run(function(err, stats) {
        if(err) handleError(err);
        if(stats) handleError(stats);
        console.log("STATS: ",stats.compilation.errors);
    });
});
//
gulp.task('zip', function(){
    var compiler = webpack({
      entry: "./src/js/main.js",
      devtool: "source-map",
      output: {
          path: "./wearshare/www/js/",
          filename: "main.min.js"
      },
      plugins: [
        new webpack.optimize.UglifyJsPlugin({minimize: true})
      ]
    });

    compiler.run(function(err, stats) {
        if(err) handleError(err);
        if(stats) handleError(stats);
    });
});

gulp.task('reload', function() {
    setTimeout(function(){
        browserSync.reload();
        console.log("dir:",__dirname);
    },6000);
});

var initOnce = false;

gulp.task('cordovaBuild', function() {
  process.chdir("./wearshare");
  console.log(__dirname);
    gulp.src('./').pipe(cordova(['build']));
});
gulp.task('cordovaEmulateIOS', function() {
  setTimeout(function(){
    process.chdir("./wearshare");
    console.log(__dirname);
    gulp.src('./').pipe(cordova(['emulate','ios']));
    setTimeout(function(){
      process.chdir(__dirname);
    },2000);
  },6000);
});

/* GULP WATCH */
gulp.task("watch", function() {
  browserSync({
      notify: true,
      server: {
          baseDir: "wearshare/platforms/browser/www"
      }
    });

  /* WATCH JAVASCRIPT */
  watchGlob(['src/js/*.js', 'src/js/**/*.js', 'src/js/**/**/*.js', 'node_modules/famous/src/**/*.js','node_modules/AtomicFramework/*.js'], { callbackArg: 'relative' }, function(filePath) {
      runSequence(['bundle']);
  });
  /* WATCH END */
  watchGlob(['wearshare/www/js/main.min.js'], { callbackArg: 'relative' }, function(filePath) {
      runSequence(["cordovaBuild"],["cordovaEmulateIOS"],['reload']);
  });
  /* WATCH SASS */
  watchGlob(['src/styles/scss/*.scss'], { callbackArg: 'relative' }, function(filePath) {
      runSequence(['sass']);
  });
  /* WATCH CSS */
  watchGlob(['src/styles/css/*.css'], { callbackArg: 'relative' }, function(filePath) {
      runSequence(['css'],["cordovaBuild"],["cordovaEmulateIOS"],['reload']);
  });

});

/* GULP GIT */
gulp.task('cloneAtomic', function(){
    git.clone('https://github.com/aintnorest/AtomicFramework',{cwd:"node_modules/"}, function (err) {
      if (err) throw err;
   });
});
gulp.task('cloneFamous', function(){
    git.clone('https://github.com/aintnorest/famous.git',{cwd:"node_modules/"}, function (err) {
      if (err) throw err;
    });
});
gulp.task('cloneFamousFlex', function(){
    git.clone('https://github.com/vizidrix/famous-flex.git',{cwd:"node_modules/"}, function (err) {
      if (err) throw err;
    });
});
gulp.task('clonePostal', function(){
    git.clone('https://github.com/aintnorest/postal.js.git',{cwd:"node_modules/"}, function (err) {
      if (err) throw err;
    });
});
//PULL
gulp.task('pullAtomic', function(){
    git.pull('origin','master',{cwd:"node_modules/AtomicFramework"}, function (err) {
      if (err) throw err;
    });
});
gulp.task('pullFamous', function(){
    git.pull('origin','master',{cwd:"node_modules/famous"}, function (err) {
      if (err) throw err;
    });
});
gulp.task('pullFamousFlex', function(){
    git.pull('origin','master',{cwd:"node_modules/famous-flex"}, function (err) {
      if (err) throw err;
    });
});
gulp.task('pullPostal', function(){
    git.pull('origin','master',{cwd:"node_modules/postal.js"}, function (err) {
      if (err) throw err;
    });
});
//
/* CORDOVA TASKS */
//INIT CORDOVA
gulp.task('cordovaCreate', function() {
    gulp.src('./package.json')
      .pipe(cordova(['create','wearshare','com.example.wearshare','WearshareMobile']));
});
//PLATFORM CORDOVA
gulp.task('cordovaPlatform', function() {
    gulp.src('./').pipe(cordova(['platform','add',"ios","browser"]));
});
//PLUGINS CORDOVA
gulp.task('cordovaPlugin-console', function() {
    process.chdir('./wearshare');
    gulp.src('./').pipe(cordova(['plugin','add',"org.apache.cordova.console"]));
});
gulp.task('cordovaPlugin-camera', function() {
    gulp.src('./').pipe(cordova(['plugin','add',"org.apache.cordova.camera"]));
});
gulp.task('cordovaPlugin-statusbar', function() {
    gulp.src('./').pipe(cordova(['plugin','add',"org.apache.cordova.statusbar"]));
});
gulp.task('cordovaPlugin-inAppBrowser', function() {
    gulp.src('./').pipe(cordova(['plugin','add',"org.apache.cordova.inappbrowser"]));
});
gulp.task('cordovaPlugin-keyboard', function() {
    gulp.src('./').pipe(cordova(['plugin','add',"https://github.com/driftyco/ionic-plugins-keyboard"]));
});

//
/* TOP LEVEL TASKS */
gulp.task('init',function(){
    runSequence(['cloneAtomic','cloneFamous','cloneFamousFlex','clonePostal','cordovaCreate']);
    setTimeout(function(){
      runSequence(["cordovaPlugin-console"],["cordovaPlugin-camera"],["cordovaPlugin-statusbar"],["cordovaPlugin-inAppBrowser"],["cordovaPlugin-keyboard"]);
    },32000);
    setTimeout(function(){
      runSequence(["cordovaPlatform"]);
    },60000);

});
gulp.task('build', function() {
  runSequence(['htmlMin', 'copyImages', 'copyFonts', 'sass'],['css','zip']);
});

gulp.task('update',function(){
  runSequence(['pullAtomic','pullFamous','pullFamousFlex','pullPostal']);
});

gulp.task('default', function() {
  runSequence(['update'],['htmlMin', 'copyImages', 'copyFonts', 'sass'],['css'],['watch']);
});
//
//
iamricard commented 9 years ago

Hi @aintnorest thanks for the feedback! I'll make some time to fix this issue sometime this week :+1:

iamricard commented 9 years ago

@aintnorest I've edited the issue for some syntax highlighting I hope you don't mind, it makes it easier to read.

Can you specify a bit more clearly what is it you need? If I understand correctly you'd like an event emitted whenever a build is finished?

It think this module needs a mejor re-work and should use apache/cordova-lib instead of apache/cordova-cli to be more reliable and stable. Relying on spawned processes is not a good idea. I'm working on porting this to apache/cordova-lib.

aintnorest commented 9 years ago

Sorry I should never write issues late at night they're never clearly written and my natural tendency to babel wins out... So two things.

  1. I use run sequence to make some things run synchronously. Such as building the browser the version then after the browser version builds I want to fire my browser reload command. Right now when I run a cordova command it acts as though it's finished as soon as It's sent to the command line not when the task actually completes so I have to emulate that with a timeout on the browser reload which is fine it's just not ideal.
  2. I have to use process.chdir to switch into the folder with the cordova project when running the cordova commands. Now this sets the entire run sequence from that point on to the new cwd until i set it back. It's not a huge deal but if we could make it use the gulp.src(..., {cwd: __dirname}) formating like other plugins that would be awesome.

I should say I don't think anything here is necessarily a bug more of enhancements that would be nice. Especially number one something about setting timeouts to try and catch when something is done is just unpalatable. Thanks again for the plugin its made my build process less of a pain.

iamricard commented 9 years ago

Everything sounds pretty reasonable! I think the first step, as I mentioned, is moving away from cordova-cli and towards cordova-lib. Hopefully that will the modules it more manageable and less fragile. I'll keep you updated on the progress.

I'll try to keep the API consistent but if you have any requests/suggestions it's probably a good time to change and break stuff :grin:

iamricard commented 9 years ago

@aintnorest it's still a work in progress (getting time from wherever I can), but if you want to see some of the changes you can take a look at the branch feature/use-cordova-lib

iamricard commented 9 years ago

@aintnorest please reopen if this issue still applies after switching to gulp-cordova@0.1.0 or open a new one if old ones still happen.

Notice the new version is published under a new name.

aintnorest commented 9 years ago

Thanks, I'll give it a try hopefully Sunday if I can find some time. Have my daughters 1st birthday this weekend. If not though I'll definitely get to it Monday. Thanks for the work you've put into it. I had thought I might get a chance to help after I get my current project shipped next week but you were really quick.

iamricard commented 9 years ago

Well let's hope I haven't broken everything! Some things might need fixing as I haven't had the time to test the changes properly.

Congratulations on your daughters birthday! 😄

iamricard commented 9 years ago

@aintnorest did you have a chance to use the new version? Is it working better?