Advertisement
MastroPino

Untitled

Aug 2nd, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.58 KB | None | 0 0
  1. // 1. LIBRARIES
  2. var $ = require('gulp-load-plugins')();
  3. var argv = require('yargs').argv;
  4. var gulp = require('gulp');
  5. var sequence = require('run-sequence');
  6. var merge = require('merge2');
  7. var del = require('del');
  8. var hash_src = require("gulp-hash-src");
  9. var cleanhtml = require('gulp-cleanhtml');
  10. var fs = require('fs');
  11. var es = require('event-stream');
  12. // 2. GLOBAL VARIABLES
  13. var defaultCustomerCode = 'Costa';
  14. var availableLanguages = ['it-IT', 'fr-FR', 'en-GB', 'es-ES', 'de-CH', 'de-AT', 'it-CH', 'fr-BE', 'nl-BE', 'de-DE','en-US'];
  15. var defaultLanguageCode = 'it-IT';
  16. //check for --skipTranslation flag
  17. var skipTranslation = !!(argv.skipTranslation);
  18. //check for the --showEmptyLabel flag
  19. var showEmptyLabel = !!(argv.showEmptyLabel);
  20. var customerRelatedCompileTimeVariables = {};
  21.  
  22. customerRelatedCompileTimeVariables['Costa'] = {
  23. '##SearchController': 'CostaSearchCtrl',
  24. '##ProductBuilderCtrl': 'CostaProductBuilderCtrl',
  25. '##AnswerController': 'CostaAnswerCtrl',
  26. '##MainCtrl': 'CostaMainCtrl',
  27. '##ProductManagerCtrl':'CostaProductManagerCtrl',
  28. '##FormatChooserCtrl':'CostaFormatChooserCtrl',
  29. '##CustomRequestCtrl': 'CostaCustomRequestCtrl',
  30. '##BackgroundCtrl' : 'CostaBackgroundCtrl',
  31. '##FinalizationCtrl': 'CostaFinalizationCtrl',
  32. '##LayoutChooserCtrl': 'CostaLayoutChooserCtrl'
  33. };
  34.  
  35. customerRelatedCompileTimeVariables['Oto'] = {
  36. '##SearchController': 'SearchCtrl',
  37. '##ProductBuilderCtrl': 'ProductBuilderCtrl',
  38. '##AnswerController': 'AnswerCtrl',
  39. '##MainCtrl': 'MainCtrl',
  40. '##ProductManagerCtrl':'ProductManagerCtrl',
  41. '##FormatChooserCtrl':'FormatChooserCtrl',
  42. '##CustomRequestCtrl' : 'CustomRequestCtrl',
  43. '##BackgroundCtrl' : 'BackgroundCtrl',
  44. '##FinalizationCtrl': 'FinalizationCtrl',
  45. '##LayoutChooserCtrl': 'LayoutChooserCtrl'
  46. };
  47.  
  48. var paths = {
  49. momentLocale: './app/bower_components/moment/locale/',
  50. installer: './app/installer.js',
  51. assets: [
  52. './app/**/*.*',
  53. './app/**/.htaccess',
  54. '!./app/index.html',
  55. '!./app/views/**/*.*',
  56. '!./app/images/**/*.*',
  57. '!./app/{styles,scripts,bower_components,assets}/**/*.*',
  58. '!./app/installer.js'
  59. ],
  60. coreJS: [
  61. 'app/bower_components/jquery/dist/jquery.min.js',
  62. 'app/bower_components/angular/angular.min.js',
  63. 'app/bower_components/angular-sanitize/angular-sanitize.js',
  64. 'app/bower_components/angular-route/angular-route.js',
  65. 'app/bower_components/angular-resource/angular-resource.min.js',
  66. //TODO: importare correttamente il locale di angular a seconda della lingua.
  67. 'app/bower_components/angular-i18n/angular-locale_it-it.js',
  68. "app/bower_components/angular-toArrayFilter/toArrayFilter.js",
  69. "app/bower_components/angulartics/dist/angulartics.min.js",
  70. "app/bower_components/angulartics-google-analytics/dist/angulartics-ga.min.js",
  71. "app/bower_components/angulartics/dist/angulartics.min.js",
  72. "app/bower_components/angulartics-google-analytics/dist/angulartics-ga.min.js"
  73. ],
  74. vendorJS: [
  75. 'app/bower_components/bootstrap/dist/js/bootstrap.min.js',
  76. 'app/bower_components/angular-bootstrap/ui-bootstrap.min.js',
  77. 'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
  78. 'app/bower_components/angular-animate/angular-animate.min.js',
  79. 'app/bower_components/moment/moment.js',
  80. 'app/bower_components/lodash/dist/lodash.min.js',
  81.  
  82. 'app/bower_components/ng-flow/dist/ng-flow-standalone.min.js',
  83.  
  84. 'app/bower_components/datatables.net/js/jquery.dataTables.min.js',
  85. 'app/bower_components/angular-datatables/dist/angular-datatables.js',
  86. 'app/bower_components/ladda/dist/spin.min.js',
  87. 'app/bower_components/ladda/dist/ladda.min.js',
  88. 'app/bower_components/angular-ladda/dist/angular-ladda.min.js',
  89.  
  90. 'app/bower_components/Croppie/croppie.min.js',
  91. 'app/bower_components/ng-magnify/src/js/ng-magnify.js',
  92.  
  93. //editor
  94. 'app/bower_components/tinymce/tinymce.min.js'
  95. ],
  96.  
  97. appJS: [
  98. 'app/scripts/app.js',
  99. 'app/scripts/**/*'
  100. ],
  101.  
  102. mainCSS: [
  103. 'app/styles/*.css'
  104. ],
  105.  
  106. vendorCSS: [
  107. 'app/bower_components/bootstrap/dist/css/bootstrap.min.css',
  108. 'app/bower_components/Ionicons/css/ionicons.min.css',
  109. 'app/bower_components/angular-datatables/dist/css/angular-datatables.css',
  110. 'app/bower_components/angular-datatables/dist/plugins/bootstrap/datatables.bootstrap.min.css',
  111. 'app/bower_components/ladda/dist/ladda-themeless.min.css',
  112. 'app/bower_components/Croppie/croppie.css',
  113. 'app/bower_components/ng-magnify/src/css/ng-magnify.css'
  114. ],
  115.  
  116. vendorFonts: [
  117. 'app/bower_components/Ionicons/fonts/**/*'
  118. ],
  119.  
  120. minifiedImgTempFolder: './tmp_minified_images'
  121.  
  122. };
  123.  
  124. // 3. TASKS
  125.  
  126. gulp.task('server', ['build'], function () {
  127.  
  128. gulp.src(['./dist_it-IT', './'])
  129. .pipe($.webserver({
  130. port: 8079,
  131. host: 'costaclick.oto',
  132. fallback: 'iframeTest.html',
  133. open: false
  134. }));
  135.  
  136. });
  137.  
  138. gulp.task('default', ['server'], function () {
  139.  
  140. // Watch Sass
  141. gulp.watch(['./app/styles/**/*', './scss/**/*'], ['compileCSS'], function () {
  142. sequence('compileCSS', 'copy', 'hash');
  143. });
  144.  
  145. // Watch JavaScript
  146. gulp.watch(['./app/scripts/**/*'], function () {
  147. sequence('uglify:app', 'copy:index', 'hash');
  148. });
  149. gulp.watch([paths.vendorJS], function () {
  150. sequence('uglify:vendorJS', 'copy:index', 'hash');
  151. });
  152.  
  153. // Watch static files
  154. gulp.watch([paths.assets, './app/index.html', './app/**/*.html'], function () {
  155. sequence('copy', 'hash');
  156. });
  157. });
  158.  
  159. gulp.task('build', function (cb) {
  160. return sequence('clean', ['copy', 'compileCSS', 'uglify', 'setMomentLocaleFile'], 'imagemin', 'hash', cb);
  161. });
  162.  
  163. gulp.task('server', ['build'], function () {
  164.  
  165. gulp.src(['./dist_'+argv.lang, './'])
  166. .pipe($.webserver({
  167. port: 8079,
  168. host: 'costaclick.oto',
  169. fallback: 'iframeTest.html',
  170. livereload: false,
  171. open: false
  172. }));
  173.  
  174. });
  175.  
  176. gulp.task('clean', function () {
  177. return del(getAllBuildPath());
  178. });
  179.  
  180. gulp.task('copy', ['copy:all', 'copy:index']);
  181. // Copies everything in the client folder except Sass, and JS
  182. gulp.task('copy:all', function () {
  183. return getStreamForEachLanguageToBuild(copyAll);
  184. });
  185.  
  186. //generate index.php from index.html
  187. gulp.task('copy:index', function () {
  188. return getStreamForEachLanguageToBuild(copyIndex);
  189. });
  190. // ======= SCSS / CSS =======
  191. gulp.task('compileCSS', ['mainCSS', 'vendorCSS', 'processInstaller']);
  192. // Compiles main css
  193. gulp.task('mainCSS', function () {
  194. return getStreamForEachLanguageToBuild(compileMainCss);
  195. });
  196. // Compiles vendor (S)CSS
  197. gulp.task('vendorCSS', function () {
  198. return getStreamForEachLanguageToBuild(compileVendorCss);
  199. });
  200.  
  201. gulp.task('processInstaller', function () {
  202. return getStreamForEachLanguageToBuild(processInstaller);
  203. });
  204. //optimize images
  205. gulp.task('imagemin', ['minifyImg'], function () {
  206. return getStreamForEachLanguageToBuildUsingQueue(copyMinifiedImages);
  207. });
  208.  
  209. gulp.task('minifyImg', function () {
  210. return minifyImages();
  211. });
  212.  
  213. gulp.task('setMomentLocaleFile', function () {
  214. return getStreamForEachLanguageToBuild(copyMomentLocaleFile);
  215. });
  216. // ======= JAVASCRIPT =======
  217. gulp.task('uglify', ['uglify:coreJS', 'uglify:vendorJS', 'uglify:app']);
  218.  
  219. gulp.task('uglify:coreJS', function (cb) {
  220. return getStreamForEachLanguageToBuild(uglifyCoreJs);
  221. });
  222.  
  223. gulp.task('uglify:vendorJS', function (cb) {
  224. return getStreamForEachLanguageToBuild(uglifyVendorJs);
  225. });
  226.  
  227. gulp.task('uglify:app', function () {
  228. return getStreamForEachLanguageToBuild(uglifyApp);
  229. });
  230. //TODO: fix hash (like CN)
  231. //add cache buster hash for js and css
  232. gulp.task("hash", function () {
  233. return getStreamForEachLanguageToBuild(hashFiles);
  234. });
  235.  
  236. function getSimplifiedLocale(outputCulture) {
  237. outputCulture = outputCulture.toLowerCase();
  238. var cultureObjParts = outputCulture.split('-');
  239.  
  240. var localesMap = {
  241. 'it-ch': 'it',
  242. 'de-ch': 'de',
  243. 'fr-be': 'fr'
  244. };
  245.  
  246. if (cultureObjParts[0] == cultureObjParts[1]) {
  247. return cultureObjParts[0];
  248. }
  249.  
  250. return !!localesMap[outputCulture] ? localesMap[outputCulture] : outputCulture;
  251. }
  252.  
  253. function copyMomentLocaleFile(lang) {
  254. var langForMoment = getSimplifiedLocale(lang);
  255. return gulp.src(paths.momentLocale + langForMoment + '.js')
  256. .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
  257. }
  258.  
  259. function copyMinifiedImages(lang, queue) {
  260. return gulp.src(paths.minifiedImgTempFolder + '/**/*')
  261. .pipe(gulp.dest(getBuildPath(lang) + '/images'))
  262. .on('end', function () {
  263. queue.pop();
  264. if (queue.length == 0) {
  265. del([paths.minifiedImgTempFolder]);
  266. }
  267. });
  268. }
  269.  
  270. function processInstaller(lang) {
  271. return gulp.src(paths.installer)
  272. .pipe(setDefaultLanguageCodeInValue(lang))
  273. .pipe(gulp.dest(getBuildPath(lang)));
  274. }
  275.  
  276. function hashFiles(lang) {
  277. var hasher = $.if(isProduction(), hash_src({
  278. build_dir: getBuildPath(lang), src_path: "./app",
  279. regex: /(href|src|ng-include)\s*=\s*(?:("'?)([^"']*)|(')([^']*)|([^'"\s>]+))|url\s*\((?:(")([^"]+)|(')([^']+)|([^'"\)]+));/ig,
  280. exts: [".html", ".js", ".css", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".pdf", ".ico", ".ttf", ".woff", ".mp3", ".ogg", ".ogv", ".mp4", ".webm", ".zip", ".tar", ".gz", ".bz2"],
  281. analyze: analyze,
  282. verbose: false
  283. }));
  284.  
  285. return gulp.src([getBuildPath(lang) + "/**/*.html", getBuildPath(lang) + "/index.html", getBuildPath(lang) + "/index.php", getBuildPath(lang) + "/**/*.css"])
  286. .pipe(hasher)
  287. .pipe(gulp.dest(getBuildPath(lang)));
  288. }
  289.  
  290. function getStreamForEachLanguageToBuild(callback) {
  291. var mergedStream = merge();
  292.  
  293. if (isBuildingForSingleLanguage()) {
  294. mergedStream.add(callback(getLanguageCode()));
  295. } else {
  296. for (var langIndex in availableLanguages) {
  297. mergedStream.add(callback(availableLanguages[langIndex]));
  298. }
  299. }
  300.  
  301. return mergedStream;
  302. }
  303.  
  304. function getStreamForEachLanguageToBuildUsingQueue(callback) {
  305. var mergedStream = merge();
  306. var queue = [];
  307.  
  308. if (isBuildingForSingleLanguage()) {
  309. queue.push(true);
  310. mergedStream.add(callback(getLanguageCode(), queue));
  311. } else {
  312. for (var langIndex in availableLanguages) {
  313. queue.push(true);
  314. mergedStream.add(callback(availableLanguages[langIndex], queue));
  315. }
  316. }
  317.  
  318. return mergedStream;
  319. }
  320.  
  321. function isProduction() {
  322. return !!(argv.production);
  323. }
  324.  
  325. function isBuildingForSingleLanguage() {
  326. return getLanguageCode() != 'ALL';
  327. }
  328.  
  329. function getBuildPath(lang) {
  330. // Check for --production flag
  331. //TODO: devo prevedere piu path, non un solo path.
  332. return "./dist_" + lang;
  333. }
  334.  
  335. function getAllBuildPath() {
  336. var toReturn = [];
  337.  
  338. for (var langIndex in availableLanguages) {
  339. toReturn.push(getBuildPath(availableLanguages[langIndex]));
  340. }
  341.  
  342. return toReturn;
  343. }
  344.  
  345. function uglifyVendorJs(lang) {
  346. var uglify = $.if(isProduction(), $.uglify()
  347. .on('error', function (e) {
  348. console.log(e);
  349. }));
  350.  
  351. return gulp.src(paths.vendorJS)
  352. .pipe(uglify)
  353. .pipe($.concat('vendor.js'))
  354. .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
  355. }
  356.  
  357. function uglifyCoreJs(lang) {
  358. var uglify = $.if(isProduction(), $.uglify()
  359. .on('error', function (e) {
  360. console.log(e);
  361. }));
  362.  
  363. return gulp.src(paths.coreJS)
  364. .pipe(uglify)
  365. .pipe($.concat('core.js'))
  366. .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
  367. }
  368.  
  369. function uglifyApp(lang) {
  370. var uglify = $.if(isProduction(), $.uglify()
  371. .on('error', function (e) {
  372. console.log(e);
  373. }));
  374.  
  375. return gulp.src(paths.appJS)
  376. .pipe(uglify)
  377. .pipe($.concat('app.js'))
  378. .pipe(setDefaultLanguageCodeInValue(lang))
  379. .pipe(setSimplifiedlanguageCodeInJs(lang))
  380. .pipe(gulp.dest(getBuildPath(lang) + '/scripts/'));
  381. }
  382.  
  383. function minifyImages() {
  384. var imagemin = $.if(isProduction(), $.imagemin());
  385. return gulp.src('app/images/**')
  386. .pipe(imagemin)
  387. .pipe(gulp.dest(paths.minifiedImgTempFolder));
  388. }
  389.  
  390. function copyAll(lang) {
  391. // Ionicons icons
  392. var ionicons = gulp.src(paths.vendorFonts)
  393. .pipe(gulp.dest(getBuildPath(lang) + '/fonts'))
  394. ;
  395.  
  396. var assets = gulp.src(paths.assets, {
  397. base: './app/'
  398. }).pipe(gulp.dest(getBuildPath(lang)))
  399. ;
  400.  
  401. var clean = $.if(isProduction(), cleanhtml());
  402. var translate = $.if(!skipTranslation, translateToDefaultLanguageCode(lang));
  403. var views = gulp.src('./app/views/**/*.html')
  404. .pipe(replaceCustomerRelatedCompileTimeVariable())
  405. .pipe(translate)
  406. .pipe(clean)
  407. .pipe(gulp.dest(getBuildPath(lang) + '/views'))
  408. ;
  409. //tinymce themes
  410. var mceThemes = gulp.src(['app/bower_components/tinymce/*/**', 'app/assets/tinymce_languages/*/**'])
  411. .pipe(gulp.dest(getBuildPath(lang) + '/scripts'));
  412.  
  413.  
  414. return [ionicons, assets, views, mceThemes];
  415. }
  416.  
  417. function compileMainCss(lang) {
  418. var minifyCss = $.if(isProduction(), $.minifyCss());
  419.  
  420. return gulp.src(paths.mainCSS)
  421. .pipe($.autoprefixer({
  422. browsers: ['last 2 versions', 'ie 10']
  423. }))
  424. .pipe(minifyCss)
  425. .pipe($.concat('main.css'))
  426. .pipe(gulp.dest(getBuildPath(lang) + '/styles/'));
  427. }
  428.  
  429. function copyIndex(lang) {
  430. return gulp.src('./app/index.html')
  431. .pipe(replaceCustomerRelatedCompileTimeVariable())
  432. .pipe(gulp.dest(getBuildPath(lang) + '/'));
  433. }
  434.  
  435. function compileVendorCss(lang) {
  436. var minifyCss = $.if(isProduction(), $.minifyCss());
  437.  
  438. return gulp.src(paths.vendorCSS)
  439. .pipe($.autoprefixer({
  440. browsers: ['last 2 versions', 'ie 10']
  441. }))
  442. .pipe(minifyCss)
  443. .pipe($.concat('vendor.css'))
  444. .pipe(gulp.dest(getBuildPath(lang) + '/styles/'));
  445. }
  446.  
  447. function getCustomerCode() {
  448. //check for customer code --c code
  449. if (!!(argv.c)) {
  450. return argv.c;
  451. }
  452. return defaultCustomerCode;
  453. }
  454.  
  455. function getLanguageCode() {
  456. //check for language code --lang [code|ALL]
  457. //when a single 'code' is specified gulp will create a build just for that language.
  458. //By using ALL gulp will create a build just for each of the supported languages.
  459. var isLocalisationNeeded = !!(argv.lang);
  460. if (isLocalisationNeeded) {
  461. return argv.lang;
  462. }
  463. return defaultLanguageCode;
  464. }
  465.  
  466. /**
  467. * replace strings like [#key] with matching value in the specified file (if any)
  468. * @param localeFilePath
  469. * @returns {Function}
  470. */
  471. var translateFn =
  472. function (localeFilePath) {
  473. var jsonString = fs.readFileSync(localeFilePath, {encoding: 'utf8'});
  474.  
  475. jsonString = jsonString.replace(/[\r\n\s]+(\/\/.*)[\r\n\s]*/g, '');
  476.  
  477. var localFile = JSON.parse(jsonString);
  478. return function () {
  479. var transform = function (line) {
  480. return line.replace(/\[\s*(#[^\s\]]*)\s*\]/g, function (match, group1) {
  481. var replacement = localFile[group1.trim()];
  482. return showEmptyLabel ? replacement || match : replacement;
  483. })
  484. };
  485.  
  486. return es.map(function (file, cb) {
  487. file.contents = new Buffer(transform(file.contents.toString()));
  488. cb(null, file);
  489. });
  490. };
  491. };
  492.  
  493. function translateToDefaultLanguageCode(lang) {
  494. return translateFn('./app/localization/local_' + lang + '.json')();
  495. }
  496.  
  497. var replaceCustomerRelatedCompileTimeVariable = function () {
  498. var transform = function (line) {
  499. return line.replace(/\[\s*(##[^\s\]]*)\s*\]/g, function (match, group1) {
  500. return customerRelatedCompileTimeVariables[getCustomerCode()][group1.trim()];
  501. })
  502. };
  503.  
  504. return es.map(function (file, cb) {
  505. file.contents = new Buffer(transform(file.contents.toString()));
  506. cb(null, file);
  507. });
  508. };
  509.  
  510. function setDefaultLanguageCodeInValue(lang) {
  511. return replacePlaceholder('[#languageCode]', lang);
  512. }
  513.  
  514. function setSimplifiedlanguageCodeInJs(lang) {
  515. return replacePlaceholder('[#simplifiedLanguageCode]', getSimplifiedLocale(lang));
  516. }
  517.  
  518. function replacePlaceholder(placeHolder, replacementValue) {
  519. var replaceDefaultLanguageCode = function (stringifiedFile) {
  520. return stringifiedFile.split(placeHolder).join(replacementValue)
  521. };
  522.  
  523. return es.map(function (file, cb) {
  524. file.contents = new Buffer(replaceDefaultLanguageCode(file.contents.toString()));
  525. cb(null, file);
  526. });
  527. }
  528.  
  529.  
  530. function analyze(match) {
  531. var quote = match[2] || match[4] || match[7] || match[9] || "",
  532. link = match[3] || match[5] || match[6];
  533.  
  534.  
  535. /// Is this a href/src match?
  536. if (link) {
  537. return {
  538. prefix: match[1] + "=" + quote,
  539. link: link,
  540. suffix: "", /// The last quote doesn't get matched
  541. abs: quote == "\"'" //for ng-include
  542. };
  543. }
  544.  
  545. /// It is a CSS match.
  546. return {
  547. prefix: "url(" + quote,
  548. link: match[8] || match[10] || match[11],
  549. suffix: "", /// The last quote doesn't get matched
  550. };
  551. }
  552.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement