<commit_before>/*
 * Copyright (C) 2012-2013 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "mongodb", "util/assert" ], function (MONGODB, ASSERT) {
	"use strict";

	var PROJECT_REGEXP = new RegExp("^[0-9a-zA-Z_]*$");
	var HASH_REGEXP = new RegExp("^#[0-9a-zA-Z_]*$");
	var BRANCH_REGEXP = new RegExp("^\\*[0-9a-zA-Z_]*$");

	var STATUS_CLOSED = "mongodb closed";
	var STATUS_UNREACHABLE = "mongodb unreachable";
	var STATUS_CONNECTED = "connected";

	function Database (options) {
		ASSERT(typeof options === "object");

		options.host = options.host || "localhost";
		options.port = options.port || 27017;
		options.database = options.database || "webgme";
		options.timeout = options.timeout || (1000 * 60 * 10);

		var mongo = null;

		function openDatabase (callback) {
			ASSERT(mongo === null && typeof callback === "function");

			mongo = new MONGODB.Db(options.database, new MONGODB.Server(options.host, options.port), {
				w: 1
			});

			mongo.open(function (err) {
				if (err) {
					mongo.close();
					mongo = null;
					callback(err);
				} else {
					callback(null);
				}
			});
		}

		function closeDatabase (callback) {
			if (mongo !== null) {
				fsyncDatabase(function () {
					mongo.close(function () {
						mongo = null;
						if (typeof callback === "function") {
							callback(null);
						}
					});
				});
			} else if (typeof callback === "function") {
				callback(null);
			}
		}

		function fsyncDatabase (callback) {
			ASSERT(typeof callback === "function");

			var error = null;
			var synced = 0;

			function fsyncConnection (conn) {
				mongo.lastError({
					fsync: true
				}, {
					connection: conn
				}, function (err, res) {
					error = error || err || res[0].err;
					if (++synced === conns.length) {
						callback(error);
					}
				});
			}

			var conns = mongo.serverConfig.allRawConnections();
			if (conns instanceof Array && conns.length >= 1) {
				for ( var i = 0; i < conns.length; ++i) {
					fsyncConnection(conns[i]);
				}
			} else {
				callback(new Error("not connected"));
			}
		}

		function getDatabaseStatus (oldstatus, callback) {
			ASSERT(oldstatus === null || typeof oldstatus === "string");
			ASSERT(typeof callback === "function");

			if (mongo === null) {
				reportStatus(oldstatus, STATUS_CLOSED, callback);
			} else {
				mongo.command({
					ping: 1
				}, function (err) {
					reportStatus(oldstatus, err ? STATUS_UNREACHABLE : STATUS_CONNECTED, callback);
				});
			}
		}

		function reportStatus (oldstatus, newstatus, callback) {
			if (oldstatus !== newstatus) {
				callback(null, newstatus);
			} else {
				setTimeout(function () {
					if (mongo === null) {
						newstatus = STATUS_CLOSED;
					}
					callback(null, newstatus);
				}, options.timeout);
			}
		}

		function getProjectNames (callback) {
			ASSERT(typeof callback === "function");

			mongo.collectionNames(function (err, collections) {
				if (err) {
					callback(err);
				} else {
					var names = [];
					for ( var i = 0; i < collections.length; i++) {
						var p = collections[i].name.indexOf(".");
						var n = collections[i].name.substring(p + 1);
						if (n.indexOf('system') === -1 && n.indexOf('.') === -1) {
							names.push(n);
						}
					}
					callback(null, names);
				}
			});
		}

		function deleteProject (name, callback) {
			ASSERT(typeof name === "string" && PROJECT_REGEXP.test(name));
			ASSERT(typeof callback === "function");

			mongo.dropCollection(name, callback);
		}

		function openProject (name, callback) {
			ASSERT(mongo !== null && typeof callback === "function");
			ASSERT(typeof name === "string" && PROJECT_REGEXP.test(name));

			var collection = null;

			mongo.collection(name, function (err, result) {
				if (err) {
					callback(err);
				} else {
					collection = result;
					callback(null, {
						fsyncDatabase: fsyncDatabase,
						getDatabaseStatus: getDatabaseStatus,
						closeProject: closeProject,
						loadObject: loadObject,
						insertObject: insertObject,
						findHash: findHash,
						dumpObjects: dumpObjects,
						getBranchNames: getBranchNames,
						getBranchHash: getBranchHash,
						setBranchHash: setBranchHash,
						getCommits: getCommits
					});
				}
			});

			function closeProject (callback) {
				collection = null;
				if (typeof callback === "function") {
					callback(null);
				}
			}

			function loadObject (hash, callback) {
				ASSERT(typeof hash === "string" && HASH_REGEXP.test(hash));

				collection.findOne({
					_id: hash
				}, callback);
			}

			function insertObject (object, callback) {
				ASSERT(object !== null && typeof object === "object");
				ASSERT(typeof object._id === "string" && HASH_REGEXP.test(object._id));

				collection.insert(object, callback);
			}

			function findHash (beginning, callback) {
				ASSERT(typeof beginning === "string" && typeof callback === "function");

				if (!HASH_REGEXP.test(beginning)) {
					callback(new Error("hash " + beginning + " not valid"));
				} else {
					collection.find({
						_id: {
							$regex: "^" + beginning
						}
					}, {
						limit: 2
					}).toArray(function (err, docs) {
						if (err) {
							callback(err);
						} else if (docs.length === 0) {
							callback(new Error("hash " + beginning + " not found"));
						} else if (docs.length !== 1) {
							callback(new Error("hash " + beginning + " not unique"));
						} else {
							callback(null, docs[0]._id);
						}
					});
				}
			}

			function dumpObjects (callback) {
				ASSERT(typeof callback === "function");

				collection.find().each(function (err, item) {
					if (err || item === null) {
						callback(err);
					} else {
						console.log(item);
					}
				});
			}

			function getBranchNames (callback) {
				ASSERT(typeof callback === "function");

				collection.find({
					_id: {
						$regex: "^\\*"
					}
				}).toArray(function (err, docs) {
					if (err) {
						callback(err);
					} else {
						var branches = {};
						for ( var i = 0; i < docs.length; ++i) {
							branches[docs[i]._id] = docs[i].hash;
						}
						callback(null, branches);
					}
				});
			}

			function getBranchHash (branch, oldhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && (oldhash === "" || HASH_REGEXP.test(oldhash)));
				ASSERT(typeof callback === "function");

				collection.findOne({
					_id: branch
				}, function (err, obj) {
					if (err) {
						callback(err);
					} else {
						var newhash = (obj && obj.hash) || "";
						if (oldhash !== newhash) {
							callback(null, newhash, null);
						} else {
							setTimeout(callback, options.timeout, null, newhash, null);
						}
					}
				});
			}

			function setBranchHash (branch, oldhash, newhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && (oldhash === "" || HASH_REGEXP.test(oldhash)));
				ASSERT(typeof newhash === "string" && (newhash === "" || HASH_REGEXP.test(newhash)));
				ASSERT(typeof callback === "function");

				if (oldhash === newhash) {
					collection.findOne({
						_id: branch
					}, function (err, obj) {
						if (!err && oldhash !== ((obj && obj.hash) || "")) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				} else if (newhash === "") {
					collection.remove({
						_id: branch,
						hash: oldhash
					}, function (err, num) {
						if (!err && num !== 1) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				} else if (oldhash === "") {
					collection.insert({
						_id: branch,
						hash: newhash
					}, callback);
				} else {
					collection.update({
						_id: branch,
						hash: oldhash
					}, {
						$set: {
							hash: newhash
						}
					}, function (err, num) {
						if (!err && num !== 1) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				}
			}

			function getCommits(before,number,callback){
				//TODO we should think whether this needs options or not
				ASSERT(typeof callback === 'function');

                collection.find({type:'commit',time:{$lt:before}}).limit(number).sort({$natural:-1}).toArray(callback);
			}
		}

		return {
			openDatabase: openDatabase,
			closeDatabase: closeDatabase,
			fsyncDatabase: fsyncDatabase,
			getDatabaseStatus: getDatabaseStatus,
			getProjectNames: getProjectNames,
			openProject: openProject,
			deleteProject: deleteProject,
			ID_NAME: "_id"
		};
	}

	return Database;
});
<commit_msg>gracefully handle inserting the same objects multiple times (and still prevent hash collisions)<commit_after>/*
 * Copyright (C) 2012-2013 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "mongodb", "util/assert" ], function (MONGODB, ASSERT) {
	"use strict";

	var PROJECT_REGEXP = new RegExp("^[0-9a-zA-Z_]*$");
	var HASH_REGEXP = new RegExp("^#[0-9a-zA-Z_]*$");
	var BRANCH_REGEXP = new RegExp("^\\*[0-9a-zA-Z_]*$");

	var STATUS_CLOSED = "mongodb closed";
	var STATUS_UNREACHABLE = "mongodb unreachable";
	var STATUS_CONNECTED = "connected";

	function Database (options) {
		ASSERT(typeof options === "object");

		options.host = options.host || "localhost";
		options.port = options.port || 27017;
		options.database = options.database || "webgme";
		options.timeout = options.timeout || (1000 * 60 * 10);

		var mongo = null;

		function openDatabase (callback) {
			ASSERT(mongo === null && typeof callback === "function");

			mongo = new MONGODB.Db(options.database, new MONGODB.Server(options.host, options.port), {
				w: 1
			});

			mongo.open(function (err) {
				if (err) {
					mongo.close();
					mongo = null;
					callback(err);
				} else {
					callback(null);
				}
			});
		}

		function closeDatabase (callback) {
			if (mongo !== null) {
				fsyncDatabase(function () {
					mongo.close(function () {
						mongo = null;
						if (typeof callback === "function") {
							callback(null);
						}
					});
				});
			} else if (typeof callback === "function") {
				callback(null);
			}
		}

		function fsyncDatabase (callback) {
			ASSERT(typeof callback === "function");

			var error = null;
			var synced = 0;

			function fsyncConnection (conn) {
				mongo.lastError({
					fsync: true
				}, {
					connection: conn
				}, function (err, res) {
					// ignoring the last error, just forcing all commands through
					error = error || err;

					if (++synced === conns.length) {
						callback(error);
					}
				});
			}

			var conns = mongo.serverConfig.allRawConnections();
			if (conns instanceof Array && conns.length >= 1) {
				for ( var i = 0; i < conns.length; ++i) {
					fsyncConnection(conns[i]);
				}
			} else {
				callback(new Error("not connected"));
			}
		}

		function getDatabaseStatus (oldstatus, callback) {
			ASSERT(oldstatus === null || typeof oldstatus === "string");
			ASSERT(typeof callback === "function");

			if (mongo === null) {
				reportStatus(oldstatus, STATUS_CLOSED, callback);
			} else {
				mongo.command({
					ping: 1
				}, function (err) {
					reportStatus(oldstatus, err ? STATUS_UNREACHABLE : STATUS_CONNECTED, callback);
				});
			}
		}

		function reportStatus (oldstatus, newstatus, callback) {
			if (oldstatus !== newstatus) {
				callback(null, newstatus);
			} else {
				setTimeout(function () {
					if (mongo === null) {
						newstatus = STATUS_CLOSED;
					}
					callback(null, newstatus);
				}, options.timeout);
			}
		}

		function getProjectNames (callback) {
			ASSERT(typeof callback === "function");

			mongo.collectionNames(function (err, collections) {
				if (err) {
					callback(err);
				} else {
					var names = [];
					for ( var i = 0; i < collections.length; i++) {
						var p = collections[i].name.indexOf(".");
						var n = collections[i].name.substring(p + 1);
						if (n.indexOf('system') === -1 && n.indexOf('.') === -1) {
							names.push(n);
						}
					}
					callback(null, names);
				}
			});
		}

		function deleteProject (name, callback) {
			ASSERT(typeof name === "string" && PROJECT_REGEXP.test(name));
			ASSERT(typeof callback === "function");

			mongo.dropCollection(name, callback);
		}

		function openProject (name, callback) {
			ASSERT(mongo !== null && typeof callback === "function");
			ASSERT(typeof name === "string" && PROJECT_REGEXP.test(name));

			var collection = null;

			mongo.collection(name, function (err, result) {
				if (err) {
					callback(err);
				} else {
					collection = result;
					callback(null, {
						fsyncDatabase: fsyncDatabase,
						getDatabaseStatus: getDatabaseStatus,
						closeProject: closeProject,
						loadObject: loadObject,
						insertObject: insertObject,
						findHash: findHash,
						dumpObjects: dumpObjects,
						getBranchNames: getBranchNames,
						getBranchHash: getBranchHash,
						setBranchHash: setBranchHash,
						getCommits: getCommits
					});
				}
			});

			function closeProject (callback) {
				collection = null;
				if (typeof callback === "function") {
					callback(null);
				}
			}

			function loadObject (hash, callback) {
				ASSERT(typeof hash === "string" && HASH_REGEXP.test(hash));

				collection.findOne({
					_id: hash
				}, callback);
			}

			function insertObject (object, callback) {
				ASSERT(object !== null && typeof object === "object");
				ASSERT(typeof object._id === "string" && HASH_REGEXP.test(object._id));

				collection.insert(object, function (err) {
					// manually check duplicate keys
					if (err && err.code === 11000) {
						collection.findOne({
							_id: object._id
						}, function (err2, data) {
							if (!err2 && JSON.stringify(object) === JSON.stringify(data)) {
								callback(null);
							} else {
								callback(err);
							}
						});
					} else {
						callback(err);
					}
				});
			}

			function findHash (beginning, callback) {
				ASSERT(typeof beginning === "string" && typeof callback === "function");

				if (!HASH_REGEXP.test(beginning)) {
					callback(new Error("hash " + beginning + " not valid"));
				} else {
					collection.find({
						_id: {
							$regex: "^" + beginning
						}
					}, {
						limit: 2
					}).toArray(function (err, docs) {
						if (err) {
							callback(err);
						} else if (docs.length === 0) {
							callback(new Error("hash " + beginning + " not found"));
						} else if (docs.length !== 1) {
							callback(new Error("hash " + beginning + " not unique"));
						} else {
							callback(null, docs[0]._id);
						}
					});
				}
			}

			function dumpObjects (callback) {
				ASSERT(typeof callback === "function");

				collection.find().each(function (err, item) {
					if (err || item === null) {
						callback(err);
					} else {
						console.log(item);
					}
				});
			}

			function getBranchNames (callback) {
				ASSERT(typeof callback === "function");

				collection.find({
					_id: {
						$regex: "^\\*"
					}
				}).toArray(function (err, docs) {
					if (err) {
						callback(err);
					} else {
						var branches = {};
						for ( var i = 0; i < docs.length; ++i) {
							branches[docs[i]._id] = docs[i].hash;
						}
						callback(null, branches);
					}
				});
			}

			function getBranchHash (branch, oldhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && (oldhash === "" || HASH_REGEXP.test(oldhash)));
				ASSERT(typeof callback === "function");

				collection.findOne({
					_id: branch
				}, function (err, obj) {
					if (err) {
						callback(err);
					} else {
						var newhash = (obj && obj.hash) || "";
						if (oldhash !== newhash) {
							callback(null, newhash, null);
						} else {
							setTimeout(callback, options.timeout, null, newhash, null);
						}
					}
				});
			}

			function setBranchHash (branch, oldhash, newhash, callback) {
				ASSERT(typeof branch === "string" && BRANCH_REGEXP.test(branch));
				ASSERT(typeof oldhash === "string" && (oldhash === "" || HASH_REGEXP.test(oldhash)));
				ASSERT(typeof newhash === "string" && (newhash === "" || HASH_REGEXP.test(newhash)));
				ASSERT(typeof callback === "function");

				if (oldhash === newhash) {
					collection.findOne({
						_id: branch
					}, function (err, obj) {
						if (!err && oldhash !== ((obj && obj.hash) || "")) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				} else if (newhash === "") {
					collection.remove({
						_id: branch,
						hash: oldhash
					}, function (err, num) {
						if (!err && num !== 1) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				} else if (oldhash === "") {
					collection.insert({
						_id: branch,
						hash: newhash
					}, callback);
				} else {
					collection.update({
						_id: branch,
						hash: oldhash
					}, {
						$set: {
							hash: newhash
						}
					}, function (err, num) {
						if (!err && num !== 1) {
							err = new Error("branch hash mismatch");
						}
						callback(err);
					});
				}
			}

			function getCommits (before, number, callback) {
				//TODO we should think whether this needs options or not
				ASSERT(typeof callback === 'function');

				collection.find({
					type: 'commit',
					time: {
						$lt: before
					}
				}).limit(number).sort({
					$natural: -1
				}).toArray(callback);
			}
		}

		return {
			openDatabase: openDatabase,
			closeDatabase: closeDatabase,
			fsyncDatabase: fsyncDatabase,
			getDatabaseStatus: getDatabaseStatus,
			getProjectNames: getProjectNames,
			openProject: openProject,
			deleteProject: deleteProject,
			ID_NAME: "_id"
		};
	}

	return Database;
});
<|endoftext|>


<commit_before>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
module.exports = {
    pdf: function(Ficha) {
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear area de desarrollo
        var areadedesarrollo = "";
        var area = "";
        switch (Ficha.seccion) {
            case 'manada':
                area = "Presa";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Bagheera (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Kaa (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Baloo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Rikki-Tikki-Tavi (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Kotick (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Francisco de Asís (Espiritualidad)";
                        break;
                };
                break;
            case 'tropa':
                 = "Territorio";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Pez (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Tortuga (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'comunidad':
                area = "Desafío";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Delfín (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Caballo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'clan':
                area = "Área de Desarrollo";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Corporalidad";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Creatividad";
                        break;
                    case "caracter":
                        areadedesarrollo = "Carácter";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Afectividad";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Sociabilidad";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Espiritualidad";
                        break;
                };
                break;
        }
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                { text: ''+Ficha.nombreactividad+'', style: 'header'},
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', ''+area.toUpperCase()+'', 'PARTICIPANTES' ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'DESCRIPCIÓN DE LA ACTIVIDAD'],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'RECOMENDACIONES'],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'MATERIALES'],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ 'TIEMPOS', 'AUTOR', 'FECHA'],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ]
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<commit_msg>Update fichaReme.js<commit_after>var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
module.exports = {
    pdf: function(Ficha) {
        // Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
        var fichaTemp = JSON.stringify(Ficha, function(key, value){
            if(value === null){
                return "";
            }
            // Primera letra mayuscula en la seccion
            if(key == "seccion"){
                return value.charAt(0).toUpperCase() + value.slice(1)
            }
            return value;
        });
        Ficha = JSON.parse(fichaTemp);
        // Parsear area de desarrollo
        var areadedesarrollo = "";
        var area = "";
        switch (Ficha.seccion) {
            case 'manada':
                area = "Presa";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Bagheera (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Kaa (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Baloo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Rikki-Tikki-Tavi (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Kotick (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Francisco de Asís (Espiritualidad)";
                        break;
                };
                break;
            case 'tropa':
                area = "Territorio";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Pez (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Tortuga (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'comunidad':
                area = "Desafío";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Delfín (Corporalidad)";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Ave (Creatividad)";
                        break;
                    case "caracter":
                        areadedesarrollo = "Caballo (Carácter)";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Flor (Afectividad)";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Abeja (Sociabilidad)";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Árbol (Espiritualidad)";
                        break;
                };
                break;
            case 'clan':
                area = "Área de Desarrollo";
                switch(Ficha.areadedesarrollo){
                    case "corporalidad":
                        areadedesarrollo = "Corporalidad";
                        break;
                    case "creatividad":
                        areadedesarrollo = "Creatividad";
                        break;
                    case "caracter":
                        areadedesarrollo = "Carácter";
                        break;
                    case "afectividad":
                        areadedesarrollo = "Afectividad";
                        break;
                    case "sociabilidad":
                        areadedesarrollo = "Sociabilidad";
                        break;
                    case "espiritualidad":
                        areadedesarrollo = "Espiritualidad";
                        break;
                };
                break;
        }
        // Parsear materiales string a array
        var materiales =[];
        Ficha.materiales.split("
").slice(0,Ficha.materiales.split('
').length - 1).forEach(function(material){
            materiales.push(material);
        });
        // PDF Content
        var dd= {
            info: {
                title: ''+Ficha.nombreactividad+'',
                author: ''+Ficha.User.facebookname+'',
                subject: ''+Ficha.nombreactividad+'',
                keywords: 'scouts',
                creator: 'http://uhluscout.com'
            },
            content: [
                { text: ''+Ficha.nombreactividad+'', style: 'header'},
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ 'auto', 'auto', 'auto', '*' ],

                        body: [
                            [ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', ''+area.toUpperCase()+'', 'PARTICIPANTES' ],
                            [ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'DESCRIPCIÓN DE LA ACTIVIDAD'],
                            [ ''+Ficha.descripcion+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'RECOMENDACIONES'],
                            [ ''+Ficha.recomendaciones+'']
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*'],

                        body: [
                            [ 'MATERIALES'],
                            [
                                {
                                // to treat a paragraph as a bulleted list, set an array of items under the ul key
                                ul: materiales
                                },
                            ]
                        ]
                    },
                    style: 'marginBot'
                },
                {
                    layout: 'headerLineOnly',
                    table: {
                        headerRows: 1,
                        widths: [ '*', '*', '*'],

                        body: [
                            [ 'TIEMPOS', 'AUTOR', 'FECHA'],
                            [ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
                        ]
                    },
                    style: 'marginBot'
                },
                { text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
            ],
            styles: {
                header: {
                    fontSize: 22,
                    bold: true,
                    alignment: 'right',
                    margin: [ 0, 0, 0, 25 ]
                },
                marginBot:{
                    margin: [ 0, 0, 0, 25 ]
                },
                footer: {
                    bold: true,
                    alignment: 'right'
                },
            }
        }//end dd

        var fontDescriptors = {
            Roboto: {
                normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
                bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
                italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
                bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
            }
        };
        var printer = new PdfPrinter(fontDescriptors);
        return printer.createPdfKitDocument(dd);
    }
};
<|endoftext|>


<commit_before>'use strict'
// move to adapter much better
var Event = require('vigour-js/lib/event')
var setByPath = require('vigour-js/lib/util/setwithpath')
exports.define = {
  receiveSubscription (subscriptions, id, event) {
    var hub = this
    var ev = new Event('data')
    for (var field in subscriptions) {
      walk(subscriptions[field], field)
    }
    // resolve if subs

    function resolvergetter (hub, field) {
      console.log('RESOLVE =================================> ?', hub._scope, field)
      if(field === '$') {
        return hub
      }

      // all wrong
      return hub
    }

    // get client by id!
    function walk (subscription, field) {
      var target = field === '$' ? hub : hub.get(field, {})
      console.log('SCOPE:', hub._scope, target.lookUp('_scope') || target._scope)
      // target
      for (var subs in subscription) {
        for (var type in subscription[subs]) {

          if (subs === '$') {
            subs = true
          }
          hub = resolvergetter(target, subs)

          if (type === 'property') {
            var client = hub.clients[id]

            target.subscribe(subs, type, [ function (data, event, client) {
              var datax = {}
              this.each(function (p, key) {
                datax[key] = {}
              })
              var thing = {}
              setByPath(thing, this.path, datax)
              client.connection.origin.push({
                stamp: event.stamp,
                set: thing
              })
            }, client], id, true, ev)
          } else {
            console.log('got subs!@!@#!@#@#!!@#!@#!@#', hub.clients[id].val, target.lookUp('_scope'), hub._scope)

            target.subscribe(subs, type, [ function (data, event, client) {
              console.log('???', type, this.lookUp('_scope'))
              // if (client.parent.parent._scope === this.lookUp('_scope') || event === ev) {
              console.log('send from subs bitch:::::::::::========>', client.path, client.parent.parent._scope)
              client.send(this, hub, data, event)
              // }
            }, hub.clients[id] ], id, true, ev)
          }
        }
      }
    }
    ev.trigger()
  }
}
<commit_msg>update<commit_after>'use strict'
// move to adapter much better
var Event = require('vigour-js/lib/event')
var setByPath = require('vigour-js/lib/util/setwithpath')
exports.define = {
  receiveSubscription (subscriptions, id, event) {
    var hub = this

    if (hub._scope) {
      console.log('xx====== SCOPE AND SUBS =====xxx')
    }

    var ev = new Event('data')
    for (var field in subscriptions) {
      walk(subscriptions[field], field)
    }
    // resolve if subs

    function resolvergetter (hub, field) {
      console.log('RESOLVE =================================> ?', hub._scope, field)
      if (field === '$') {
        return hub
      }

      console.log('get --------->', Object.getPrototypeOf(hub)._scope)
      // all wrong
      return Object.getPrototypeOf(hub) || hub
    }

    // get client by id!
    function walk (subscription, field) {
      var reshub = resolvergetter(hub, subs)
      var target = field === '$' ? reshub : reshub.get(field, {})
      // console.log('SCOPE:', hub._scope, target.lookUp('_scope') || target._scope)
      // target
      for (var subs in subscription) {
        for (var type in subscription[subs]) {
          if (subs === '$') {
            subs = true
          }

          if (type === 'property') {
            var client = hub.clients[id]

            target.subscribe(subs, type, [ function (data, event, client) {
              var datax = {}
              this.each(function (p, key) {
                datax[key] = {}
              })
              var thing = {}
              setByPath(thing, this.path, datax)
              client.connection.origin.push({
                stamp: event.stamp,
                set: thing
              })
            }, client], id, true, ev)
          } else {
            console.log('got subs!@!@#!@#@#!!@#!@#!@#', hub.clients[id].val, target.lookUp('_scope'), hub._scope)

            target.subscribe(subs, type, [ function (data, event, client) {
              // console.log('???', type, this.lookUp('_scope'))
              if (client.parent.parent._scope === this.lookUp('_scope') || event === ev || !this.lookUp('_scope')) {

                if (!this.lookUp('_scope') && client.parent.parent._scope) {
                  // now do special trickas
                  var realdeal = hub.get(this.path)
                  // console.log('yo', realdeal.)
                  data = realdeal ? realdeal._input : this
                }

                console.log('send from subs bitch:::::::::::========>', client.path, client.parent.parent._scope)
                client.send(realdeal || this, hub, data, event)
              }
            }, hub.clients[id] ], id, true, ev)
          }
        }
      }
    }
    ev.trigger()
  }
}
<|endoftext|>


<commit_before>import webpack from '../webpack';

export default {
    description: `
    # roc-plugin-typescript
    A roc plugin for compiling typescript (*.ts and *.tsx) files. It uses
    [ts-loader](https://github.com/TypeStrong/ts-loader) for to let webpack compile
    typescript files and adds source maps via
    [source-map-loader](https://github.com/webpack/source-map-loader).

    ## How to use?
    Add the plugin as a dev dependency of your [roc](http://www.getroc.org) application:
    \`\`\`
    npm install --save-dev roc-plugin-typescript
    \`\`\`

    The plugin will automatically hook into webpacks build process and add a loader
    for *.ts and *.tsx files. The compiler will look for a \`tsconfig.json\` file in
    the root of you roc project, which you can use for configuration.
    `,
    actions: [{
        hook: 'build-webpack',
        description: 'Adds typescript support to Webpack.',
        action: webpack,
    }],
    required: {
        'roc-package-webpack': '^1.0.0-beta.1',
    },
};
<commit_msg>Use lazyFunctionRequire for improved import performance.<commit_after>import { lazyFunctionRequire } from 'roc';

const lazyRequire = lazyFunctionRequire(require);

export default {
    description: `
    # roc-plugin-typescript
    A roc plugin for compiling typescript (*.ts and *.tsx) files. It uses
    [ts-loader](https://github.com/TypeStrong/ts-loader) for to let webpack compile
    typescript files and adds source maps via
    [source-map-loader](https://github.com/webpack/source-map-loader).

    ## How to use?
    Add the plugin as a dev dependency of your [roc](http://www.getroc.org) application:
    \`\`\`
    npm install --save-dev roc-plugin-typescript
    \`\`\`

    The plugin will automatically hook into webpacks build process and add a loader
    for *.ts and *.tsx files. The compiler will look for a \`tsconfig.json\` file in
    the root of you roc project, which you can use for configuration.
    `,
    actions: [{
        hook: 'build-webpack',
        description: 'Adds typescript support to Webpack.',
        action: lazyRequire('../webpack'),
    }],
    required: {
        'roc-package-webpack': '^1.0.0-beta.1',
    },
};
<|endoftext|>


<commit_before>var config = require('../config.json');
module.exports = function(gulp, flags) {
  gulp.task('docs', ['docs.demos'], function() {
    var Dgeni = require('dgeni');
    var semver = require('semver');

    var docVersion = flags['doc-version'] || 'nightly';
    if (docVersion != 'nightly' && !semver.valid(docVersion)) {
      console.log('Usage: gulp docs --doc-version=(nightly|versionName)\nversionName must be a valid semver version.');
      return process.exit(1);
    }
    try {
      var ionicPackage = require('./dgeni-config')(docVersion);
      var dgeni = new Dgeni([ionicPackage]);
      return dgeni.generate();
    } catch (err) {
      console.log(err.stack);
    }
  });

  gulp.task('docs.demos', ['demos', 'sass', 'fonts'], function(){
    return gulp.src([
        'dist/**',
        '!dist/e2e',
        '!dist/e2e/**/*',
        '!dist/ionic-site',
        '!dist/ionic-site/**/*',
        '!dist/src',
        '!dist/src/**/*'
      ])
      .pipe(gulp.dest(config.docsDest + '/dist'));
  });

  gulp.task('docs.index', function() {
    var lunr = require('lunr');
    var gutil = require('gulp-util');
    var es = require('event-stream');
    var yaml = require('js-yaml');
    var htmlparser = require('htmlparser2');
    var mkdirp = require('mkdirp');
    var fs = require('fs');

    var idx = lunr(function() {
      this.field('path');
      this.field('title', {boost: 10});
      this.field('body');
      this.ref('id');
    });
    var ref = {};
    var refId = 0;

    function addToIndex(path, title, layout, body) {
      // Add the data to the indexer and ref object
      idx.add({'path': path, 'body': body, 'title': title, id: refId});
      ref[refId] = {'p': path, 't': title, 'l': layout};
      refId++;
    }

    var docPath = config.docsDest;
    gutil.log('Reading docs from', gutil.colors.cyan(docPath));

    return gulp.src([
      docPath + '/{guide,api,overview, what-is,utilities,ui,theming,native}/**/*.{md,html,markdown}',
      docPath + '/index.md',
    ])
      .pipe(es.map(function(file, callback) {
        //docs for gulp file objects: https://github.com/wearefractal/vinyl
        var contents = file.contents.toString(); //was buffer

        // Grab relative path from ionic-site root
        var relpath = file.path.replace(RegExp('^.*?' + docPath.replace('/' + config.v2DocsDir, '') + '/'), '');

        // Read out the yaml portion of the Jekyll file
        var yamlStartIndex = contents.indexOf('---');

        if (yamlStartIndex === -1) {
          return callback();
        }

        // read Jekyll's page yaml variables at the top of the file
        var yamlEndIndex = contents.indexOf('---', yamlStartIndex+3); //starting from start
        var yamlRaw = contents.substring(yamlStartIndex+3, yamlEndIndex);

        var pageData =  yaml.safeLoad(yamlRaw);
        if(!pageData.title || !pageData.layout) {
          return callback();
        }

        // manually set to not be searchable, or for a blog post, manually set to be searchable
        if(pageData.searchable === false || (pageData.layout == 'post' && pageData.searchable !== true)) {
          return callback();
        }

        // clean up some content so code variables are searchable too
        contents = contents.substring(yamlEndIndex+3);
        contents = contents.replace(/<code?>/gi, '');
        contents = contents.replace(/<\/code>/gi, '');
        contents = contents.replace(/<code?></gi, '');
        contents = contents.replace(/><\/code>/gi, '');
        contents = contents.replace(/`</gi, '');
        contents = contents.replace(/>`/gi, '');

        // create a clean path to the URL
        var path = '/' + relpath.replace('index.md', '')
                                .replace('index.html', '')
                                .replace('.md', '.html')
                                .replace('.markdown', '.html');
        if(pageData.layout == 'post') {
          path = '/blog/' + path.substring(19).replace('.html', '/');
        }

        var parser;
        if(pageData.search_sections === true) {
          // each section within the content should be its own search result
          var section = { body: '', title: '' };
          var isTitleOpen = false;

          parser = new htmlparser.Parser({
            ontext: function(text){
              if(isTitleOpen) {
                section.title += text; // get the title of this section
              } else {
                section.body += text.replace(/{%.*%}/, '', 'g'); // Ignore any Jekyll expressions
              }
            },
            onopentag: function(name, attrs) {
              if(name == 'section' && attrs.id) {
                // start building new section data
                section = { body: '', path: path + '#' + attrs.id, title: '' };
              } else if( (name == 'h1' || name == 'h2' || name == 'h3') && attrs.class == 'title') {
                isTitleOpen = true; // the next text will be this sections title
              }
            },
            onclosetag: function(name) {
              if(name == 'section') {
                // section closed, index this section then clear it out
                addToIndex(section.path, section.title, pageData.layout, section.body);
                section = { body: '', title: '' };
              } else if( (name == 'h1' || name == 'h2' || name == 'h3') && isTitleOpen) {
                isTitleOpen = false;
              }
            }
          });
          parser.write(contents);
          parser.end();

        } else {
          // index the entire page
          var body = '';
          parser = new htmlparser.Parser({
            ontext: function(text){
              body += text.replace(/{%.*%}/, '', 'g'); // Ignore any Jekyll expressions
            }
          });
          parser.write(contents);
          parser.end();

          addToIndex(path, pageData.title, pageData.layout, body);
        }

        callback();

      })).on('end', function() {
        // Write out as one json file
        mkdirp.sync(docPath + '/data');
        fs.writeFileSync(
          docPath + '/data/index.json',
          JSON.stringify({'ref': ref, 'index': idx.toJSON()})
        );
      });
  });

  gulp.task('docs.sass-variables', function() {
    var fs = require('fs');
    var gutil = require('gulp-util');
    var es = require('event-stream');
    var path = require('path');
    var Entities = require('html-entities').AllHtmlEntities;
    entities = new Entities();

    var variables = [];
    var outputFile = config.docsDest + '/data/sass.json';

    // Add the variable to the array, encode the html and remove !default from the value
    function addVariable(variableName, defaultValue, file) {
      defaultValue = entities.encode(defaultValue);
      defaultValue = defaultValue.replace("!default;", "");

      variables.push({
        "name": variableName,
        "defaultValue": defaultValue.trim(),
        "file": path.relative('./', file.path)
      });
    }

    return gulp.src('ionic/**/*.scss')
      .pipe(es.map(function(file, callback) {
        var contents = file.contents.toString();
        var variableLine, variableName, defaultValue, multiline;

        fs.createReadStream(file.path, {flags: 'r'})
          .pipe(es.split())
          .pipe(es.map(function (line, callback) {
            if (line.charAt(0) == '$') {
              variableLine = line.split(/:(.+)/);
              variableName = variableLine[0];
              defaultValue = variableLine[1];

              // If there is a semicolon then it isn't a multiline value
              multiline = line.indexOf(';') > -1 ? false : true;

              if (!multiline && line.indexOf('!default') > -1)
                addVariable(variableName, defaultValue, file);
            } else if (multiline == true) {
              defaultValue += '\n' + line;

              // If the line has a semicolon then we've found the end of the value
              if (line.indexOf(';') > -1 && line.indexOf('!default') > -1) {
                addVariable(variableName, defaultValue, file);
                multiline = false;
              }
            }
            callback();
          }));
        callback();
      }).on('end', function() {
        gutil.log("Writing to file at", gutil.colors.cyan("/driftyco/ionic2/" + outputFile));
        gutil.log("Place this file in", gutil.colors.cyan("/driftyco/ionic-site/" + config.v2DocsDir + "/theming/overriding-ionic-variables/"), "in order to update the docs");
        fs.writeFileSync(outputFile, JSON.stringify(variables));
      }));
  });
}
<commit_msg>chore(docs): make copy.web-animations a dependency of docs task<commit_after>var config = require('../config.json');
module.exports = function(gulp, flags) {
  gulp.task('docs', ['docs.demos'], function() {
    var Dgeni = require('dgeni');
    var semver = require('semver');

    var docVersion = flags['doc-version'] || 'nightly';
    if (docVersion != 'nightly' && !semver.valid(docVersion)) {
      console.log('Usage: gulp docs --doc-version=(nightly|versionName)\nversionName must be a valid semver version.');
      return process.exit(1);
    }
    try {
      var ionicPackage = require('./dgeni-config')(docVersion);
      var dgeni = new Dgeni([ionicPackage]);
      return dgeni.generate();
    } catch (err) {
      console.log(err.stack);
    }
  });

  gulp.task('docs.demos', ['demos', 'sass', 'fonts', 'copy.web-animations'], function(){
    return gulp.src([
        'dist/**',
        '!dist/e2e',
        '!dist/e2e/**/*',
        '!dist/ionic-site',
        '!dist/ionic-site/**/*',
        '!dist/src',
        '!dist/src/**/*'
      ])
      .pipe(gulp.dest(config.docsDest + '/dist'));
  });

  gulp.task('docs.index', function() {
    var lunr = require('lunr');
    var gutil = require('gulp-util');
    var es = require('event-stream');
    var yaml = require('js-yaml');
    var htmlparser = require('htmlparser2');
    var mkdirp = require('mkdirp');
    var fs = require('fs');

    var idx = lunr(function() {
      this.field('path');
      this.field('title', {boost: 10});
      this.field('body');
      this.ref('id');
    });
    var ref = {};
    var refId = 0;

    function addToIndex(path, title, layout, body) {
      // Add the data to the indexer and ref object
      idx.add({'path': path, 'body': body, 'title': title, id: refId});
      ref[refId] = {'p': path, 't': title, 'l': layout};
      refId++;
    }

    var docPath = config.docsDest;
    gutil.log('Reading docs from', gutil.colors.cyan(docPath));

    return gulp.src([
      docPath + '/{guide,api,overview, what-is,utilities,ui,theming,native}/**/*.{md,html,markdown}',
      docPath + '/index.md',
    ])
      .pipe(es.map(function(file, callback) {
        //docs for gulp file objects: https://github.com/wearefractal/vinyl
        var contents = file.contents.toString(); //was buffer

        // Grab relative path from ionic-site root
        var relpath = file.path.replace(RegExp('^.*?' + docPath.replace('/' + config.v2DocsDir, '') + '/'), '');

        // Read out the yaml portion of the Jekyll file
        var yamlStartIndex = contents.indexOf('---');

        if (yamlStartIndex === -1) {
          return callback();
        }

        // read Jekyll's page yaml variables at the top of the file
        var yamlEndIndex = contents.indexOf('---', yamlStartIndex+3); //starting from start
        var yamlRaw = contents.substring(yamlStartIndex+3, yamlEndIndex);

        var pageData =  yaml.safeLoad(yamlRaw);
        if(!pageData.title || !pageData.layout) {
          return callback();
        }

        // manually set to not be searchable, or for a blog post, manually set to be searchable
        if(pageData.searchable === false || (pageData.layout == 'post' && pageData.searchable !== true)) {
          return callback();
        }

        // clean up some content so code variables are searchable too
        contents = contents.substring(yamlEndIndex+3);
        contents = contents.replace(/<code?>/gi, '');
        contents = contents.replace(/<\/code>/gi, '');
        contents = contents.replace(/<code?></gi, '');
        contents = contents.replace(/><\/code>/gi, '');
        contents = contents.replace(/`</gi, '');
        contents = contents.replace(/>`/gi, '');

        // create a clean path to the URL
        var path = '/' + relpath.replace('index.md', '')
                                .replace('index.html', '')
                                .replace('.md', '.html')
                                .replace('.markdown', '.html');
        if(pageData.layout == 'post') {
          path = '/blog/' + path.substring(19).replace('.html', '/');
        }

        var parser;
        if(pageData.search_sections === true) {
          // each section within the content should be its own search result
          var section = { body: '', title: '' };
          var isTitleOpen = false;

          parser = new htmlparser.Parser({
            ontext: function(text){
              if(isTitleOpen) {
                section.title += text; // get the title of this section
              } else {
                section.body += text.replace(/{%.*%}/, '', 'g'); // Ignore any Jekyll expressions
              }
            },
            onopentag: function(name, attrs) {
              if(name == 'section' && attrs.id) {
                // start building new section data
                section = { body: '', path: path + '#' + attrs.id, title: '' };
              } else if( (name == 'h1' || name == 'h2' || name == 'h3') && attrs.class == 'title') {
                isTitleOpen = true; // the next text will be this sections title
              }
            },
            onclosetag: function(name) {
              if(name == 'section') {
                // section closed, index this section then clear it out
                addToIndex(section.path, section.title, pageData.layout, section.body);
                section = { body: '', title: '' };
              } else if( (name == 'h1' || name == 'h2' || name == 'h3') && isTitleOpen) {
                isTitleOpen = false;
              }
            }
          });
          parser.write(contents);
          parser.end();

        } else {
          // index the entire page
          var body = '';
          parser = new htmlparser.Parser({
            ontext: function(text){
              body += text.replace(/{%.*%}/, '', 'g'); // Ignore any Jekyll expressions
            }
          });
          parser.write(contents);
          parser.end();

          addToIndex(path, pageData.title, pageData.layout, body);
        }

        callback();

      })).on('end', function() {
        // Write out as one json file
        mkdirp.sync(docPath + '/data');
        fs.writeFileSync(
          docPath + '/data/index.json',
          JSON.stringify({'ref': ref, 'index': idx.toJSON()})
        );
      });
  });

  gulp.task('docs.sass-variables', function() {
    var fs = require('fs');
    var gutil = require('gulp-util');
    var es = require('event-stream');
    var path = require('path');
    var Entities = require('html-entities').AllHtmlEntities;
    entities = new Entities();

    var variables = [];
    var outputFile = config.docsDest + '/data/sass.json';

    // Add the variable to the array, encode the html and remove !default from the value
    function addVariable(variableName, defaultValue, file) {
      defaultValue = entities.encode(defaultValue);
      defaultValue = defaultValue.replace("!default;", "");

      variables.push({
        "name": variableName,
        "defaultValue": defaultValue.trim(),
        "file": path.relative('./', file.path)
      });
    }

    return gulp.src('ionic/**/*.scss')
      .pipe(es.map(function(file, callback) {
        var contents = file.contents.toString();
        var variableLine, variableName, defaultValue, multiline;

        fs.createReadStream(file.path, {flags: 'r'})
          .pipe(es.split())
          .pipe(es.map(function (line, callback) {
            if (line.charAt(0) == '$') {
              variableLine = line.split(/:(.+)/);
              variableName = variableLine[0];
              defaultValue = variableLine[1];

              // If there is a semicolon then it isn't a multiline value
              multiline = line.indexOf(';') > -1 ? false : true;

              if (!multiline && line.indexOf('!default') > -1)
                addVariable(variableName, defaultValue, file);
            } else if (multiline == true) {
              defaultValue += '\n' + line;

              // If the line has a semicolon then we've found the end of the value
              if (line.indexOf(';') > -1 && line.indexOf('!default') > -1) {
                addVariable(variableName, defaultValue, file);
                multiline = false;
              }
            }
            callback();
          }));
        callback();
      }).on('end', function() {
        gutil.log("Writing to file at", gutil.colors.cyan("/driftyco/ionic2/" + outputFile));
        gutil.log("Place this file in", gutil.colors.cyan("/driftyco/ionic-site/" + config.v2DocsDir + "/theming/overriding-ionic-variables/"), "in order to update the docs");
        fs.writeFileSync(outputFile, JSON.stringify(variables));
      }));
  });
}
<|endoftext|>


<commit_before>/* @flow */

const _ = require('lodash')
const path = require('path')

const metadata = require('../../../core/metadata')
const events = require('../../../core/local/steps/event')

const statsBuilder = require('./stats')

/*::
import type { Stats } from 'fs'
import type { Metadata } from '../../../core/metadata'
import type { AtomWatcherEvent, EventAction, EventKind, Batch } from '../../../core/local/steps/event'
import type { StatsBuilder } from './stats'
*/

function randomPick /*:: <T> */ (elements /*: Array<T> */) /*: T */{
  const l = elements.length
  const i = Math.floor(Math.random() * l)
  return elements[i]
}

function kind (doc /*: Metadata */) /*: EventKind */ {
  return doc.docType === 'folder' ? 'directory' : doc.docType
}

module.exports = class AtomWatcherEventBuilder {
  /*::
  _event: AtomWatcherEvent
  _statsBuilder: ?StatsBuilder
  */

  constructor (old /*: ?AtomWatcherEvent */) {
    if (old) {
      this._event = _.cloneDeep(old)
    } else {
      const kind = randomPick(events.KINDS)
      this._event = {
        action: randomPick(events.ACTIONS),
        kind,
        path: '/',
        _id: '/'
      }
    }
    this._ensureStatsBuilder()
  }

  _ensureStatsBuilder () /*: StatsBuilder */ {
    this._statsBuilder = this._statsBuilder ||
      statsBuilder
        .fromStats(this._event.stats)
        .kind(this._event.kind)
    return this._statsBuilder
  }

  fromDoc (doc /*: Metadata */) /*: this */ {
    const updatedAt = new Date(doc.updated_at)

    let builder =
      this
        .kind(kind(doc))
        .path(doc.path)
        .ctime(updatedAt)
        .mtime(updatedAt)
    if (doc.ino) builder = builder.ino(doc.ino)
    return builder
  }

  build () /*: AtomWatcherEvent */ {
    if (this._statsBuilder) {
      this._event.stats = this._statsBuilder.build()
    }
    return this._event
  }

  action (newAction /*: EventAction */) /*: this */ {
    this._event.action = newAction

    if (newAction === 'deleted') this.noStats()

    return this
  }

  kind (newKind /*: EventKind */) /*: this */ {
    this._event.kind = newKind
    if (this._statsBuilder) this._statsBuilder.kind(newKind)
    return this
  }

  path (newPath /*: string */) /*: this */ {
    this._event.path = path.normalize(newPath)
    this._event._id = metadata.id(newPath)
    return this
  }

  oldPath (newPath /*: string */) /*: this */{
    this._event.oldPath = path.normalize(newPath)
    return this
  }

  id (newId /*: string */) /*: this */ {
    this._event._id = newId
    return this
  }

  ino (newIno /*: number */) /*: this */ {
    this._ensureStatsBuilder().ino(newIno)
    return this
  }

  mtime (newMtime /*: Date */) /*: this */ {
    this._ensureStatsBuilder().mtime(newMtime)
    return this
  }

  ctime (newCtime /*: Date */) /*: this */ {
    this._ensureStatsBuilder().ctime(newCtime)
    return this
  }

  noStats () /*: this */ {
    delete this._event.stats
    delete this._statsBuilder
    return this
  }

  md5sum (newMd5sum /*: string */) /*: this */ {
    this._event.md5sum = newMd5sum
    return this
  }

  noIgnore () /*: this */ {
    this._event.noIgnore = true
    return this
  }

  incomplete () /*: this */ {
    this._event.incomplete = true
    delete this._event.md5sum
    return this.noStats()
  }
}
<commit_msg>test/support/builders/atom_watcher_event: Fix #path() (#1519)<commit_after>/* @flow */

const _ = require('lodash')
const path = require('path')

const metadata = require('../../../core/metadata')
const events = require('../../../core/local/steps/event')

const statsBuilder = require('./stats')

/*::
import type { Stats } from 'fs'
import type { Metadata } from '../../../core/metadata'
import type { AtomWatcherEvent, EventAction, EventKind, Batch } from '../../../core/local/steps/event'
import type { StatsBuilder } from './stats'
*/

function randomPick /*:: <T> */ (elements /*: Array<T> */) /*: T */{
  const l = elements.length
  const i = Math.floor(Math.random() * l)
  return elements[i]
}

function kind (doc /*: Metadata */) /*: EventKind */ {
  return doc.docType === 'folder' ? 'directory' : doc.docType
}

module.exports = class AtomWatcherEventBuilder {
  /*::
  _event: AtomWatcherEvent
  _statsBuilder: ?StatsBuilder
  */

  constructor (old /*: ?AtomWatcherEvent */) {
    if (old) {
      this._event = _.cloneDeep(old)
    } else {
      const kind = randomPick(events.KINDS)
      this._event = {
        action: randomPick(events.ACTIONS),
        kind,
        path: '/',
        _id: '/'
      }
    }
    this._ensureStatsBuilder()
  }

  _ensureStatsBuilder () /*: StatsBuilder */ {
    this._statsBuilder = this._statsBuilder ||
      statsBuilder
        .fromStats(this._event.stats)
        .kind(this._event.kind)
    return this._statsBuilder
  }

  fromDoc (doc /*: Metadata */) /*: this */ {
    const updatedAt = new Date(doc.updated_at)

    let builder =
      this
        .kind(kind(doc))
        .path(doc.path)
        .ctime(updatedAt)
        .mtime(updatedAt)
    if (doc.ino) builder = builder.ino(doc.ino)
    return builder
  }

  build () /*: AtomWatcherEvent */ {
    if (this._statsBuilder) {
      this._event.stats = this._statsBuilder.build()
    }
    return this._event
  }

  action (newAction /*: EventAction */) /*: this */ {
    this._event.action = newAction

    if (newAction === 'deleted') this.noStats()

    return this
  }

  kind (newKind /*: EventKind */) /*: this */ {
    this._event.kind = newKind
    if (this._statsBuilder) this._statsBuilder.kind(newKind)
    return this
  }

  path (newPath /*: string */) /*: this */ {
    this._event.path = path.normalize(newPath)
    this._event._id = metadata.id(this._event.path)
    return this
  }

  oldPath (newPath /*: string */) /*: this */{
    this._event.oldPath = path.normalize(newPath)
    return this
  }

  id (newId /*: string */) /*: this */ {
    this._event._id = newId
    return this
  }

  ino (newIno /*: number */) /*: this */ {
    this._ensureStatsBuilder().ino(newIno)
    return this
  }

  mtime (newMtime /*: Date */) /*: this */ {
    this._ensureStatsBuilder().mtime(newMtime)
    return this
  }

  ctime (newCtime /*: Date */) /*: this */ {
    this._ensureStatsBuilder().ctime(newCtime)
    return this
  }

  noStats () /*: this */ {
    delete this._event.stats
    delete this._statsBuilder
    return this
  }

  md5sum (newMd5sum /*: string */) /*: this */ {
    this._event.md5sum = newMd5sum
    return this
  }

  noIgnore () /*: this */ {
    this._event.noIgnore = true
    return this
  }

  incomplete () /*: this */ {
    this._event.incomplete = true
    delete this._event.md5sum
    return this.noStats()
  }
}
<|endoftext|>


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

// https://github.com/octokit/rest.js
// https://octokit.github.io/rest.js/
const { Octokit } = require('@octokit/rest');

console.log("process.cwd():");
console.log(process.cwd());
console.log("path.resolve(\".\")");
console.log(path.resolve("."));

console.log("__dirname:");
console.log(__dirname);

const args = process.argv.slice(2);
console.log("args:");
console.log(args);

const envCommitSha = process.env.TRAVIS_COMMIT || process.env.APPVEYOR_REPO_COMMIT;

console.log("TRAVIS_COMMIT:");
console.log(envCommitSha);
if (!envCommitSha) {
    console.log("Missing TRAVIS_COMMIT! Abort.");
    process.exit(1);
    return;
}

console.log("TRAVIS_TAG:");
console.log(process.env.TRAVIS_TAG);
if (!process.env.TRAVIS_TAG) {
    console.log("Missing TRAVIS_TAG! Abort.");
    process.exit(1);
    return;
}

if (!process.env.GH_TOKEN) {
    console.log("Missing GH_TOKEN! Abort.");
    process.exit(1);
    return;
}

const octokit = new Octokit({
    auth: `token ${process.env.GH_TOKEN}`
});

// !!!!!!!!!!!!!!!!
// IMPORTANT !!!!
// Make sure DEBUG is *off* in TravisCI,
// as this potentially prints console messages that contain the HTTP header:
// authorization: 'token GH_TOKEN'
// It that happens, revoke the token immediately!
// https://github.com/settings/tokens
// Example: when getReleaseByTag() return 404
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
const DEBUG = false;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

const owner_appveyor = "danielweck";
const owner = "readium";
const repo = "readium-desktop";
const tag = process.env.TRAVIS_TAG;

(async () => {

console.log("################################################");
console.log("################ getReleaseByTag:");
let getReleaseByTagRES = undefined;
try {
    getReleaseByTagRES = await octokit.repos.getReleaseByTag({owner, repo, tag})
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("getReleaseByTag error! Continue.");
    // if (err.status !== 404) {
    //     console.log("getReleaseByTag error! Abort.");
    //     process.exit(1);
    //     return;
    // }
}

if (getReleaseByTagRES) {
    console.log("getReleaseByTagRES:");
    if (DEBUG) console.log(getReleaseByTagRES);

    const release_id = getReleaseByTagRES.data.id;

    console.log("################################################");
    console.log("################ deleteRelease:");
    let deleteReleaseRES = undefined;
    try {
        deleteReleaseRES = await octokit.repos.deleteRelease({owner, repo, release_id})
    } catch (err) {
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        if (DEBUG) console.log(err);
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        console.log("deleteReleaseRES error! Continue.");
        // console.log("deleteRelease error! Abort.");
        // process.exit(1);
        // return;
    }
    if (deleteReleaseRES) {
        console.log("deleteReleaseRES:");
        if (DEBUG) console.log(deleteReleaseRES);
    }
}

const ref = `tags/${process.env.TRAVIS_TAG}`;

console.log("################################################");
console.log("################ deleteRef:");
let deleteRefRES = undefined;
try {
    deleteRefRES = await octokit.git.deleteRef({owner, repo, ref})
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("deleteRefRES error! Continue.");
    // console.log("deleteRef error! Abort.");
    // process.exit(1);
    // return;
}

if (deleteRefRES) {
    console.log("deleteRefRES:");
    if (DEBUG) console.log(deleteRefRES);
}

if (process.env.APPVEYOR_REPO_COMMIT) {
    console.log("Appveyor: skip create tag and release.");
    process.exit(0);
}

const message = process.env.TRAVIS_TAG;
const object = envCommitSha;
const type =  "commit";
const tagger = {
    name: "Daniel Weck",
    email: "daniel.weck@gmail.com",
    date: new Date().toISOString(),
};

console.log("################################################");
console.log("################ createTag:");
let createTagRES = undefined;
try {
    createTagRES = await octokit.git.createTag({owner, repo, tag, message, object, type, tagger, "tagger:name": tagger.name, "tagger:email": tagger.email, "tagger:date": tagger.date});
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("createTag error! Continue.");
    // console.log("createTag error! Abort.");
    // process.exit(1);
    // return;
}
if (createTagRES) {
    console.log("createTagRES:");
    if (DEBUG) console.log(createTagRES);

    const ref2 = `refs/tags/${process.env.TRAVIS_TAG}`;
    const sha = createTagRES.data.sha;

    console.log("################################################");
    console.log("################ createRef:");
    let createRefRES = undefined;
    try {
        createRefRES = await octokit.git.createRef({owner, repo, ref: ref2, sha});
    } catch (err) {
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        if (DEBUG) console.log(err);
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        console.log("createRef error! Continue.");
        // console.log("createRef error! Abort.");
        // process.exit(1);
        // return;
    }

    if (createRefRES) {
        console.log("createRefRES:");
        if (DEBUG) console.log(createRefRES);
    }
}

const travisURL = process.env.TRAVIS_JOB_WEB_URL || process.env.TRAVIS_BUILD_WEB_URL || `${process.env.APPVEYOR_URL}/project/${owner_appveyor}/${repo}/builds/${process.env.APPVEYOR_BUILD_ID}`;

const tag_name = process.env.TRAVIS_TAG;
const target_commitish = envCommitSha;
const name = `[${tag_name}] continuous test build (prerelease)`;
const body = `Travis build job: ${travisURL}`; // gets replaced by Appveyor script anyway
const draft = false;
const prerelease = true;

console.log("################################################");
console.log("################ createRelease:");
let createReleaseRES = undefined;
try {
    createReleaseRES = await octokit.repos.createRelease({owner, repo, tag_name, target_commitish, name, body, draft, prerelease});
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("createRelease error! Continue.");
    // console.log("createRelease error! Abort.");
    // process.exit(1);
    // return;
}

if (createReleaseRES) {
    console.log("createReleaseRES:");
    if (DEBUG) console.log(createReleaseRES);
}

})();
<commit_msg>chore(CI): TravisCI deploy script with new edrlab/thorium-reader GitHub repository (was readium/readium-desktop)<commit_after>var fs = require("fs");
var path = require("path");

// https://github.com/octokit/rest.js
// https://octokit.github.io/rest.js/
const { Octokit } = require('@octokit/rest');

console.log("process.cwd():");
console.log(process.cwd());
console.log("path.resolve(\".\")");
console.log(path.resolve("."));

console.log("__dirname:");
console.log(__dirname);

const args = process.argv.slice(2);
console.log("args:");
console.log(args);

const envCommitSha = process.env.TRAVIS_COMMIT || process.env.APPVEYOR_REPO_COMMIT;

console.log("TRAVIS_COMMIT:");
console.log(envCommitSha);
if (!envCommitSha) {
    console.log("Missing TRAVIS_COMMIT! Abort.");
    process.exit(1);
    return;
}

console.log("TRAVIS_TAG:");
console.log(process.env.TRAVIS_TAG);
if (!process.env.TRAVIS_TAG) {
    console.log("Missing TRAVIS_TAG! Abort.");
    process.exit(1);
    return;
}

if (!process.env.GH_TOKEN) {
    console.log("Missing GH_TOKEN! Abort.");
    process.exit(1);
    return;
}

const octokit = new Octokit({
    auth: `token ${process.env.GH_TOKEN}`
});

// !!!!!!!!!!!!!!!!
// IMPORTANT !!!!
// Make sure DEBUG is *off* in TravisCI,
// as this potentially prints console messages that contain the HTTP header:
// authorization: 'token GH_TOKEN'
// It that happens, revoke the token immediately!
// https://github.com/settings/tokens
// Example: when getReleaseByTag() return 404
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
const DEBUG = false;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

const owner_appveyor = "danielweck";
const owner = "edrlab";
const repo = "thorium-reader";
const tag = process.env.TRAVIS_TAG;

(async () => {

console.log("################################################");
console.log("################ getReleaseByTag:");
let getReleaseByTagRES = undefined;
try {
    getReleaseByTagRES = await octokit.repos.getReleaseByTag({owner, repo, tag})
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("getReleaseByTag error! Continue.");
    // if (err.status !== 404) {
    //     console.log("getReleaseByTag error! Abort.");
    //     process.exit(1);
    //     return;
    // }
}

if (getReleaseByTagRES) {
    console.log("getReleaseByTagRES:");
    if (DEBUG) console.log(getReleaseByTagRES);

    const release_id = getReleaseByTagRES.data.id;

    console.log("################################################");
    console.log("################ deleteRelease:");
    let deleteReleaseRES = undefined;
    try {
        deleteReleaseRES = await octokit.repos.deleteRelease({owner, repo, release_id})
    } catch (err) {
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        if (DEBUG) console.log(err);
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        console.log("deleteReleaseRES error! Continue.");
        // console.log("deleteRelease error! Abort.");
        // process.exit(1);
        // return;
    }
    if (deleteReleaseRES) {
        console.log("deleteReleaseRES:");
        if (DEBUG) console.log(deleteReleaseRES);
    }
}

const ref = `tags/${process.env.TRAVIS_TAG}`;

console.log("################################################");
console.log("################ deleteRef:");
let deleteRefRES = undefined;
try {
    deleteRefRES = await octokit.git.deleteRef({owner, repo, ref})
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("deleteRefRES error! Continue.");
    // console.log("deleteRef error! Abort.");
    // process.exit(1);
    // return;
}

if (deleteRefRES) {
    console.log("deleteRefRES:");
    if (DEBUG) console.log(deleteRefRES);
}

if (process.env.APPVEYOR_REPO_COMMIT) {
    console.log("Appveyor: skip create tag and release.");
    process.exit(0);
}

const message = process.env.TRAVIS_TAG;
const object = envCommitSha;
const type =  "commit";
const tagger = {
    name: "Daniel Weck",
    email: "daniel.weck@gmail.com",
    date: new Date().toISOString(),
};

console.log("################################################");
console.log("################ createTag:");
let createTagRES = undefined;
try {
    createTagRES = await octokit.git.createTag({owner, repo, tag, message, object, type, tagger, "tagger:name": tagger.name, "tagger:email": tagger.email, "tagger:date": tagger.date});
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("createTag error! Continue.");
    // console.log("createTag error! Abort.");
    // process.exit(1);
    // return;
}
if (createTagRES) {
    console.log("createTagRES:");
    if (DEBUG) console.log(createTagRES);

    const ref2 = `refs/tags/${process.env.TRAVIS_TAG}`;
    const sha = createTagRES.data.sha;

    console.log("################################################");
    console.log("################ createRef:");
    let createRefRES = undefined;
    try {
        createRefRES = await octokit.git.createRef({owner, repo, ref: ref2, sha});
    } catch (err) {
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        if (DEBUG) console.log(err);
        console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
        console.log("createRef error! Continue.");
        // console.log("createRef error! Abort.");
        // process.exit(1);
        // return;
    }

    if (createRefRES) {
        console.log("createRefRES:");
        if (DEBUG) console.log(createRefRES);
    }
}

const travisURL = process.env.TRAVIS_JOB_WEB_URL || process.env.TRAVIS_BUILD_WEB_URL || `${process.env.APPVEYOR_URL}/project/${owner_appveyor}/${repo}/builds/${process.env.APPVEYOR_BUILD_ID}`;

const tag_name = process.env.TRAVIS_TAG;
const target_commitish = envCommitSha;
const name = `[${tag_name}] continuous test build (prerelease)`;
const body = `Travis build job: ${travisURL}`; // gets replaced by Appveyor script anyway
const draft = false;
const prerelease = true;

console.log("################################################");
console.log("################ createRelease:");
let createReleaseRES = undefined;
try {
    createReleaseRES = await octokit.repos.createRelease({owner, repo, tag_name, target_commitish, name, body, draft, prerelease});
} catch (err) {
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    if (DEBUG) console.log(err);
    console.log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    console.log("createRelease error! Continue.");
    // console.log("createRelease error! Abort.");
    // process.exit(1);
    // return;
}

if (createReleaseRES) {
    console.log("createReleaseRES:");
    if (DEBUG) console.log(createReleaseRES);
}

})();
<|endoftext|>


<commit_before>chatApp.factory('MessageObserver', ['SocketIOMessageObserver',
	function MessageObserver (MessageObserverStrategy) {
		return new MessageObserverStrategy();
	}
]);<commit_msg>Changed default strategy to polling<commit_after>chatApp.factory('MessageObserver', ['PollingMessageObserver',
	function MessageObserver (MessageObserverStrategy) {
		return new MessageObserverStrategy();
	}
]);<|endoftext|>


<commit_before>/*

	Dr ToDo Little
	The main controller

*/
tdapp.controller("MainCtrl",
function(
	$scope,
	$timeout,
	$location,
	$routeParams,
	todoservice
){

	// General Done Filter
	$scope.showdone = false;
	$scope.showdonetext = "Show Done";

	// Keyboard
	$scope.newtodoKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic = $scope.newtodotxt;
				newtodo.done = false;
				$scope.newtodotxt = "";
				todoservice.create(newtodo);
				if($scope.showdone){
					$scope.showdone = false;
					$scope.showdonetext = "Show Done";
				}
				if(newtodo.tag!=undefined){
					$scope.filtertag = newtodo.tag;
				} else {
					$scope.filtertag = "All";
				}
				$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
				window.scrollTo(0,0);
				$("#todotxta").focus();
			}
		} else
		if(k==9){//tab
			e.preventDefault();
		}
	}

	$scope.todolineKeydown = function(e,id){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			var currentTodo = $('#todoid'+id);
			// Correct contenteditable behaviour
			currentTodo.html(currentTodo.html().replace('
',''));
			currentTodo.blur();
			var obj = todoservice.getTodoById(id);
			if(obj!=undefined){
				obj.topic = currentTodo.html();
				todoservice.update(obj);
				var oldtag = obj.tag;
				todoservice.checkForHashtag(obj);
				if(oldtag!=undefined){
					var ttd = todoservice.getTodosByTag(oldtag);
					if(ttd.length<=0){
						todoservice.tags.splice(todoservice.tags.indexOf(oldtag),1);
					}
				}
				$scope.tags = (todoservice.getTags()).sort();
				$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
			}
		}
	}

	$scope.displaytodos = function(tag) {
		$scope.filtertag = tag;
		$scope.todos = todoservice.getTodosByTag(tag,$scope.showdone);
	}

	// Todo functions
	$scope.seltodoline = function(id){
		$("#todoid"+id).focus();
	}

	$scope.deltodo = function(obj){ // No animation
		obj.deleted = true;
		todoservice.delTodo(obj);
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	$scope.togDone = function(item) {
		if (item.done) {
			todoservice.undone(item);
			item.done = false;
		}
		else {
			todoservice.done(item);
			item.done=true;
		}
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	$scope.saveedittodo = function(todo){
		$scope.showedit = false;
		todoservice.update(todo);
	}

	// Filter function

	$scope.togShowdone = function(){
		$scope.showdone = !$scope.showdone;
		if($scope.showdone){
			$scope.showdonetext = "Show Open";
		} else {
			$scope.showdonetext = "Show Done";
		}
		$scope.todos=todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	// Tags

	$scope.getTodosByTag = todoservice.getTodosByTag;
	todoservice.getTodos().then(function(todos) {
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
		$scope.tags = todoservice.getTags();
	});

	// Routeparams
	if(
		$routeParams.type!=undefined &&
		$routeParams.id!=undefined &&
		$routeParams.type=="todo"
	){
		var todo = TDMgr.getTodoById($routeParams.id)
		if(todo!=undefined){
			var todos = [];
			todos.push(todo);
			$scope.todos = todos;
		} else {
			$scope.todos = [];
		}
	}
	if(
		$routeParams.type!=undefined &&
		$routeParams.id!=undefined &&
		$routeParams.type=="tag"
	){
		$scope.todos = TDMgr.getTodosByTag("#"+$routeParams.id,false);
	}

	// Finish
	$("#todotxta").focus();

});
<commit_msg>Bugfix.<commit_after>/*

	Dr ToDo Little
	The main controller

*/
tdapp.controller("MainCtrl",
function(
	$scope,
	$timeout,
	$location,
	$routeParams,
	todoservice
){

	// General Done Filter
	$scope.showdone = false;
	$scope.showdonetext = "Show Done";

	// Keyboard
	$scope.newtodoKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			if($scope.newtodotxt!=""){
				var newtodo = {};
				newtodo.topic = $scope.newtodotxt;
				newtodo.done = false;
				$scope.newtodotxt = "";
				todoservice.create(newtodo);
				if($scope.showdone){
					$scope.showdone = false;
					$scope.showdonetext = "Show Done";
				}
				if(newtodo.tag!=undefined){
					$scope.filtertag = newtodo.tag;
				} else {
					$scope.filtertag = "All";
				}
				$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
				window.scrollTo(0,0);
				$("#todotxta").focus();
			}
		} else
		if(k==9){//tab
			e.preventDefault();
		}
	}

	$scope.todolineKeydown = function(e,id){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			var currentTodo = $('#todoid'+id);
			// Correct contenteditable behaviour
			currentTodo.html(currentTodo.html().replace('
',''));
			currentTodo.blur();
			var obj = todoservice.getTodoById(id);
			if(obj!=undefined){
				obj.topic = currentTodo.html();
				todoservice.update(obj);
				var oldtag = obj.tag;
				todoservice.checkForHashtag(obj);
				if(oldtag!=undefined){
					var ttd = todoservice.getTodosByTag(oldtag);
					if(ttd.length<=0){
						todoservice.tags.splice(todoservice.tags.indexOf(oldtag),1);
					}
				}
				$scope.tags = (todoservice.getTags()).sort();
				$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
			}
		}
	}

	$scope.displaytodos = function(tag) {
		$scope.filtertag = tag;
		$scope.todos = todoservice.getTodosByTag(tag,$scope.showdone);
	}

	// Todo functions
	$scope.seltodoline = function(id){
		$("#todoid"+id).focus();
	}

	$scope.deltodo = function(obj){ // No animation
		obj.deleted = true;
		todoservice.delTodo(obj);
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	$scope.togDone = function(item) {
		if (item.done) {
			todoservice.undone(item);
			item.done = false;
		}
		else {
			todoservice.done(item);
			item.done=true;
		}
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	$scope.saveedittodo = function(todo){
		$scope.showedit = false;
		todoservice.update(todo);
	}

	// Filter function

	$scope.togShowdone = function(){
		$scope.showdone = !$scope.showdone;
		if($scope.showdone){
			$scope.showdonetext = "Show Open";
		} else {
			$scope.showdonetext = "Show Done";
		}
		$scope.todos=todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
	}

	// Tags

	$scope.getTodosByTag = todoservice.getTodosByTag;
	todoservice.getTodos().then(function(todos) {
		$scope.todos = todoservice.getTodosByTag($scope.filtertag,$scope.showdone);
		$scope.tags = todoservice.getTags();
	});

	// Routeparams
	if(
		$routeParams.type!=undefined &&
		$routeParams.id!=undefined &&
		$routeParams.type=="todo"
	){
		var todo = todoservice.getTodoById($routeParams.id)
		if(todo!=undefined){
			var todos = [];
			todos.push(todo);
			$scope.todos = todos;
		} else {
			$scope.todos = [];
		}
	}
	if(
		$routeParams.type!=undefined &&
		$routeParams.id!=undefined &&
		$routeParams.type=="tag"
	){
		$scope.todos = todoservice.getTodosByTag("#"+$routeParams.id,false);
	}

	// Finish
	$("#todotxta").focus();

});
<|endoftext|>