<commit_before>/*
zaa.controller("UploadController", function($scope) {

	$scope.bildId = 0;

	$scope.save = function()
	{
		console.log('save', $scope.bildId);
	}

})
*/
/*
zaa.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);
*/

/*
zaa.directive('storageImageUrl', function() {
	return {
		restrict : 'E',
		scope : {
			image : '@'
		},
		controller : function($scope, $http) {
			$http.get('admin/api-admin-storage/image-path', { params: { imageId : $scope.image } }).success(function(response) {
				$scope.imagesrc = response.source;
				$scope.fileId = response.file_id;
			}).error(function(response) {
			})
		},
		template : function() {
			return '<div>{{imagesrc}} {{fileId}} </div>';
		}
	}
});
*/

/*
zaa.directive('storageFileUpload', function() {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope, element, attrs) {
			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n !== o) {
					scope.ngModel = n;
				}
			})
			scope.modal = true;
		},
		controller : function($scope, $http) {
			if ($scope.ngModel) {
				console.log('file_here', $scope.ngModel);
				$http.get('admin/api-admin-storage/file-path', { params: { fileId : $scope.ngModel } }).success(function(response) {
					$scope.filesrc = response.source_http;
				}).error(function(response) {
					console.log('error', response);
				})
			} else {
				console.log('no_file_here!');
			}

			$scope.$watch(function() { return $scope.ngModel }, function(newValue, oldValue) {
				if (newValue) {
					$scope.modal = true;
				}
			});

			$scope.openModal = function() {
				$scope.modal = !$scope.modal;
			}
		},
		templateUrl : 'storageFileUpload'
	}
});

zaa.directive('storageImageUpload', function() {
	return {
		restrict : 'E',
		scope : {
			ngModel : '=',
		},
		controller : function($scope, $http, ApiAdminFilter) {

			if ($scope.filterId == undefined) {
				$scope.filterId = 0;
			}

			if ($scope.ngModel) {
				$http.get('admin/api-admin-storage/image-path', { params: { imageId : $scope.ngModel } }).success(function(response) {
					$scope.imagesrc = response.source;
					$scope.fileId = response.file_id;
				}).error(function(response) {
					console.log('error', response);
				})
			}

			$scope.filters = ApiAdminFilter.query();

			$scope.push2 = function() {
				$http.post('admin/api-admin-storage/image-upload', $.param({ fileId : $scope.fileId, filterId : $scope.filterId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(success) {
		        	if (!success) {
		        		alert('IMAGE UPLOAD ERROR!');
		        	} else {
		        		$scope.ngModel = success.id;

		        		$scope.imagesrc = success.image.source;

		        	}
				}).error(function(error) {
					console.log('err', error);
				});
			}

		},
		templateUrl : 'storageImageUpload'
	}
});
*/

zaa.factory('FileListeService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(folderId, forceReload) {
		return $q(function(resolve, reject) {
			if (folderId in service.data && forceReload !== true) {
				resolve(service.data[folderId]);
			} else {
				$http.get('admin/api-admin-storage/get-files', { params : { folderId : folderId } }).success(function(response) {
					service.data[folderId] = response;
					resolve(response);
				});
			}
		});

	}

	return service;
});

zaa.factory('FileIdService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(fileId, forceReload) {
		return $q(function(resolve, reject) {
			if (fileId in service.data && forceReload !== true) {
				//console.log('request existing fileId', fileId);
				resolve(service.data[fileId]);
			} else {
				$http.get('admin/api-admin-storage/file-path', { params: { fileId : fileId } }).success(function(response) {
					service.data[fileId] = response;
					//console.log('request NOT EXISTING fileId', fileId);
					resolve(response);
				}).error(function(response) {
					console.log('Error while loading fileID ' + fileId, response);
				})
			}
		});
	}

	return service;
});

zaa.factory('ImageIdService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(imageId, forceReload) {
		return $q(function(resolve, reject) {
			if (imageId in service.data && forceReload !== true) {
				//console.log('request existing imageId', imageId);
				resolve(service.data[imageId]);
			} else {
				$http.get('admin/api-admin-storage/image-path', { params: { imageId : imageId } }).success(function(response) {
					service.data[imageId] = response;
					//console.log('request NOT EXISTING imageId', imageId);
					resolve(response);
				}).error(function(response) {
					console.log('Error while loading imageId ' + imageId, response);
				})
			}
		});
	}

	return service;
});

zaa.directive('storageFileUpload', function($http, FileIdService) {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope) {

			scope.modal = true;
			scope.fileinfo = null;

			scope.select = function(fileId) {
				scope.toggleModal();
				scope.ngModel = fileId;
			}

			scope.toggleModal = function() {
				scope.modal = !scope.modal;
			}

			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n != 0 && n != null && n !== undefined) {
					FileIdService.get(n).then(function(response) {
						scope.fileinfo = response;
					});
				}
			});
		},
		templateUrl : 'storageFileUpload'
	}
});

zaa.directive('storageImageUpload', function($http, ApiAdminFilter, ImageIdService) {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope) {

            scope.imageLoading = false;
			scope.fileId = 0;
			scope.filterId = 0;
			scope.imageinfo = null;
			scope.filters = ApiAdminFilter.query();

			scope.filterApply = function() {
				if (scope.fileId == 0) {
					alert('Sie müssen zuerst eine Datei auswählen um den Filter anzuwenden.');
					return;
				}

                scope.imageLoading = true;

				$http.post('admin/api-admin-storage/image-upload', $.param({ fileId : scope.fileId, filterId : scope.filterId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(success) {
		        	if (!success) {
		        		alert('Beim Anwenden des Filters auf die Datei ist ein Fehler Passiert');
		        		console.log(success);
		        	} else {
		        		scope.ngModel = success.id;
		        	}

                    scope.imageLoading = false;
				}).error(function(error) {
					alert('Beim Anwenden des Filters auf die Datei ist ein Fehler Passiert');
	        		console.log(error);

                    scope.imageLoading = false;
				});
			};

			scope.$watch(function() { return scope.filterId }, function(n, o) {
				if (n != 0 && n !== undefined && scope.fileId !== 0) {
					scope.filterApply();
				}
			});

			scope.$watch(function() { return scope.fileId }, function(n, o) {
				if (n != 0 && n !== undefined) {
					scope.filterApply();
				}
			});

			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n != 0 && n != null && n !== undefined) {
					ImageIdService.get(n).then(function(response) {
						scope.imageinfo = response;
						scope.filterId = response.filter_id;
						scope.fileId = response.file_id;
					});
				}
			})
		},
		templateUrl : 'storageImageUpload'
	}
});

/**
 * FILE MANAGER DIR
 */
zaa.directive("storageFileManager", function(FileListeService, Upload) {
	return {
		restrict : 'E',
		transclude : false,
		scope : {
			allowSelection : '@selection'
		},
		transclude : false,
		controller : function($scope, $http, $timeout) {

			$scope.showFolderForm = false;

			$scope.files = [];

			$scope.folders = [];

			$scope.currentFolderId = 0;

			$scope.selectedFiles = [];

			$scope.uploading = false;

			$scope.serverProcessing = false;

			$scope.uploadResults = null;

			$scope.$watch('uploadingfiles', function (uploadingfiles) {
		        if (uploadingfiles != null) {
					$scope.uploadResults = 0;
					$scope.uploading = true;
		            for (var i = 0; i < uploadingfiles.length; i++) {
		                $scope.errorMsg = null;
		                (function (uploadingfiles) {
		                	$scope.uploadUsingUpload(uploadingfiles);
		                })(uploadingfiles[i]);
		            }
		        }
		    });

			$scope.$watch('uploadResults', function(n, o) {
				if ($scope.uploadingfiles != null) {
					if (n == $scope.uploadingfiles.length) {
						$scope.serverProcessing = true;
						$scope.getFiles($scope.currentFolderId, true);
					}
				}
			})

			$scope.uploadUsingUpload = function(file) {
		        file.upload = Upload.upload({
		        	url: 'admin/api-admin-storage/files-upload',
                    fields: {'folderId': $scope.currentFolderId},
                    file: file
		        });

		        file.upload.then(function (response) {
		            $timeout(function () {
		            	$scope.uploadResults++;
		            	file.processed = true;
		                file.result = response.data;
		            });
		        }, function (response) {
		            if (response.status > 0)
		                $scope.errorMsg = response.status + ': ' + response.data;
		        });

		        file.upload.progress(function (evt) {
		        	file.processed = false;
		            // Math.min is to fix IE which reports 200% sometimes
		            file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
		        });
		    }

			$scope.hasSelection = function() {
				if ($scope.selectedFiles.length > 0) {
					return true;
				}

				return false;
			}

			$scope.moveFilesTo = function(folder) {
				console.log(folder);
			}

			$scope.toggleSelection = function(file) {
				var i = $scope.selectedFiles.indexOf(file.id);
				if (i > -1) {
					$scope.selectedFiles.splice(i, 1);
				} else {
					$scope.selectedFiles.push(file.id);
				}
			}

			$scope.inSelection = function(file) {
				response = $scope.selectedFiles.indexOf(file.id);

				if (response != -1) {
					return true;
				}

				return false;
			}

			$scope.createNewFolder = function(newFolderName) {
				$http.post('admin/api-admin-storage/folder-create', $.param({ folderName : newFolderName , parentFolderId : $scope.currentFolderId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(transport) {
		        	if (transport) {
		        		$scope.showFolderForm = false;
		        		$scope.newFolderName = '';
		        		$http.get('admin/api-admin-storage/get-folders').success(function(response) {
		        			$scope.folders = response;
		        		});
		        	}
		        });
			}

			$scope.folderFormToggler = function() {
				$scope.showFolderForm = !$scope.showFolderForm;
			}

			$scope.selectFile = function(file) {
				$scope.$parent.select(file.id);
			}

            $scope.toggleModal = function() {
                $scope.$parent.toggleModal();
            }

			$scope.loadFolder = function(folderId) {
				$scope.currentFolderId = folderId;
				$scope.getFiles(folderId);
			}

			$scope.getFiles = function(folderId, forceReload) {
				FileListeService.get(folderId, forceReload).then(function(r) {
					$scope.files = r;
					$scope.uploading = false;
					$scope.serverProcessing = false;
				});
			}

			$http.get('admin/api-admin-storage/get-folders').success(function(response) {
    			$scope.folders = response;
    			$scope.getFiles(0);
    		});

		},
		templateUrl : 'storageFileManager'
	}
})<commit_msg>file manager remember folder id fixed #114<commit_after>/*
zaa.controller("UploadController", function($scope) {

	$scope.bildId = 0;

	$scope.save = function()
	{
		console.log('save', $scope.bildId);
	}

})
*/
/*
zaa.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);
*/

/*
zaa.directive('storageImageUrl', function() {
	return {
		restrict : 'E',
		scope : {
			image : '@'
		},
		controller : function($scope, $http) {
			$http.get('admin/api-admin-storage/image-path', { params: { imageId : $scope.image } }).success(function(response) {
				$scope.imagesrc = response.source;
				$scope.fileId = response.file_id;
			}).error(function(response) {
			})
		},
		template : function() {
			return '<div>{{imagesrc}} {{fileId}} </div>';
		}
	}
});
*/

/*
zaa.directive('storageFileUpload', function() {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope, element, attrs) {
			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n !== o) {
					scope.ngModel = n;
				}
			})
			scope.modal = true;
		},
		controller : function($scope, $http) {
			if ($scope.ngModel) {
				console.log('file_here', $scope.ngModel);
				$http.get('admin/api-admin-storage/file-path', { params: { fileId : $scope.ngModel } }).success(function(response) {
					$scope.filesrc = response.source_http;
				}).error(function(response) {
					console.log('error', response);
				})
			} else {
				console.log('no_file_here!');
			}

			$scope.$watch(function() { return $scope.ngModel }, function(newValue, oldValue) {
				if (newValue) {
					$scope.modal = true;
				}
			});

			$scope.openModal = function() {
				$scope.modal = !$scope.modal;
			}
		},
		templateUrl : 'storageFileUpload'
	}
});

zaa.directive('storageImageUpload', function() {
	return {
		restrict : 'E',
		scope : {
			ngModel : '=',
		},
		controller : function($scope, $http, ApiAdminFilter) {

			if ($scope.filterId == undefined) {
				$scope.filterId = 0;
			}

			if ($scope.ngModel) {
				$http.get('admin/api-admin-storage/image-path', { params: { imageId : $scope.ngModel } }).success(function(response) {
					$scope.imagesrc = response.source;
					$scope.fileId = response.file_id;
				}).error(function(response) {
					console.log('error', response);
				})
			}

			$scope.filters = ApiAdminFilter.query();

			$scope.push2 = function() {
				$http.post('admin/api-admin-storage/image-upload', $.param({ fileId : $scope.fileId, filterId : $scope.filterId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(success) {
		        	if (!success) {
		        		alert('IMAGE UPLOAD ERROR!');
		        	} else {
		        		$scope.ngModel = success.id;

		        		$scope.imagesrc = success.image.source;

		        	}
				}).error(function(error) {
					console.log('err', error);
				});
			}

		},
		templateUrl : 'storageImageUpload'
	}
});
*/

zaa.factory('FileListeService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(folderId, forceReload) {
		return $q(function(resolve, reject) {
			if (folderId in service.data && forceReload !== true) {
				resolve(service.data[folderId]);
			} else {
				$http.get('admin/api-admin-storage/get-files', { params : { folderId : folderId } }).success(function(response) {
					service.data[folderId] = response;
					resolve(response);
				});
			}
		});

	}

	return service;
});

zaa.factory('FileIdService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(fileId, forceReload) {
		return $q(function(resolve, reject) {
			if (fileId in service.data && forceReload !== true) {
				//console.log('request existing fileId', fileId);
				resolve(service.data[fileId]);
			} else {
				$http.get('admin/api-admin-storage/file-path', { params: { fileId : fileId } }).success(function(response) {
					service.data[fileId] = response;
					//console.log('request NOT EXISTING fileId', fileId);
					resolve(response);
				}).error(function(response) {
					console.log('Error while loading fileID ' + fileId, response);
				})
			}
		});
	}

	return service;
});

zaa.factory('ImageIdService', function($http, $q) {
	var service = [];

	service.data = [];

	service.get = function(imageId, forceReload) {
		return $q(function(resolve, reject) {
			if (imageId in service.data && forceReload !== true) {
				//console.log('request existing imageId', imageId);
				resolve(service.data[imageId]);
			} else {
				$http.get('admin/api-admin-storage/image-path', { params: { imageId : imageId } }).success(function(response) {
					service.data[imageId] = response;
					//console.log('request NOT EXISTING imageId', imageId);
					resolve(response);
				}).error(function(response) {
					console.log('Error while loading imageId ' + imageId, response);
				})
			}
		});
	}

	return service;
});

zaa.factory('FilemanagerFolderService', function() {
	var service = [];

	service.folderId = 0;

	service.set = function(id) {
		service.folderId = id;
	}

	service.get = function() {
		return service.folderId;
	}

	return service;
});

zaa.directive('storageFileUpload', function($http, FileIdService) {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope) {

			scope.modal = true;
			scope.fileinfo = null;

			scope.select = function(fileId) {
				scope.toggleModal();
				scope.ngModel = fileId;
			}

			scope.toggleModal = function() {
				scope.modal = !scope.modal;
			}

			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n != 0 && n != null && n !== undefined) {
					FileIdService.get(n).then(function(response) {
						scope.fileinfo = response;
					});
				}
			});
		},
		templateUrl : 'storageFileUpload'
	}
});

zaa.directive('storageImageUpload', function($http, ApiAdminFilter, ImageIdService) {
	return {
		restrict : 'E',
		scope : {
			ngModel : '='
		},
		link : function(scope) {

            scope.imageLoading = false;
			scope.fileId = 0;
			scope.filterId = 0;
			scope.imageinfo = null;
			scope.filters = ApiAdminFilter.query();

			scope.filterApply = function() {
				if (scope.fileId == 0) {
					alert('Sie müssen zuerst eine Datei auswählen um den Filter anzuwenden.');
					return;
				}

                scope.imageLoading = true;

				$http.post('admin/api-admin-storage/image-upload', $.param({ fileId : scope.fileId, filterId : scope.filterId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(success) {
		        	if (!success) {
		        		alert('Beim Anwenden des Filters auf die Datei ist ein Fehler Passiert');
		        		console.log(success);
		        	} else {
		        		scope.ngModel = success.id;
		        	}

                    scope.imageLoading = false;
				}).error(function(error) {
					alert('Beim Anwenden des Filters auf die Datei ist ein Fehler Passiert');
	        		console.log(error);

                    scope.imageLoading = false;
				});
			};

			scope.$watch(function() { return scope.filterId }, function(n, o) {
				if (n != 0 && n !== undefined && scope.fileId !== 0) {
					scope.filterApply();
				}
			});

			scope.$watch(function() { return scope.fileId }, function(n, o) {
				if (n != 0 && n !== undefined) {
					scope.filterApply();
				}
			});

			scope.$watch(function() { return scope.ngModel }, function(n, o) {
				if (n != 0 && n != null && n !== undefined) {
					ImageIdService.get(n).then(function(response) {
						scope.imageinfo = response;
						scope.filterId = response.filter_id;
						scope.fileId = response.file_id;
					});
				}
			})
		},
		templateUrl : 'storageImageUpload'
	}
});

/**
 * FILE MANAGER DIR
 */
zaa.directive("storageFileManager", function(FileListeService, Upload, FilemanagerFolderService) {
	return {
		restrict : 'E',
		transclude : false,
		scope : {
			allowSelection : '@selection'
		},
		transclude : false,
		controller : function($scope, $http, $timeout) {

			$scope.showFolderForm = false;

			$scope.files = [];

			$scope.folders = [];

			$scope.selectedFiles = [];

			$scope.uploading = false;

			$scope.serverProcessing = false;

			$scope.uploadResults = null;

			$scope.$watch('uploadingfiles', function (uploadingfiles) {
		        if (uploadingfiles != null) {
					$scope.uploadResults = 0;
					$scope.uploading = true;
		            for (var i = 0; i < uploadingfiles.length; i++) {
		                $scope.errorMsg = null;
		                (function (uploadingfiles) {
		                	$scope.uploadUsingUpload(uploadingfiles);
		                })(uploadingfiles[i]);
		            }
		        }
		    });

			$scope.$watch('uploadResults', function(n, o) {
				if ($scope.uploadingfiles != null) {
					if (n == $scope.uploadingfiles.length) {
						$scope.serverProcessing = true;
						$scope.getFiles($scope.currentFolderId, true);
					}
				}
			})

			$scope.uploadUsingUpload = function(file) {
		        file.upload = Upload.upload({
		        	url: 'admin/api-admin-storage/files-upload',
                    fields: {'folderId': $scope.currentFolderId},
                    file: file
		        });

		        file.upload.then(function (response) {
		            $timeout(function () {
		            	$scope.uploadResults++;
		            	file.processed = true;
		                file.result = response.data;
		            });
		        }, function (response) {
		            if (response.status > 0)
		                $scope.errorMsg = response.status + ': ' + response.data;
		        });

		        file.upload.progress(function (evt) {
		        	file.processed = false;
		            // Math.min is to fix IE which reports 200% sometimes
		            file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
		        });
		    }

			$scope.hasSelection = function() {
				if ($scope.selectedFiles.length > 0) {
					return true;
				}

				return false;
			}

			$scope.moveFilesTo = function(folder) {
				console.log(folder);
			}

			$scope.toggleSelection = function(file) {
				var i = $scope.selectedFiles.indexOf(file.id);
				if (i > -1) {
					$scope.selectedFiles.splice(i, 1);
				} else {
					$scope.selectedFiles.push(file.id);
				}
			}

			$scope.inSelection = function(file) {
				response = $scope.selectedFiles.indexOf(file.id);

				if (response != -1) {
					return true;
				}

				return false;
			}

			$scope.createNewFolder = function(newFolderName) {
				$http.post('admin/api-admin-storage/folder-create', $.param({ folderName : newFolderName , parentFolderId : $scope.currentFolderId }), {
		        	headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		        }).success(function(transport) {
		        	if (transport) {
		        		$scope.showFolderForm = false;
		        		$scope.newFolderName = '';
		        		$http.get('admin/api-admin-storage/get-folders').success(function(response) {
		        			$scope.folders = response;
		        		});
		        	}
		        });
			}

			$scope.folderFormToggler = function() {
				$scope.showFolderForm = !$scope.showFolderForm;
			}

			$scope.selectFile = function(file) {
				$scope.$parent.select(file.id);
			}

            $scope.toggleModal = function() {
                $scope.$parent.toggleModal();
            }

			$scope.loadFolder = function(folderId) {
				FilemanagerFolderService.set(folderId);
				$scope.currentFolderId = folderId;
				$scope.getFiles(folderId);
			}

			$scope.getFiles = function(folderId, forceReload) {
				FileListeService.get(folderId, forceReload).then(function(r) {
					$scope.files = r;
					$scope.uploading = false;
					$scope.serverProcessing = false;
				});
			}

			$http.get('admin/api-admin-storage/get-folders').success(function(response) {
    			$scope.folders = response;
    			$scope.getFiles(FilemanagerFolderService.get());
    			$scope.currentFolderId = FilemanagerFolderService.get();
    		});

		},
		templateUrl : 'storageFileManager'
	}
})<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var smaps = require('gulp-sourcemaps');

gulp.task('default', ['build']);

gulp.task('build', function() {
    var babel = require('gulp-babel');

    return gulp.src('src/**/*.js')
        .pipe(smaps.init())
        .pipe(babel())
        .pipe(smaps.write('.'))
        .pipe(gulp.dest('lib'));
});
<commit_msg>Add source roots for source maps<commit_after>'use strict';

var gulp = require('gulp');
var smaps = require('gulp-sourcemaps');

gulp.task('default', ['build']);

gulp.task('build', function() {
    var babel = require('gulp-babel');

    return gulp.src('src/**/*.js')
        .pipe(smaps.init())
        .pipe(babel())
        .pipe(smaps.write('.', {sourceRoot: '/source/src/'}))
        .pipe(gulp.dest('lib'));
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var juice = require('juice');
var sass = require('node-sass');
var nunjucksLib = require('nunjucks');
var through = require('through2');
var File = require('vinyl');

var nunjucks = new nunjucksLib.Environment(new nunjucksLib.FileSystemLoader('templates'));

gulp.task('scss', function (callback) {
  gulp.src('./scss/main.scss')
  .pipe(sass({
    outputStyle: 'expanded'
  }))
  .pipe(gulp.dest('./css'));
});

var buildTemplate = function (options, callback) {
  gutil.log('Compiling SCSS...');
  sass.render({
    file: './scss/main.scss'
  }, function (err, result) {
    if(err) {
      return callback(err);
    }

    var css = result.css.toString();

    var template = path.resolve(process.cwd(), options.template );
    gutil.log('Rendering Template %s...', template);
    var renderedTemplate = nunjucks.render(template, {
      css: css,
      content: {
        subject: 'Hello there!'
      }
    });

    gutil.log('Inlining CSS...');
    var inlined = juice(renderedTemplate, {
      preserveMediaQueries: true,
      removeStyleTags: false
    });

    if(options.output) {
      fs.writeFileSync(path.resolve(process.cwd(), './build/' + options.output), inlined);
    }
    else {
      fs.writeFileSync(path.resolve(process.cwd(), './build/' + path.basename(options.template)), inlined);
    }

    return callback();
  });
};

gulp.task('build', function (next) {
  var argv = require('yargs')
    .alias('t', 'template')
    .alias('d', 'data')
    .alias('o', 'output')
    .demand(['t'])
    .argv;

  buildTemplate({
    template: argv.template,
    data: argv.data,
    output: argv.output
  }, next);
});

gulp.task('manualbuild', function (next) {
  var spawn = require('child_process').spawn;

  var proc = spawn('gulp', ['build', '-t', 'templates/new-user-no-activity.html'], {stdio: 'inherit'});

  proc.on('close', function () {
    next();
  });
});

gulp.task('mail', function (next) {
  var mailgun = require('mailgun-js')({
    apiKey: process.env.MG_APIKEY,
    domain: process.env.MG_DOMAIN
  });

  var argv = require('yargs')
    .alias('f', 'file')
    .alias('t', 'to')
    .demand(['f'])
    .argv;

  mailgun.messages().send({
    from: 'Carina Email Test <noreply@getcarina.com>',
    to: argv.to,
    subject: 'Carina Email Test',
    html: fs.readFileSync(path.join(process.cwd(), argv.file)).toString('utf-8')
  }, function (err, body) {
    if(err) {
      return next(err);
    }

    return next();
  });
});

gulp.task('watch', function () {
  gulp.watch(['scss/**/*.scss', 'templates/**/*.html'], ['manualbuild']);
});
<commit_msg>Adds a check for a missing build directory, creating if not found<commit_after>var fs = require('fs');
var path = require('path');

var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var juice = require('juice');
var sass = require('node-sass');
var nunjucksLib = require('nunjucks');
var through = require('through2');
var File = require('vinyl');

var nunjucks = new nunjucksLib.Environment(new nunjucksLib.FileSystemLoader('templates'));

gulp.task('scss', function (callback) {
  gulp.src('./scss/main.scss')
  .pipe(sass({
    outputStyle: 'expanded'
  }))
  .pipe(gulp.dest('./css'));
});

var buildTemplate = function (options, callback) {
  gutil.log('Compiling SCSS...');
  sass.render({
    file: './scss/main.scss'
  }, function (err, result) {
    if(err) {
      return callback(err);
    }

    var css = result.css.toString();

    var template = path.resolve(process.cwd(), options.template );
    gutil.log('Rendering Template %s...', template);
    var renderedTemplate = nunjucks.render(template, {
      css: css,
      content: {
        subject: 'Hello there!'
      }
    });

    gutil.log('Inlining CSS...');
    var inlined = juice(renderedTemplate, {
      preserveMediaQueries: true,
      removeStyleTags: false
    });

    // ensure we've got a valid build directory
    var buildPath = path.resolve(process.cwd(), './build');
    try {
      fs.statSync(buildPath)
    }
    catch (e) {
      gutil.log('Build directory not found, creating...');
      if (e.code === 'ENOENT') {
        fs.mkdirSync(buildPath)
      }
      else {
        // something else is going on here
        gutil.log('Unknown error checking build directory...');
        process.exit(1);
      }
    }

    if(options.output) {
      fs.writeFileSync(path.resolve(buildPath, options.output), inlined);
    }
    else {
      fs.writeFileSync(path.resolve(buildPath, path.basename(options.template)), inlined);
    }

    return callback();
  });
};

gulp.task('build', function (next) {
  var argv = require('yargs')
    .alias('t', 'template')
    .alias('d', 'data')
    .alias('o', 'output')
    .demand(['t'])
    .argv;

  buildTemplate({
    template: argv.template,
    data: argv.data,
    output: argv.output
  }, next);
});

gulp.task('manualbuild', function (next) {
  var spawn = require('child_process').spawn;

  var proc = spawn('gulp', ['build', '-t', 'templates/new-user-no-activity.html'], {stdio: 'inherit'});

  proc.on('close', function () {
    next();
  });
});

gulp.task('mail', function (next) {
  var mailgun = require('mailgun-js')({
    apiKey: process.env.MG_APIKEY,
    domain: process.env.MG_DOMAIN
  });

  var argv = require('yargs')
    .alias('f', 'file')
    .alias('t', 'to')
    .demand(['f'])
    .argv;

  mailgun.messages().send({
    from: 'Carina Email Test <noreply@getcarina.com>',
    to: argv.to,
    subject: 'Carina Email Test',
    html: fs.readFileSync(path.join(process.cwd(), argv.file)).toString('utf-8')
  }, function (err, body) {
    if(err) {
      return next(err);
    }

    return next();
  });
});

gulp.task('watch', function () {
  gulp.watch(['scss/**/*.scss', 'templates/**/*.html'], ['manualbuild']);
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var concat = require('gulp-concat');
var cssmin = require('gulp-cssmin');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var pump = require('pump');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');

var webpackOptions = require('./webpack.config');

gulp.task('webpack', function(callback) {
  webpack(webpackOptions, function(err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack', err);
    }
    gutil.log('[webpack]', stats.toString());
    callback();
  });
});

gulp.task('webpack-dev-server', function(callback) {
  var compiler = webpack(webpackOptions);

  new WebpackDevServer(compiler, {
    watch: true,
    publicPath: webpackOptions.output.publicPath,
    proxy: {
      '/**': {
        target: 'https://budget.bristol.fela.london',
        secure: true,
        changeOrigin: true
      }
    }
  }).listen(8080, '0.0.0.0', function(err) {
      if (err) {
        throw new gutil.PluginError('webpack-dev-server', err);
      }
      gutil.log('[webpack-dev-server] 0.0.0.0:8080');
  });
});

gulp.task('uglify', function(callback) {
  pump([
    gulp.src('web/js/main.js'),
    uglify(),
    gulp.dest('web/js/build/')
  ], callback);
});

gulp.task('concat', function() {
  return gulp.src([
    'web/js/src/lib/js.cookie.min.js',
    'web/js/build/main.js'
  ]).pipe(concat('main.min.js', {newLine: ';'}))
  .pipe(gulp.dest('web/js/'));
});

gulp.task('less', function() {
  return gulp.src('resources/less/*.less')
  .pipe(less({
    paths: [path.join(__dirname, 'resources', 'less')]
  }))
  .pipe(gulp.dest('web/css'));
});

gulp.task('cssmin', function() {
  gulp.src('web/css/budget.css')
  .pipe(cssmin())
  .pipe(rename({suffix: '.min'}))
  .pipe(gulp.dest('web/css/'))
});

gulp.task('compile_js', ['webpack']);
gulp.task('minify_js', ['uglify', 'concat']);
gulp.task('build_js', ['compile_js', 'minify_js']);

gulp.task('build_css', ['less', 'cssmin']);

gulp.task('default', ['build_js', 'build_css']);

<commit_msg>Run webpack before minifying<commit_after>'use strict';

var path = require('path');

var concat = require('gulp-concat');
var cssmin = require('gulp-cssmin');
var gulp = require('gulp');
var gutil = require('gulp-util');
var less = require('gulp-less');
var pump = require('pump');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');

var webpackOptions = require('./webpack.config');

gulp.task('webpack', function(callback) {
  webpack(webpackOptions, function(err, stats) {
    if (err) {
      throw new gutil.PluginError('webpack', err);
    }
    gutil.log('[webpack]', stats.toString());
    callback();
  });
});

gulp.task('webpack-dev-server', function(callback) {
  var compiler = webpack(webpackOptions);

  new WebpackDevServer(compiler, {
    watch: true,
    publicPath: webpackOptions.output.publicPath,
    proxy: {
      '/**': {
        target: 'https://budget.bristol.fela.london',
        secure: true,
        changeOrigin: true
      }
    }
  }).listen(8080, '0.0.0.0', function(err) {
      if (err) {
        throw new gutil.PluginError('webpack-dev-server', err);
      }
      gutil.log('[webpack-dev-server] 0.0.0.0:8080');
  });
});

gulp.task('uglify', ['webpack'], function(callback) {
  pump([
    gulp.src('web/js/main.js'),
    uglify(),
    gulp.dest('web/js/build/')
  ], callback);
});

gulp.task('concat', ['uglify'], function() {
  return gulp.src([
    'web/js/src/lib/js.cookie.min.js',
    'web/js/build/main.js'
  ]).pipe(concat('main.min.js', {newLine: ';'}))
  .pipe(gulp.dest('web/js/'));
});

gulp.task('less', function() {
  return gulp.src('resources/less/*.less')
  .pipe(less({
    paths: [path.join(__dirname, 'resources', 'less')]
  }))
  .pipe(gulp.dest('web/css'));
});

gulp.task('cssmin', function() {
  gulp.src('web/css/budget.css')
  .pipe(cssmin())
  .pipe(rename({suffix: '.min'}))
  .pipe(gulp.dest('web/css/'))
});

gulp.task('compile_js', ['webpack']);
gulp.task('minify_js', ['concat']);
gulp.task('build_js', ['compile_js', 'minify_js']);

gulp.task('build_css', ['less', 'cssmin']);

gulp.task('default', ['build_js', 'build_css']);

<|endoftext|>


<commit_before>var gulp = require('gulp')

var browserify = require('browserify')
var del = require('del');
var documentation = require('gulp-documentation')
var karmaServer = require('karma').Server;
var source = require('vinyl-source-stream')
var serve = require('gulp-serve')
var standard = require('gulp-standard')
var shell = require('gulp-shell')
var ts = require('gulp-typescript')
var rename = require('gulp-rename')
var tsd = require('gulp-tsd')
var tslint = require('gulp-tslint')

var paths = {
  mapillaryjs: 'mapillaryjs',
  ts: {
    src: './src/**/*.ts',
    tests: './spec/**/*.ts',
    dest: 'dist',
    testDest: 'dist/spec'
  },
  js: {
    src: './dist/**/*.js',
    tests: './spec/**/*.js'
  },
  devFiles: {
    src: ['./dist/mapillary-js.css', './dist/bundle.js'],
    dest: 'debug'
  }
}

var config = {
  ts: {
      noImplicitAny: true,
      target: 'ES5',
      module: 'commonjs'
    }
}

gulp.task('browserify', ['typescript'], function () {
  var bundler = browserify({
    entries: ['./dist/Viewer.js'],
    debug: true,
    fullPaths: false,
    standalone: 'Mapillary'
  })

  return bundler
    .bundle()
    .pipe(source('./dist/Viewer.js'))
    .pipe(rename('bundle.js'))
    .pipe(gulp.dest('./dist/'))
})

gulp.task('clean', function () {
  return del([
    'html-documentation',
    'dist/**/*',
    'debug/**/*.js'
  ])
})

gulp.task('copy-dev-files', ['browserify'], function () {
  return gulp.src(paths.devFiles.src)
    .pipe(gulp.dest(paths.devFiles.dest))
})

gulp.task('documentation', ['browserify'], function () {
    gulp.src(['./dist/Viewer.js', './dist/API.js'])
    .pipe(documentation({format: 'html' }))
    .pipe(gulp.dest('html-documentation'))
})

gulp.task('js-lint', function () {
  return gulp.src('./Gulpfile.js')
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true
    }))
})

gulp.task('serve', ['browserify'], serve('.'))

gulp.task('test', function (done) {
  new karmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
})

gulp.task('test-watch', function (done) {
  new karmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
})

gulp.task('ts-lint', function () {
  return gulp.src(paths.ts.src)
    .pipe(tslint())
    .pipe(tslint.report('verbose'))
})

gulp.task('tsd', function (callback) {
  tsd({
    command: 'reinstall',
    config: './tsd.json'
  }, callback)
})

gulp.task('typescript', ['ts-lint', 'typescript-src', 'typescript-test'], function () {})

gulp.task('typescript-src', ['tsd'], function () {
  gulp.src(paths.ts.src)
    .pipe(ts(config.ts))
    .pipe(gulp.dest(paths.ts.dest))
})

gulp.task('typescript-test', ['tsd'], function () {
  gulp.src(paths.ts.tests)
    .pipe(ts(config.ts))
    .pipe(gulp.dest(paths.ts.testDest))
})

gulp.task('watch', ['browserify'], function () {
    gulp.watch([paths.ts.src, paths.ts.tests], ['browserify'])
})

gulp.task('default', ['serve', 'watch'])
<commit_msg>Fix synch in gulp<commit_after>var gulp = require('gulp')

var browserify = require('browserify')
var del = require('del');
var documentation = require('gulp-documentation')
var karmaServer = require('karma').Server;
var source = require('vinyl-source-stream')
var serve = require('gulp-serve')
var standard = require('gulp-standard')
var shell = require('gulp-shell')
var ts = require('gulp-typescript')
var rename = require('gulp-rename')
var tsd = require('gulp-tsd')
var tslint = require('gulp-tslint')

var paths = {
  mapillaryjs: 'mapillaryjs',
  ts: {
    src: './src/**/*.ts',
    tests: './spec/**/*.ts',
    dest: 'dist',
    testDest: 'dist/spec'
  },
  js: {
    src: './dist/**/*.js',
    tests: './spec/**/*.js'
  },
  devFiles: {
    src: ['./dist/mapillary-js.css', './dist/bundle.js'],
    dest: 'debug'
  }
}

var config = {
  ts: {
      noImplicitAny: true,
      target: 'ES5',
      module: 'commonjs'
    }
}

gulp.task('browserify', ['typescript'], function () {
  var bundler = browserify({
    entries: ['./dist/Viewer.js'],
    debug: true,
    fullPaths: false,
    standalone: 'Mapillary'
  })

  bundler
    .bundle()
    .pipe(source('./dist/Viewer.js'))
    .pipe(rename('bundle.js'))
    .pipe(gulp.dest('./dist/'))
})

gulp.task('clean', function () {
  return del([
    'html-documentation',
    'dist/**/*',
    'debug/**/*.js'
  ])
})

gulp.task('copy-dev-files', ['browserify'], function () {
  return gulp.src(paths.devFiles.src)
    .pipe(gulp.dest(paths.devFiles.dest))
})

gulp.task('documentation', ['browserify'], function () {
    gulp.src(['./dist/Viewer.js', './dist/API.js'])
    .pipe(documentation({format: 'html' }))
    .pipe(gulp.dest('html-documentation'))
})

gulp.task('js-lint', function () {
  return gulp.src('./Gulpfile.js')
    .pipe(standard())
    .pipe(standard.reporter('default', {
      breakOnError: true
    }))
})

gulp.task('serve', ['browserify'], serve('.'))

gulp.task('test', function (done) {
  new karmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
})

gulp.task('test-watch', function (done) {
  new karmaServer({
    configFile: __dirname + '/karma.conf.js',
    singleRun: false
  }, done).start();
})

gulp.task('ts-lint', ['tsd'], function (cb) {
    var stream = gulp.src(paths.ts.src)
      .pipe(tslint())
      .pipe(tslint.report('verbose'))
    return stream
})

gulp.task('tsd', function (cb) {
  tsd({
    command: 'reinstall',
    config: './tsd.json'
  }, cb())
})

gulp.task('typescript', ['ts-lint', 'typescript-src', 'typescript-test'], function (cb) {cb()})

gulp.task('typescript-src', function () {
    var stream = gulp.src(paths.ts.src)
      .pipe(ts(config.ts))
      .pipe(gulp.dest(paths.ts.dest))
    return stream
})

gulp.task('typescript-test', function () {
  var stream = gulp.src(paths.ts.tests)
    .pipe(ts(config.ts))
    .pipe(gulp.dest(paths.ts.testDest))
  return stream
})

gulp.task('watch', [], function () {
    gulp.watch([paths.ts.src, paths.ts.tests], ['browserify'])
})

gulp.task('default', ['serve', 'watch'])
<|endoftext|>


<commit_before>var gulp = require('gulp');

var javascripts = [
  'index.js',
  'lib/**/*.js',
  'test/**/*.js'
];

gulp.task('jscs', function () {
  var jscs = require('gulp-jscs');
  return gulp.src(javascripts)
    .pipe(jscs());
});

gulp.task('lint', function () {
  var jshint = require('gulp-jshint');
  return gulp.src(javascripts)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('test', function () {
  var mocha = require('gulp-mocha');
  return gulp.src('test/**/*.js', {
    read: false
  })
    .pipe(mocha({
      bail: true
    }));
});

gulp.task('watch', function () {
  return gulp.watch(javascripts, ['default']);
});

gulp.task('default', ['test']);
<commit_msg>Watch Gulpfile<commit_after>var gulp = require('gulp');

var javascripts = [
  'Gulpfile.js',
  'index.js',
  'lib/**/*.js',
  'test/**/*.js'
];

gulp.task('jscs', function () {
  var jscs = require('gulp-jscs');
  return gulp.src(javascripts)
    .pipe(jscs());
});

gulp.task('lint', function () {
  var jshint = require('gulp-jshint');
  return gulp.src(javascripts)
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('test', function () {
  var mocha = require('gulp-mocha');
  return gulp.src('test/**/*.js', {
    read: false
  })
    .pipe(mocha({
      bail: true
    }));
});

gulp.task('watch', function () {
  return gulp.watch(javascripts, ['default']);
});

gulp.task('default', ['test']);
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    rimraf = require('gulp-rimraf'),
    env = require('node-env-file'),
    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    autoprefixer = require('gulp-autoprefixer'),
    minify = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    sass = require('gulp-sass'),
    plumber = require('gulp-plumber'),
    karma = require('karma').server,
    uglify = require('gulp-uglify'),
    express = require('express'),
    refresh = require('gulp-livereload'),
    livereload = require('connect-livereload'),
    lrserver = require('tiny-lr')(),
    gutil = require('gulp-util'),
    livereloadport = 35729,
    serverport = 5000,
    server = express();

env(__dirname + '/.env');

var PRODUCTION = process.env.ENVIRONMENT === 'production',
    DIST_FOLDER = 'dist',
    KARMA_CONFIG = '/karma.conf.js',
    BUNDLE_FILENAME = "main";

server.use(livereload({port: livereloadport}));
server.use(express.static('./' + DIST_FOLDER));

server.all('/*', function (req, res) {
    res.sendfile('index.html', { root: DIST_FOLDER });
});

gulp.task('build', ['clean'], function () {
    gulp.start(['views', 'styles', 'browserify']);
});

gulp.task('clean', function () {
    return gulp.src('./' + DIST_FOLDER + '/', { read: false })
        .pipe(plumber())
        .pipe(rimraf({force: true}));
});

gulp.task('lint', function () {
    gulp.src('scripts/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('styles', function () {
    var stream = gulp.src(['bootstrapper.scss', 'styles/*.scss'])
        .pipe(concat(BUNDLE_FILENAME + '.css'))
        .pipe(plumber())
        .pipe(sass())
        .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'));
    if (PRODUCTION)
        stream = stream.pipe(minify());
    stream
        .pipe(gulp.dest(DIST_FOLDER + '/css/'))
        .pipe(refresh(lrserver));
});

gulp.task('browserify', function () {
    var stream = browserify({
        entries: ['./bootstrapper.js'],
        noParse: [
            require.resolve('jquery'),
            require.resolve('angular/angular'),
            require.resolve('angular/angular.mocks'),
            require.resolve('angular/angular.sanitize'),
            require.resolve('angular/angular.resource'),
            require.resolve('angular/angular.route'),
            require.resolve('angular/angular.animate'),
            require.resolve('underscore')
        ]
    })
        .bundle({ debug: !PRODUCTION })
        .on('error', gutil.log)
        .pipe(source('main.js'));
    if (PRODUCTION)
        stream = stream.pipe(streamify(uglify()));
    stream
        .pipe(gulp.dest('./' + DIST_FOLDER + '/js'))
        .pipe(refresh(lrserver));
});

gulp.task('test', function (done) {
    karma.start({
        configFile: __dirname + KARMA_CONFIG,
        singleRun: PRODUCTION
    }, done);
});

gulp.task('views', function () {
    gulp.src('index.html')
        .pipe(gulp.dest(DIST_FOLDER));
    gulp.src('views/**/*')
        .pipe(gulp.dest(DIST_FOLDER + '/views/'))
        .pipe(refresh(lrserver));
});

gulp.task('watch', ['build', 'serve'], function () {
    gulp.watch(['bootstrapper.js', 'scripts/**/*.js'], [
        'browserify'
    ]);

    gulp.watch(['bootstrapper.css', 'styles/**/*.scss'], [
        'styles'
    ]);

    gulp.watch(['views/**/*.html'], [
        'views'
    ]);
});

gulp.task('watch-test', ['build', 'serve', 'test']);

gulp.task('serve', function () {
    server.listen(serverport);
    refresh.listen(livereloadport);
    console.log('App listening on http://localhost:' + serverport);
});

gulp.task('default', ['build']);<commit_msg>Fix reload for css bootstrapper<commit_after>'use strict';

var gulp = require('gulp'),
    jshint = require('gulp-jshint'),
    rimraf = require('gulp-rimraf'),
    env = require('node-env-file'),
    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    streamify = require('gulp-streamify'),
    autoprefixer = require('gulp-autoprefixer'),
    minify = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    sass = require('gulp-sass'),
    plumber = require('gulp-plumber'),
    karma = require('karma').server,
    uglify = require('gulp-uglify'),
    express = require('express'),
    refresh = require('gulp-livereload'),
    livereload = require('connect-livereload'),
    lrserver = require('tiny-lr')(),
    gutil = require('gulp-util'),
    livereloadport = 35729,
    serverport = 5000,
    server = express();

env(__dirname + '/.env');

var PRODUCTION = process.env.ENVIRONMENT === 'production',
    DIST_FOLDER = 'dist',
    KARMA_CONFIG = '/karma.conf.js',
    BUNDLE_FILENAME = "main";

server.use(livereload({port: livereloadport}));
server.use(express.static('./' + DIST_FOLDER));

server.all('/*', function (req, res) {
    res.sendfile('index.html', { root: DIST_FOLDER });
});

gulp.task('build', ['clean'], function () {
    gulp.start(['views', 'styles', 'browserify']);
});

gulp.task('clean', function () {
    return gulp.src('./' + DIST_FOLDER + '/', { read: false })
        .pipe(plumber())
        .pipe(rimraf({force: true}));
});

gulp.task('lint', function () {
    gulp.src('scripts/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('styles', function () {
    var stream = gulp.src(['bootstrapper.scss', 'styles/*.scss'])
        .pipe(concat(BUNDLE_FILENAME + '.css'))
        .pipe(plumber())
        .pipe(sass())
        .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'));
    if (PRODUCTION)
        stream = stream.pipe(minify());
    stream
        .pipe(gulp.dest(DIST_FOLDER + '/css/'))
        .pipe(refresh(lrserver));
});

gulp.task('browserify', function () {
    var stream = browserify({
        entries: ['./bootstrapper.js'],
        noParse: [
            require.resolve('jquery'),
            require.resolve('angular/angular'),
            require.resolve('angular/angular.mocks'),
            require.resolve('angular/angular.sanitize'),
            require.resolve('angular/angular.resource'),
            require.resolve('angular/angular.route'),
            require.resolve('angular/angular.animate'),
            require.resolve('underscore')
        ]
    })
        .bundle({ debug: !PRODUCTION })
        .on('error', gutil.log)
        .pipe(source('main.js'));
    if (PRODUCTION)
        stream = stream.pipe(streamify(uglify()));
    stream
        .pipe(gulp.dest('./' + DIST_FOLDER + '/js'))
        .pipe(refresh(lrserver));
});

gulp.task('test', function (done) {
    karma.start({
        configFile: __dirname + KARMA_CONFIG,
        singleRun: PRODUCTION
    }, done);
});

gulp.task('views', function () {
    gulp.src('index.html')
        .pipe(gulp.dest(DIST_FOLDER));
    gulp.src('views/**/*')
        .pipe(gulp.dest(DIST_FOLDER + '/views/'))
        .pipe(refresh(lrserver));
});

gulp.task('watch', ['build', 'serve'], function () {
    gulp.watch(['bootstrapper.js', 'scripts/**/*.js'], [
        'browserify'
    ]);

    gulp.watch(['bootstrapper.scss', 'styles/**/*.scss'], [
        'styles'
    ]);

    gulp.watch(['views/**/*.html'], [
        'views'
    ]);
});

gulp.task('watch-test', ['build', 'serve', 'test']);

gulp.task('serve', function () {
    server.listen(serverport);
    refresh.listen(livereloadport);
    console.log('App listening on http://localhost:' + serverport);
});

gulp.task('default', ['build']);<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var rimraf = require('rimraf');
var argv = require('yargs').argv;
var notifier = require('node-notifier');
var template = require('gulp-template');
var fs = require('fs');
var path = require('path');
var filter = require('gulp-filter');
var addsrc = require('gulp-add-src');
var liveReload = require('gulp-livereload');
var liveReloadServer = require('tiny-lr')();
var connectLiveReload = require('connect-livereload');
var express = require('express');
var through = require('through2');
var reduceStream = require('through2-reduce');
var File = require('vinyl');

if ( !argv.site ) {
  gutil.log('Please define the site to be rendered with the --site option');
  gutil.log('E.e gulp --site examples/demo');
  process.exit(1);
}

var db = {};
var siteConfig;

function logErrorAndNotify(e) {
  notifier.notify({
    title:'Error on ' + e.plugin,
    message: e.message
  });
  gutil.log('Error running task', e.plugin);
  gutil.log(e.message);
  gutil.log(e.stack);
}

// Build Configuration
function initConfig(sitePathOrConfig) {
  [
    // Check under the working directory
    path.join(process.cwd(), sitePathOrConfig + '.js'),
    path.join(process.cwd(), sitePathOrConfig, 'config.js'),
    path.join(process.cwd(), sitePathOrConfig),

    // Check under the directory where gulp was started
    path.join(process.env.INIT_CWD, sitePathOrConfig + '.js'),
    path.join(process.env.INIT_CWD, sitePathOrConfig, 'config.js'),
    path.join(process.env.INIT_CWD, sitePathOrConfig)
  ]
  .some(function(configFile) {
    var stat;
    try {
      stat = fs.lstatSync(configFile);
    } catch(err) {}
    if ( stat && stat.isFile() ) {
      gutil.log('Using configuration in ', configFile);
      siteConfig = require(path.resolve(configFile));
      siteConfig.configFile = configFile;
      siteConfig.rootPath = path.dirname(siteConfig.configFile);
      return true;
    }
  });
  if ( !siteConfig || !siteConfig.paths ) {
    gutil.log('Invalid site configuration in ', sitePathOrConfig);
    process.exit(1);
  }
}
initConfig(argv.site.replace(/\/$/, ''));

// Config
gulp.task('config', initConfig);
gulp.watch([
  'Gulpfile.js',
  siteConfig.configFile
], ['lint', 'config']);

// Clean
gulp.task('clean', function() {
  rimraf.sync(siteConfig.paths.dist);
});

// JSHint
var jshint = require('gulp-jshint');
gulp.task('lint', function() {
  return gulp.src([
    'Gulpfile.js',
    siteConfig.configFile,
    siteConfig.paths.mainModule + '/**/*.js',
    siteConfig.paths.features + '/**/*.js',
  ])
  .pipe(jshint())
  .on('error', logErrorAndNotify)
  .pipe(jshint.reporter('default'));
});

// Browserify
var browserify = require('gulp-browserify');
var uglify = require('gulp-uglify');
gulp.task('browserify', ['lint'], function() {
  var stream = gulp.src([
    siteConfig.paths.mainJS
  ])
  .pipe(browserify())
  .on('error', logErrorAndNotify)
  .pipe(concat('main.js'))
  .on('error', logErrorAndNotify);

  if ( siteConfig.browserify.enableUglify ) {
    stream.pipe(uglify())
    .on('error', logErrorAndNotify);
  }

  stream.pipe(gulp.dest(siteConfig.paths.dist))
  .on('error', logErrorAndNotify);
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.js',
  siteConfig.paths.features + '/**/*.js',
  siteConfig.rootPath + '/**/*.js',
],[
  'lint',
  'browserify'
]);

// View partials
gulp.task('templates', function() {
  siteConfig.client.bootstraps.templates = {};
  return gulp.src([
    siteConfig.paths.mainModule + '/**/*.html',
    siteConfig.paths.features + '/**/*.html',
    siteConfig.rootPath + '/**/*.html'
  ])
  .pipe(through.obj(function (file, enc, next) {
    var fn = path.relative('./', file.path);
    siteConfig.client.bootstraps.templates[fn] = file.contents.toString();
    next();
  }));
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.html',
  siteConfig.paths.features + '/**/*.html',
  siteConfig.rootPath + '/**/*.html'
], ['index']);

// Index template and partials
gulp.task('index', ['templates', 'menu'], function() {
  var stream;
  siteConfig.client.url = function(suffix) {
    return  siteConfig.server.baseUrl + suffix.replace(/^\//,'');
  };

  // Get bootstrapped content from DB
  siteConfig.client.footer = db.footer;
  siteConfig.client.header = db.header;

  // Process
  stream = gulp.src([siteConfig.paths.mainHTML])
  .pipe(template(siteConfig))
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.mainHTML], ['index']);

// Assets
gulp.task('assets', function() {
  var stream = gulp.src([
    siteConfig.paths.assets + '/**/*.*',
    'node_modules/font-awesome/fonts/*.*'
  ])
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist + '/assets'));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.assets + '/**/*.*'], ['assets']);

// SASS
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
// Styles task
gulp.task('styles', function() {
  var stream = gulp.src([
    siteConfig.paths.mainModule + '/css/main.scss',
    siteConfig.paths.features + '/**/*.scss',
    siteConfig.paths.styles + '/**/*.scss',
    siteConfig.rootPath + '/**/*.scss',
  ])
  // Concat before compile, so that includes are available in dynamic styles
  .pipe(concat('main.css'))
  // Add separate files at this point E.g build icons separately to circumvent IE's rule limit
  .pipe(addsrc([
    siteConfig.paths.mainModule + '/css/icons.scss'
  ]))
  .pipe(
    sass({
      includePaths: [
        siteConfig.paths.mainModule + '/css',
        process.cwd() + '/node_modules',
        siteConfig.rootPath,
      ]
    }).on('error', logErrorAndNotify)
  )
  .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
  .on('error', logErrorAndNotify);

  if ( siteConfig.styles.enableMinify ) {
    stream.pipe(cssmin())
    .on('error', logErrorAndNotify);
  }

  stream.pipe(gulp.dest(siteConfig.paths.dist));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.scss',
  siteConfig.paths.features + '/**/*.scss',
  siteConfig.paths.styles + '/**/*.scss',
], [
  'styles'
]);

// Server
var server = express();
server.use(siteConfig.server.baseUrl, express.static(siteConfig.paths.dist));

if ( siteConfig.server.enableLiveReload ) {
  server.use(connectLiveReload({port: siteConfig.liveReloadPort}));
}

if ( siteConfig.server.enablePushState ) {
  server.all(siteConfig.server.baseUrl + '[^.]+', function(req, res) {
    res.sendFile('index.html', {
      root: siteConfig.paths.dist
    });
  });
}

gulp.task('server', ['build'], function() {
  server.listen(siteConfig.server.port);
  if ( siteConfig.server.enableLiveReload ) {
    liveReloadServer.listen(siteConfig.server.liveReloadPort);
  }
});

// MENU
var yaml = require('gulp-yaml');
var markdown = require('gulp-markdown');
var marked = require('marked');
var frontMatter = require('gulp-front-matter');
var entityConvert = require('gulp-entity-convert');
marked.setOptions(siteConfig.markdown);

gulp.task('menu', function(){
  var mdFilter = filter('**/*.md', {restore: true});
  var yamlFilter = filter('**/*.yaml', {restore: true});
  var stream = gulp.src(['**/*.yaml', '**/*.md'], {cwd:siteConfig.paths.pages})

  // YAML -> JSON
  .pipe(yamlFilter)
  .pipe(yaml())
  .on('error', logErrorAndNotify)
  .pipe(yamlFilter.restore)

  // Markdown -> HTML
  .pipe(mdFilter)
  .pipe(frontMatter({
    property: 'frontMatterData',
    remove: true
  }))
  .pipe(entityConvert())
  .pipe(markdown(siteConfig.markdown))

  // Frontmatter + HTML -> JSON
  .pipe(through.obj(function (file, enc, next) {
    if ( file.isBuffer() ) {
      file.frontMatterData.content = file.contents.toString();
      file.contents = new Buffer(JSON.stringify(file.frontMatterData));
      file.path = file.path.replace(/\.html$/, '.json');
    }
    this.push(file);
    return next();
  }))
  .on('error', logErrorAndNotify)
  .pipe(mdFilter.restore)

  // JSON -> api/pages/*.json
  .pipe(gulp.dest(siteConfig.paths.dist + '/api/'))

  // menu.json
  .pipe(through.obj(function (file, enc, next) {
    this.push(file);
    return next();
  }))
  // Convert a stream of files into a menu collection object
  .pipe(reduceStream({objectMode: true}, function (menu, file) {
    var input={};
    input = JSON.parse(file.contents.toString());
    input.url = path.relative(siteConfig.paths.dist, file.path);
    input.id = input.id || 'page-'+menu.pages.length;
    if ( input.contentFromFile ) {
      input.content = fs.readFileSync(input.contentFromFile).toString();
      if ( !input.content ) {
        throw new gutil.PluginError('menu', 'Invalid contentFromFile reference ' + input.contentFromFile);
      } else {
        input.content = marked(input.content);
      }
    }
    menu.pages.forEach(function(p){
      if ( p.id === input.id ) {
        throw new gutil.PluginError('menu', 'Duplicate id in Page datatabase when parsing page ' + file.path);
      }
    });
    menu.pages.push(input);
    if ( input.isFrontPage && !menu.frontPageId ) {
      menu.frontPageId = input.id;
    }

    // Run feature builds
    var builds = [];
    if ( input.features ) {
      input.features.forEach(function(f){
        var stat;
        var feature = typeof f === 'string' ? {id:f} : f;
        var fn = './features/' + feature.id + '/build.js';
        try {
          stat = fs.lstatSync(fn);
        } catch(err) {}
        if ( stat && stat.isFile() ) {
          var build = require(fn);
          builds.push(build(input));
        }
      });
    }
    // Store for other tasks
    db[input.id] = input;
    return menu;
  }, {
    pages:[],
    frontPageId:null
  }))
  .on('error', logErrorAndNotify)
  // Convert reduced object into a json file
  .pipe(through.obj(function(data, enc, next){
    this.push(new File({
      path: process.cwd() + '/menu.json',
      contents: new Buffer(JSON.stringify(data))
    }));
    return next();
  }))
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist + '/api/'));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.pages + '/**/*.*'], ['menu']);

// Generic tasks
gulp.task('build', ['clean', 'assets', 'styles', 'templates', 'menu', 'index', 'browserify']);
gulp.task('dist', ['build'], function(){
  process.exit(0);
});

// Target specific tasks
Object.keys(siteConfig.tasks).forEach(function(name){
  gulp.task(name, siteConfig.tasks[name]);
});
<commit_msg>Fix site path resolution with absolute paths<commit_after>'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var rimraf = require('rimraf');
var argv = require('yargs').argv;
var notifier = require('node-notifier');
var template = require('gulp-template');
var fs = require('fs');
var path = require('path');
var filter = require('gulp-filter');
var addsrc = require('gulp-add-src');
var liveReload = require('gulp-livereload');
var liveReloadServer = require('tiny-lr')();
var connectLiveReload = require('connect-livereload');
var express = require('express');
var through = require('through2');
var reduceStream = require('through2-reduce');
var File = require('vinyl');

if ( !argv.site ) {
  gutil.log('Please define the site to be rendered with the --site option');
  gutil.log('E.e gulp --site examples/demo');
  process.exit(1);
}

var db = {};
var siteConfig;

function logErrorAndNotify(e) {
  notifier.notify({
    title:'Error on ' + e.plugin,
    message: e.message
  });
  gutil.log('Error running task', e.plugin);
  gutil.log(e.message);
  gutil.log(e.stack);
}

// Build Configuration
function initConfig(sitePathOrConfig) {
  [
    // Check exact path
    sitePathOrConfig + '.js',
    path.join(sitePathOrConfig, 'config.js'),
    sitePathOrConfig,

    // Check under the working directory
    path.join(process.cwd(), sitePathOrConfig + '.js'),
    path.join(process.cwd(), sitePathOrConfig, 'config.js'),
    path.join(process.cwd(), sitePathOrConfig),

    // Check under the directory where gulp was started
    path.join(process.env.INIT_CWD, sitePathOrConfig + '.js'),
    path.join(process.env.INIT_CWD, sitePathOrConfig, 'config.js'),
    path.join(process.env.INIT_CWD, sitePathOrConfig),
  ]
  .some(function(configFile) {
    var stat;
    try {
      stat = fs.lstatSync(configFile);
    } catch(err) {}
    if ( stat && stat.isFile() ) {
      gutil.log('Using configuration in ', configFile);
      siteConfig = require(path.resolve(configFile));
      siteConfig.configFile = configFile;
      siteConfig.rootPath = path.dirname(siteConfig.configFile);
      return true;
    }
  });
  if ( !siteConfig || !siteConfig.paths ) {
    gutil.log('Invalid site configuration in ', sitePathOrConfig);
    process.exit(1);
  }
}
initConfig(argv.site.replace(/\/$/, ''));

// Config
gulp.task('config', function(){
  initConfig(argv.site.replace(/\/$/, ''));
});
gulp.watch([
  'Gulpfile.js',
  siteConfig.configFile
], ['lint', 'config']);

// Clean
gulp.task('clean', function() {
  rimraf.sync(siteConfig.paths.dist);
});

// JSHint
var jshint = require('gulp-jshint');
gulp.task('lint', function() {
  return gulp.src([
    'Gulpfile.js',
    siteConfig.configFile,
    siteConfig.paths.mainModule + '/**/*.js',
    siteConfig.paths.features + '/**/*.js',
  ])
  .pipe(jshint())
  .on('error', logErrorAndNotify)
  .pipe(jshint.reporter('default'));
});

// Browserify
var browserify = require('gulp-browserify');
var uglify = require('gulp-uglify');
gulp.task('browserify', ['lint'], function() {
  var stream = gulp.src([
    siteConfig.paths.mainJS
  ])
  .pipe(browserify())
  .on('error', logErrorAndNotify)
  .pipe(concat('main.js'))
  .on('error', logErrorAndNotify);

  if ( siteConfig.browserify.enableUglify ) {
    stream.pipe(uglify())
    .on('error', logErrorAndNotify);
  }

  stream.pipe(gulp.dest(siteConfig.paths.dist))
  .on('error', logErrorAndNotify);
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.js',
  siteConfig.paths.features + '/**/*.js',
  siteConfig.rootPath + '/**/*.js',
],[
  'lint',
  'browserify'
]);

// View partials
gulp.task('templates', function() {
  siteConfig.client.bootstraps.templates = {};
  return gulp.src([
    siteConfig.paths.mainModule + '/**/*.html',
    siteConfig.paths.features + '/**/*.html',
    siteConfig.rootPath + '/**/*.html'
  ])
  .pipe(through.obj(function (file, enc, next) {
    var fn = path.relative('./', file.path);
    siteConfig.client.bootstraps.templates[fn] = file.contents.toString();
    next();
  }));
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.html',
  siteConfig.paths.features + '/**/*.html',
  siteConfig.rootPath + '/**/*.html'
], ['index']);

// Index template and partials
gulp.task('index', ['templates', 'menu'], function() {
  var stream;
  siteConfig.client.url = function(suffix) {
    return  siteConfig.server.baseUrl + suffix.replace(/^\//,'');
  };

  // Get bootstrapped content from DB
  siteConfig.client.footer = db.footer;
  siteConfig.client.header = db.header;

  // Process
  stream = gulp.src([siteConfig.paths.mainHTML])
  .pipe(template(siteConfig))
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.mainHTML], ['index']);

// Assets
gulp.task('assets', function() {
  var stream = gulp.src([
    siteConfig.paths.assets + '/**/*.*',
    'node_modules/font-awesome/fonts/*.*'
  ])
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist + '/assets'));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.assets + '/**/*.*'], ['assets']);

// SASS
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
// Styles task
gulp.task('styles', function() {
  var stream = gulp.src([
    siteConfig.paths.mainModule + '/css/main.scss',
    siteConfig.paths.features + '/**/*.scss',
    siteConfig.paths.styles + '/**/*.scss',
    siteConfig.rootPath + '/**/*.scss',
  ])
  // Concat before compile, so that includes are available in dynamic styles
  .pipe(concat('main.css'))
  // Add separate files at this point E.g build icons separately to circumvent IE's rule limit
  .pipe(addsrc([
    siteConfig.paths.mainModule + '/css/icons.scss'
  ]))
  .pipe(
    sass({
      includePaths: [
        siteConfig.paths.mainModule + '/css',
        process.cwd() + '/node_modules',
        siteConfig.rootPath,
      ]
    }).on('error', logErrorAndNotify)
  )
  .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
  .on('error', logErrorAndNotify);

  if ( siteConfig.styles.enableMinify ) {
    stream.pipe(cssmin())
    .on('error', logErrorAndNotify);
  }

  stream.pipe(gulp.dest(siteConfig.paths.dist));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([
  siteConfig.paths.mainModule + '/**/*.scss',
  siteConfig.paths.features + '/**/*.scss',
  siteConfig.paths.styles + '/**/*.scss',
], [
  'styles'
]);

// Server
var server = express();
server.use(siteConfig.server.baseUrl, express.static(siteConfig.paths.dist));

if ( siteConfig.server.enableLiveReload ) {
  server.use(connectLiveReload({port: siteConfig.liveReloadPort}));
}

if ( siteConfig.server.enablePushState ) {
  server.all(siteConfig.server.baseUrl + '[^.]+', function(req, res) {
    res.sendFile('index.html', {
      root: siteConfig.paths.dist
    });
  });
}

gulp.task('server', ['build'], function() {
  server.listen(siteConfig.server.port);
  if ( siteConfig.server.enableLiveReload ) {
    liveReloadServer.listen(siteConfig.server.liveReloadPort);
  }
});

// MENU
var yaml = require('gulp-yaml');
var markdown = require('gulp-markdown');
var marked = require('marked');
var frontMatter = require('gulp-front-matter');
var entityConvert = require('gulp-entity-convert');
marked.setOptions(siteConfig.markdown);

gulp.task('menu', function(){
  var mdFilter = filter('**/*.md', {restore: true});
  var yamlFilter = filter('**/*.yaml', {restore: true});
  var stream = gulp.src(['**/*.yaml', '**/*.md'], {cwd:siteConfig.paths.pages})

  // YAML -> JSON
  .pipe(yamlFilter)
  .pipe(yaml())
  .on('error', logErrorAndNotify)
  .pipe(yamlFilter.restore)

  // Markdown -> HTML
  .pipe(mdFilter)
  .pipe(frontMatter({
    property: 'frontMatterData',
    remove: true
  }))
  .pipe(entityConvert())
  .pipe(markdown(siteConfig.markdown))

  // Frontmatter + HTML -> JSON
  .pipe(through.obj(function (file, enc, next) {
    if ( file.isBuffer() ) {
      file.frontMatterData.content = file.contents.toString();
      file.contents = new Buffer(JSON.stringify(file.frontMatterData));
      file.path = file.path.replace(/\.html$/, '.json');
    }
    this.push(file);
    return next();
  }))
  .on('error', logErrorAndNotify)
  .pipe(mdFilter.restore)

  // JSON -> api/pages/*.json
  .pipe(gulp.dest(siteConfig.paths.dist + '/api/'))

  // menu.json
  .pipe(through.obj(function (file, enc, next) {
    this.push(file);
    return next();
  }))
  // Convert a stream of files into a menu collection object
  .pipe(reduceStream({objectMode: true}, function (menu, file) {
    var input={};
    input = JSON.parse(file.contents.toString());
    input.url = path.relative(siteConfig.paths.dist, file.path);
    input.id = input.id || 'page-'+menu.pages.length;
    if ( input.contentFromFile ) {
      input.content = fs.readFileSync(input.contentFromFile).toString();
      if ( !input.content ) {
        throw new gutil.PluginError('menu', 'Invalid contentFromFile reference ' + input.contentFromFile);
      } else {
        input.content = marked(input.content);
      }
    }
    menu.pages.forEach(function(p){
      if ( p.id === input.id ) {
        throw new gutil.PluginError('menu', 'Duplicate id in Page datatabase when parsing page ' + file.path);
      }
    });
    menu.pages.push(input);
    if ( input.isFrontPage && !menu.frontPageId ) {
      menu.frontPageId = input.id;
    }

    // Run feature builds
    var builds = [];
    if ( input.features ) {
      input.features.forEach(function(f){
        var stat;
        var feature = typeof f === 'string' ? {id:f} : f;
        var fn = './features/' + feature.id + '/build.js';
        try {
          stat = fs.lstatSync(fn);
        } catch(err) {}
        if ( stat && stat.isFile() ) {
          var build = require(fn);
          builds.push(build(input));
        }
      });
    }
    // Store for other tasks
    db[input.id] = input;
    return menu;
  }, {
    pages:[],
    frontPageId:null
  }))
  .on('error', logErrorAndNotify)
  // Convert reduced object into a json file
  .pipe(through.obj(function(data, enc, next){
    this.push(new File({
      path: process.cwd() + '/menu.json',
      contents: new Buffer(JSON.stringify(data))
    }));
    return next();
  }))
  .on('error', logErrorAndNotify)
  .pipe(gulp.dest(siteConfig.paths.dist + '/api/'));
  if ( siteConfig.server.enableLiveReload ) {
    stream.pipe(liveReload(liveReloadServer));
  }
  return stream;
});
gulp.watch([siteConfig.paths.pages + '/**/*.*'], ['menu']);

// Generic tasks
gulp.task('build', ['clean', 'assets', 'styles', 'templates', 'menu', 'index', 'browserify']);
gulp.task('dist', ['build'], function(){
  process.exit(0);
});

// Target specific tasks
Object.keys(siteConfig.tasks).forEach(function(name){
  gulp.task(name, siteConfig.tasks[name]);
});
<|endoftext|>


<commit_before>/**
 * Created by staticfunction on 8/18/14.
 */
var gulp = require('gulp');
var browserify = require('browserify');
var dts = require('dts-bundle');
var ts = require('gulp-typescript');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var replace = require('gulp-replace');
var insert = require('gulp-insert');
var filter = require('gulp-filter');
var merge = require('merge2');
var mocha = require('gulp-mocha');
var del = require('del');
var pkg = require('./package.json');

var BUILD_DIR = "bin-build";
var RELEASE_DIR = "bin-release";

var srcProject = ts.createProject({
    module: "commonjs",
    sortOutput: true
})

gulp.task("debug", function() {
    var srcOnly = filter(['*','!**Spec.js']);
    var testOnly = filter(['**Spec.js']);

    var commonjs =
        gulp.src(['src/signals.ts', 'test/**Spec.ts','typings/tsd.d.ts'])
            .pipe(sourcemaps.init())
            .pipe(ts(srcProject))

       return merge([
           commonjs.js
               .pipe(sourcemaps.write({includeContent: false, sourceRoot: 'src'}))
               .pipe(srcOnly)
               .pipe(gulp.dest('bin-debug/src'))
               .pipe(srcOnly.restore())
               .pipe(testOnly)
               .pipe(gulp.dest('bin-debug/test'))
           ]);
});

gulp.task('test', ['debug'], function() {
    return gulp.src('bin-debug/test/**/*.js', {read: false})
        .pipe(mocha({reporter: 'nyan'}));
});

gulp.task('bundle', function(cb) {
    dts.bundle({
        name: "stfu-signals",
        main: BUILD_DIR + 'signals.d.ts',
        out:  'stfu-signals.d.ts'
    });

    cb();
})

gulp.task('release', function() {
    gulp.src(BUILD_DIR + '/signals.js')
        .pipe(gulp.dest(RELEASE_DIR));

    gulp.src(['package.json','README.md','LICENSE'])
        .pipe(gulp.dest(RELEASE_DIR));

    gulp.src(BUILD_DIR + '/stfu-signals.d.ts').pipe(gulp.dest(RELEASE_DIR));
})
<commit_msg>automate release with amd, commonjs, and dts<commit_after>/**
 * Created by staticfunction on 8/18/14.
 */
var gulp = require('gulp');
var browserify = require('browserify');
var ts = require('gulp-typescript');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var replace = require('gulp-replace');
var insert = require('gulp-insert');
var filter = require('gulp-filter');
var merge = require('merge2');
var mocha = require('gulp-mocha');
var del = require('del');
var pkg = require('./package.json');

var srcProject = ts.createProject({
    module: "commonjs",
    sortOutput: true
})

gulp.task("debug", function() {
    var srcOnly = filter(['*','!**Spec.js']);
    var testOnly = filter(['**Spec.js']);

    var commonjs =
        gulp.src(['src/signals.ts', 'test/**Spec.ts','typings/tsd.d.ts'])
            .pipe(sourcemaps.init())
            .pipe(ts(srcProject))

       return merge([
           commonjs.js
               .pipe(sourcemaps.write({includeContent: false, sourceRoot: 'src'}))
               .pipe(srcOnly)
               .pipe(gulp.dest('bin-debug/src'))
               .pipe(srcOnly.restore())
               .pipe(testOnly)
               .pipe(gulp.dest('bin-debug/test'))
           ]);
});

gulp.task('test', ['debug'], function() {
    return gulp.src('bin-debug/test/**/*.js', {read: false})
        .pipe(mocha({reporter: 'nyan'}));
});

gulp.task('clean-dist', function(cb) {
    del(['dist'], cb);
})

gulp.task('release', ['clean-dist'], function() {
    var commonjs = gulp.src(['src/signals.ts', 'typings/tsd.d.ts'])
        .pipe(ts({
            declarationFiles: true,
            module: "commonjs"
        }));

    var amd = gulp.src(['src/signals.ts', 'typings/tsd.d.ts'])
        .pipe(ts({
            declarationFiles: true,
            module: "amd"
        }));

    return merge([
        commonjs.js
            .pipe(gulp.dest('dist')),
        commonjs.dts
            .pipe(replace(/declare\s/g, ''))
            .pipe(insert.wrap('declare module \"'+ pkg.name +'\" {\n', '\n}'))
            .pipe(gulp.dest('dist')),
        amd.js
            .pipe(gulp.dest('dist/amd'))
    ])
})
<|endoftext|>