Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1. LIBRARIES
- var $ = require('gulp-load-plugins')();
- var argv = require('yargs').argv;
- var gulp = require('gulp');
- var sequence = require('run-sequence');
- var merge = require('merge2');
- var del = require('del');
- var hash_src = require("gulp-hash-src");
- var cleanhtml = require('gulp-cleanhtml');
- var fs = require('fs');
- var es = require('event-stream');
- // 2. GLOBAL VARIABLES
- var defaultCustomerCode = 'Costa';
- var availableLanguages = ['it-IT', 'fr-FR', 'en-GB', 'es-ES', 'de-CH', 'de-AT', 'it-CH', 'fr-BE', 'nl-BE', 'de-DE','en-US'];
- var defaultLanguageCode = 'it-IT';
- //check for --skipTranslation flag
- var skipTranslation = !!(argv.skipTranslation);
- //check for the --showEmptyLabel flag
- var showEmptyLabel = !!(argv.showEmptyLabel);
- var customerRelatedCompileTimeVariables = {};
- customerRelatedCompileTimeVariables['Costa'] = {
- '##SearchController': 'CostaSearchCtrl',
- '##ProductBuilderCtrl': 'CostaProductBuilderCtrl',
- '##AnswerController': 'CostaAnswerCtrl',
- '##MainCtrl': 'CostaMainCtrl',
- '##ProductManagerCtrl':'CostaProductManagerCtrl',
- '##FormatChooserCtrl':'CostaFormatChooserCtrl',
- '##CustomRequestCtrl': 'CostaCustomRequestCtrl',
- '##BackgroundCtrl' : 'CostaBackgroundCtrl',
- '##FinalizationCtrl': 'CostaFinalizationCtrl',
- '##LayoutChooserCtrl': 'CostaLayoutChooserCtrl'
- };
- customerRelatedCompileTimeVariables['Oto'] = {
- '##SearchController': 'SearchCtrl',
- '##ProductBuilderCtrl': 'ProductBuilderCtrl',
- '##AnswerController': 'AnswerCtrl',
- '##MainCtrl': 'MainCtrl',
- '##ProductManagerCtrl':'ProductManagerCtrl',
- '##FormatChooserCtrl':'FormatChooserCtrl',
- '##CustomRequestCtrl' : 'CustomRequestCtrl',
- '##BackgroundCtrl' : 'BackgroundCtrl',
- '##FinalizationCtrl': 'FinalizationCtrl',
- '##LayoutChooserCtrl': 'LayoutChooserCtrl'
- };
- var paths = {
- momentLocale: './app/bower_components/moment/locale/',
- installer: './app/installer.js',
- assets: [
- './app/**/*.*',
- './app/**/.htaccess',
- '!./app/index.html',
- '!./app/views/**/*.*',
- '!./app/images/**/*.*',
- '!./app/{styles,scripts,bower_components,assets}/**/*.*',
- '!./app/installer.js'
- ],
- coreJS: [
- 'app/bower_components/jquery/dist/jquery.min.js',
- 'app/bower_components/angular/angular.min.js',
- 'app/bower_components/angular-sanitize/angular-sanitize.js',
- 'app/bower_components/angular-route/angular-route.js',
- 'app/bower_components/angular-resource/angular-resource.min.js',
- //TODO: importare correttamente il locale di angular a seconda della lingua.
- 'app/bower_components/angular-i18n/angular-locale_it-it.js',
- "app/bower_components/angular-toArrayFilter/toArrayFilter.js",
- "app/bower_components/angulartics/dist/angulartics.min.js",
- "app/bower_components/angulartics-google-analytics/dist/angulartics-ga.min.js",
- "app/bower_components/angulartics/dist/angulartics.min.js",
- "app/bower_components/angulartics-google-analytics/dist/angulartics-ga.min.js"
- ],
- vendorJS: [
- 'app/bower_components/bootstrap/dist/js/bootstrap.min.js',
- 'app/bower_components/angular-bootstrap/ui-bootstrap.min.js',
- 'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
- 'app/bower_components/angular-animate/angular-animate.min.js',
- 'app/bower_components/moment/moment.js',
- 'app/bower_components/lodash/dist/lodash.min.js',
- 'app/bower_components/ng-flow/dist/ng-flow-standalone.min.js',
- 'app/bower_components/datatables.net/js/jquery.dataTables.min.js',
- 'app/bower_components/angular-datatables/dist/angular-datatables.js',
- 'app/bower_components/ladda/dist/spin.min.js',
- 'app/bower_components/ladda/dist/ladda.min.js',
- 'app/bower_components/angular-ladda/dist/angular-ladda.min.js',
- 'app/bower_components/Croppie/croppie.min.js',
- 'app/bower_components/ng-magnify/src/js/ng-magnify.js',
- //editor
- 'app/bower_components/tinymce/tinymce.min.js'
- ],
- appJS: [
- 'app/scripts/app.js',
- 'app/scripts/**/*'
- ],
- mainCSS: [
- 'app/styles/*.css'
- ],
- vendorCSS: [
- 'app/bower_components/bootstrap/dist/css/bootstrap.min.css',
- 'app/bower_components/Ionicons/css/ionicons.min.css',
- 'app/bower_components/angular-datatables/dist/css/angular-datatables.css',
- 'app/bower_components/angular-datatables/dist/plugins/bootstrap/datatables.bootstrap.min.css',
- 'app/bower_components/ladda/dist/ladda-themeless.min.css',
- 'app/bower_components/Croppie/croppie.css',
- 'app/bower_components/ng-magnify/src/css/ng-magnify.css'
- ],
- vendorFonts: [
- 'app/bower_components/Ionicons/fonts/**/*'
- ],
- minifiedImgTempFolder: './tmp_minified_images'
- };
- // 3. TASKS
- gulp.task('server', ['build'], function () {
- gulp.src(['./dist_it-IT', './'])
- .pipe($.webserver({
- port: 8079,
- host: 'costaclick.oto',
- fallback: 'iframeTest.html',
- open: false
- }));
- });
- gulp.task('default', ['server'], function () {
- // Watch Sass
- gulp.watch(['./app/styles/**/*', './scss/**/*'], ['compileCSS'], function () {
- sequence('compileCSS', 'copy', 'hash');
- });
- // Watch JavaScript
- gulp.watch(['./app/scripts/**/*'], function () {
- sequence('uglify:app', 'copy:index', 'hash');
- });
- gulp.watch([paths.vendorJS], function () {
- sequence('uglify:vendorJS', 'copy:index', 'hash');
- });
- // Watch static files
- gulp.watch([paths.assets, './app/index.html', './app/**/*.html'], function () {
- sequence('copy', 'hash');
- });
- });
- gulp.task('build', function (cb) {
- return sequence('clean', ['copy', 'compileCSS', 'uglify', 'setMomentLocaleFile'], 'imagemin', 'hash', cb);
- });
- gulp.task('server', ['build'], function () {
- gulp.src(['./dist_'+argv.lang, './'])
- .pipe($.webserver({
- port: 8079,
- host: 'costaclick.oto',
- fallback: 'iframeTest.html',
- livereload: false,
- open: false
- }));
- });
- gulp.task('clean', function () {
- return del(getAllBuildPath());
- });
- gulp.task('copy', ['copy:all', 'copy:index']);
- // Copies everything in the client folder except Sass, and JS
- gulp.task('copy:all', function () {
- return getStreamForEachLanguageToBuild(copyAll);
- });
- //generate index.php from index.html
- gulp.task('copy:index', function () {
- return getStreamForEachLanguageToBuild(copyIndex);
- });
- // ======= SCSS / CSS =======
- gulp.task('compileCSS', ['mainCSS', 'vendorCSS', 'processInstaller']);
- // Compiles main css
- gulp.task('mainCSS', function () {
- return getStreamForEachLanguageToBuild(compileMainCss);
- });
- // Compiles vendor (S)CSS
- gulp.task('vendorCSS', function () {
- return getStreamForEachLanguageToBuild(compileVendorCss);
- });
- gulp.task('processInstaller', function () {
- return getStreamForEachLanguageToBuild(processInstaller);
- });
- //optimize images
- gulp.task('imagemin', ['minifyImg'], function () {
- return getStreamForEachLanguageToBuildUsingQueue(copyMinifiedImages);
- });
- gulp.task('minifyImg', function () {
- return minifyImages();
- });
- gulp.task('setMomentLocaleFile', function () {
- return getStreamForEachLanguageToBuild(copyMomentLocaleFile);
- });
- // ======= JAVASCRIPT =======
- gulp.task('uglify', ['uglify:coreJS', 'uglify:vendorJS', 'uglify:app']);
- gulp.task('uglify:coreJS', function (cb) {
- return getStreamForEachLanguageToBuild(uglifyCoreJs);
- });
- gulp.task('uglify:vendorJS', function (cb) {
- return getStreamForEachLanguageToBuild(uglifyVendorJs);
- });
- gulp.task('uglify:app', function () {
- return getStreamForEachLanguageToBuild(uglifyApp);
- });
- //TODO: fix hash (like CN)
- //add cache buster hash for js and css
- gulp.task("hash", function () {
- return getStreamForEachLanguageToBuild(hashFiles);
- });
- function getSimplifiedLocale(outputCulture) {
- outputCulture = outputCulture.toLowerCase();
- var cultureObjParts = outputCulture.split('-');
- var localesMap = {
- 'it-ch': 'it',
- 'de-ch': 'de',
- 'fr-be': 'fr'
- };
- if (cultureObjParts[0] == cultureObjParts[1]) {
- return cultureObjParts[0];
- }
- return !!localesMap[outputCulture] ? localesMap[outputCulture] : outputCulture;
- }
- function copyMomentLocaleFile(lang) {
- var langForMoment = getSimplifiedLocale(lang);
- return gulp.src(paths.momentLocale + langForMoment + '.js')
- .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
- }
- function copyMinifiedImages(lang, queue) {
- return gulp.src(paths.minifiedImgTempFolder + '/**/*')
- .pipe(gulp.dest(getBuildPath(lang) + '/images'))
- .on('end', function () {
- queue.pop();
- if (queue.length == 0) {
- del([paths.minifiedImgTempFolder]);
- }
- });
- }
- function processInstaller(lang) {
- return gulp.src(paths.installer)
- .pipe(setDefaultLanguageCodeInValue(lang))
- .pipe(gulp.dest(getBuildPath(lang)));
- }
- function hashFiles(lang) {
- var hasher = $.if(isProduction(), hash_src({
- build_dir: getBuildPath(lang), src_path: "./app",
- regex: /(href|src|ng-include)\s*=\s*(?:("'?)([^"']*)|(')([^']*)|([^'"\s>]+))|url\s*\((?:(")([^"]+)|(')([^']+)|([^'"\)]+));/ig,
- exts: [".html", ".js", ".css", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".pdf", ".ico", ".ttf", ".woff", ".mp3", ".ogg", ".ogv", ".mp4", ".webm", ".zip", ".tar", ".gz", ".bz2"],
- analyze: analyze,
- verbose: false
- }));
- return gulp.src([getBuildPath(lang) + "/**/*.html", getBuildPath(lang) + "/index.html", getBuildPath(lang) + "/index.php", getBuildPath(lang) + "/**/*.css"])
- .pipe(hasher)
- .pipe(gulp.dest(getBuildPath(lang)));
- }
- function getStreamForEachLanguageToBuild(callback) {
- var mergedStream = merge();
- if (isBuildingForSingleLanguage()) {
- mergedStream.add(callback(getLanguageCode()));
- } else {
- for (var langIndex in availableLanguages) {
- mergedStream.add(callback(availableLanguages[langIndex]));
- }
- }
- return mergedStream;
- }
- function getStreamForEachLanguageToBuildUsingQueue(callback) {
- var mergedStream = merge();
- var queue = [];
- if (isBuildingForSingleLanguage()) {
- queue.push(true);
- mergedStream.add(callback(getLanguageCode(), queue));
- } else {
- for (var langIndex in availableLanguages) {
- queue.push(true);
- mergedStream.add(callback(availableLanguages[langIndex], queue));
- }
- }
- return mergedStream;
- }
- function isProduction() {
- return !!(argv.production);
- }
- function isBuildingForSingleLanguage() {
- return getLanguageCode() != 'ALL';
- }
- function getBuildPath(lang) {
- // Check for --production flag
- //TODO: devo prevedere piu path, non un solo path.
- return "./dist_" + lang;
- }
- function getAllBuildPath() {
- var toReturn = [];
- for (var langIndex in availableLanguages) {
- toReturn.push(getBuildPath(availableLanguages[langIndex]));
- }
- return toReturn;
- }
- function uglifyVendorJs(lang) {
- var uglify = $.if(isProduction(), $.uglify()
- .on('error', function (e) {
- console.log(e);
- }));
- return gulp.src(paths.vendorJS)
- .pipe(uglify)
- .pipe($.concat('vendor.js'))
- .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
- }
- function uglifyCoreJs(lang) {
- var uglify = $.if(isProduction(), $.uglify()
- .on('error', function (e) {
- console.log(e);
- }));
- return gulp.src(paths.coreJS)
- .pipe(uglify)
- .pipe($.concat('core.js'))
- .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
- }
- function uglifyApp(lang) {
- var uglify = $.if(isProduction(), $.uglify()
- .on('error', function (e) {
- console.log(e);
- }));
- return gulp.src(paths.appJS)
- .pipe(uglify)
- .pipe($.concat('app.js'))
- .pipe(setDefaultLanguageCodeInValue(lang))
- .pipe(setSimplifiedlanguageCodeInJs(lang))
- .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
- }
- function minifyImages() {
- var imagemin = $.if(isProduction(), $.imagemin());
- return gulp.src('app/images/**')
- .pipe(imagemin)
- .pipe(gulp.dest(paths.minifiedImgTempFolder));
- }
- function copyAll(lang) {
- // Ionicons icons
- var ionicons = gulp.src(paths.vendorFonts)
- .pipe(gulp.dest(getBuildPath(lang) + '/fonts'))
- ;
- var assets = gulp.src(paths.assets, {
- base: './app/'
- }).pipe(gulp.dest(getBuildPath(lang)))
- ;
- var clean = $.if(isProduction(), cleanhtml());
- var translate = $.if(!skipTranslation, translateToDefaultLanguageCode(lang));
- var views = gulp.src('./app/views/**/*.html')
- .pipe(replaceCustomerRelatedCompileTimeVariable())
- .pipe(translate)
- .pipe(clean)
- .pipe(gulp.dest(getBuildPath(lang) + '/views'))
- ;
- //tinymce themes
- var mceThemes = gulp.src(['app/bower_components/tinymce/*/**', 'app/assets/tinymce_languages/*/**'])
- .pipe(gulp.dest(getBuildPath(lang) + '/scripts'));
- return [ionicons, assets, views, mceThemes];
- }
- function compileMainCss(lang) {
- var minifyCss = $.if(isProduction(), $.minifyCss());
- return gulp.src(paths.mainCSS)
- .pipe($.autoprefixer({
- browsers: ['last 2 versions', 'ie 10']
- }))
- .pipe(minifyCss)
- .pipe($.concat('main.css'))
- .pipe(gulp.dest(getBuildPath(lang) + '/styles/'));
- }
- function copyIndex(lang) {
- return gulp.src('./app/index.html')
- .pipe(replaceCustomerRelatedCompileTimeVariable())
- .pipe(gulp.dest(getBuildPath(lang) + '/'));
- }
- function compileVendorCss(lang) {
- var minifyCss = $.if(isProduction(), $.minifyCss());
- return gulp.src(paths.vendorCSS)
- .pipe($.autoprefixer({
- browsers: ['last 2 versions', 'ie 10']
- }))
- .pipe(minifyCss)
- .pipe($.concat('vendor.css'))
- .pipe(gulp.dest(getBuildPath(lang) + '/styles/'));
- }
- function getCustomerCode() {
- //check for customer code --c code
- if (!!(argv.c)) {
- return argv.c;
- }
- return defaultCustomerCode;
- }
- function getLanguageCode() {
- //check for language code --lang [code|ALL]
- //when a single 'code' is specified gulp will create a build just for that language.
- //By using ALL gulp will create a build just for each of the supported languages.
- var isLocalisationNeeded = !!(argv.lang);
- if (isLocalisationNeeded) {
- return argv.lang;
- }
- return defaultLanguageCode;
- }
- /**
- * replace strings like [#key] with matching value in the specified file (if any)
- * @param localeFilePath
- * @returns {Function}
- */
- var translateFn =
- function (localeFilePath) {
- var jsonString = fs.readFileSync(localeFilePath, {encoding: 'utf8'});
- jsonString = jsonString.replace(/[\r\n\s]+(\/\/.*)[\r\n\s]*/g, '');
- var localFile = JSON.parse(jsonString);
- return function () {
- var transform = function (line) {
- return line.replace(/\[\s*(#[^\s\]]*)\s*\]/g, function (match, group1) {
- var replacement = localFile[group1.trim()];
- return showEmptyLabel ? replacement || match : replacement;
- })
- };
- return es.map(function (file, cb) {
- file.contents = new Buffer(transform(file.contents.toString()));
- cb(null, file);
- });
- };
- };
- function translateToDefaultLanguageCode(lang) {
- return translateFn('./app/localization/local_' + lang + '.json')();
- }
- var replaceCustomerRelatedCompileTimeVariable = function () {
- var transform = function (line) {
- return line.replace(/\[\s*(##[^\s\]]*)\s*\]/g, function (match, group1) {
- return customerRelatedCompileTimeVariables[getCustomerCode()][group1.trim()];
- })
- };
- return es.map(function (file, cb) {
- file.contents = new Buffer(transform(file.contents.toString()));
- cb(null, file);
- });
- };
- function setDefaultLanguageCodeInValue(lang) {
- return replacePlaceholder('[#languageCode]', lang);
- }
- function setSimplifiedlanguageCodeInJs(lang) {
- return replacePlaceholder('[#simplifiedLanguageCode]', getSimplifiedLocale(lang));
- }
- function replacePlaceholder(placeHolder, replacementValue) {
- var replaceDefaultLanguageCode = function (stringifiedFile) {
- return stringifiedFile.split(placeHolder).join(replacementValue)
- };
- return es.map(function (file, cb) {
- file.contents = new Buffer(replaceDefaultLanguageCode(file.contents.toString()));
- cb(null, file);
- });
- }
- function analyze(match) {
- var quote = match[2] || match[4] || match[7] || match[9] || "",
- link = match[3] || match[5] || match[6];
- /// Is this a href/src match?
- if (link) {
- return {
- prefix: match[1] + "=" + quote,
- link: link,
- suffix: "", /// The last quote doesn't get matched
- abs: quote == "\"'" //for ng-include
- };
- }
- /// It is a CSS match.
- return {
- prefix: "url(" + quote,
- link: match[8] || match[10] || match[11],
- suffix: "", /// The last quote doesn't get matched
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement