<commit_before>'use strict'

require("babel-core").transform("code");

const {ipcRenderer} = require('electron');
const {shell} = require('electron');
const {requireTaskPool} = require('electron-remote');
const {app} = require('electron').remote;

const remote = require('electron').remote,
	  fs = require('fs'),
	  path = require('path'),
	  pImg = requireTaskPool(require.resolve('./scripts/imgProcess')),
	  jFiles = path.join(app.getPath('userData'), 'files.json'),
	  unFiles = path.join(app.getPath('userData'), 'unprocessed.json'),
	  dirFile = path.join(app.getPath('userData'), 'dir.json');

let docFrag = document.createDocumentFragment(),
	pFiles = [],
	uArray = [],
	jsonFiles = [],
	progTotal = 0,
	progAmt = 0,
	dir;

// Create window controls and browse functionality
(function() {
	document.getElementById('min-btn').addEventListener('click', () => {
		remote.getCurrentWindow().minimize();
	}, false);

	document.getElementById('max-btn').addEventListener('click', () => {
		if (!remote.getCurrentWindow().isMaximized()) {
			remote.getCurrentWindow().maximize();
		} else {
			remote.getCurrentWindow().unmaximize();
		}
	}, false);

	document.getElementById('close-btn').addEventListener('click', () => {

		// Add processed images to files.json if app quit before finishing
		if (pFiles.length > 0) {
			addFiles(pFiles);
		} else {
			app.quit();
		}

		// All images processed? Remove file. If not, save list.
		if (uArray.length === 0) {
			fs.unlink(unFiles, (err) => {
				if (err) throw err;
			});
		} else {
			fs.writeFile(unFiles, JSON.stringify(uArray, null, '\t'), (err) => {
				if (err) console.log(err);
			});
		}

	}, false);

	// Fetch dir chosen by user
	if (fs.existsSync(dirFile)) {
		fs.readFile(dirFile, (err, data) => {
			if (err) throw err;

			dir = JSON.parse(data);
		});
	}

	// If files have been processed, display them
	if (fs.existsSync(jFiles)) {
		jsonDisplay();
	} else {
		document.getElementById('browse').style.display = 'block';
	}

	// If unprocessed images, continue processing them
	if (fs.existsSync(unFiles)) {
		fs.readFile(unFiles, (err, data) => {
			if (err) throw err;

			const unprocessedJson = JSON.parse(data);
			uArray = unprocessedJson;
			initAssets(unprocessedJson, dir[0]);
		});
	}

	// Send message to main process to load files
	document.getElementById('browse-files').addEventListener('click', () => {
		ipcRenderer.send('loadAssets');
	});

	// Add event listener for filter options
	document.getElementById('ftr-clear').addEventListener('click', () => {
		showEl();
	});
	document.getElementById('ftr-stock-photos').addEventListener('click', () => {
		filters("stock");
	});
	document.getElementById('ftr-icons').addEventListener('click', () => {
		filters("icons");
	});
	document.getElementById('ftr-fonts').addEventListener('click', () => {
		filters("fonts");
	});
	document.getElementById('ftr-mockups').addEventListener('click', () => {
		filters("mockups");
	});
	document.getElementById('ftr-ui-elements').addEventListener('click', () => {
		filters("kits");
	});

	// Initially hide progress bar
	document.getElementById('progCont').style.display = 'none';

	search();
})();

// Displays assets once browse btn is clicked
ipcRenderer.on('getAssets', (event, filtered, filePath) => {
	document.getElementById('browse').style.display = 'none';
	let jsonFilePath = [filePath.replace(/\\/g,"\\") + "\\"];

	fs.writeFile(path.join(app.getPath('userData'), 'dir.json'), JSON.stringify(jsonFilePath, null, '\t'), (err) => {
		if (err) console.log(err);
	});

	let aPath = filePath + "\\";
	uArray = filtered;
	initAssets(filtered, aPath);
});

// Process and append each asset
function initAssets(array, aPath) {
	progTotal = array.length;

	for (let i = array.length; i-- > 0;) {
		process(array, i, aPath);

		// If at end of array, save json. Prevent overwritting. Use addFiles()
		if (i === 0) {
			if (fs.existsSync(jFiles)) {
				fs.readFile(jFiles, (err, data) => {
					if (err) throw err;

					const jsonFiles = JSON.parse(data),
						  newFiles = jsonFiles.concat(pFiles);

					fs.writeFile(jFiles, JSON.stringify(newFiles, null, '\t'), (err) => {
						if (err) throw err;
					});
				});
			} else {
				fs.writeFile(jFiles, JSON.stringify(pFiles), (err) => {
					if (err) console.log(err);
				});
			}
		}
	}
}

// Process Images
function process(image, count, aPath) {
	// Format path strings
	let src = image[count].path.replace(/\\/g,"/"),
		fileName = path.basename(image[count].path).replace(/\.[^.]+$/g,""),
		tagPath = image[count].path.replace(aPath, ""), // Remove dir from path
		assetTags = tagPath.toLowerCase().replace(/\\/g," ").split(" "); // Create array of tags

	// Process image
	pImg.processImage(src, count).then((path) => {
		let formattedPath = path.replace(/\\/g,"/"),
			assetID = count.toString();

		// Push file info to array
		pFiles.push({id: assetID, file: formattedPath, name: fileName, og: src, tags: assetTags});

		jsonFiles.push({id: assetID, file: formattedPath, name: fileName, og: src, tags: assetTags});

		// Filter out processed image from array
		uArray = uArray.filter(item => item.path != image[count].path);

		// Create html for images
		genHtml(fileName, formattedPath, src, assetID);

		progressBar();

		// Iterate progress
		progAmt++;
	});
};

// Displays processed files
function jsonDisplay() {
	fs.readFile(jFiles, (err, data) => {
		if (err) throw err;

		jsonFiles = JSON.parse(data);

		for (let i = 0; i < jsonFiles.length; i++) {
			genHtml(jsonFiles[i].name, jsonFiles[i].file, jsonFiles[i].og, jsonFiles[i].id);
		}
	});
}

// Create HTML elements and display images
function genHtml(fName, fPath, ogPath, id) {
	// Create html elements
	let divImg = document.createElement('div'),
		imageNode = document.createElement('div'),
		imgName = document.createElement('p'),
		img = document.createElement('img'),
		text = document.createTextNode(fName),
		openBtn = document.createElement('div'),
		openTxt = document.createElement('p'),
		openTxtValue = document.createTextNode('open file location'),
		openIcon = document.createElement('img');

	// Create styles and add file path to div
	divImg.className = 'asset-img';
	divImg.id = id;
	//imgName.className = 'asset-title';
	imageNode.className = 'image-node';
	openBtn.className = 'open-btn';
	openTxt.className = 'open-txt';
	openIcon.classList = 'open-icon';
	openIcon.src = './assets/open-icon.png';
	img.src = fPath;

	// Add hover events
	imageNode.addEventListener('mouseover', () => {
		openBtn.style.display = 'block';
		openTxt.style.display = 'block';
	}, false);
	imageNode.addEventListener('mouseout', () => {
		openBtn.style.display = 'none';
		openTxt.style.display = 'none';
	}, false);

	// Add click events
	imageNode.addEventListener('click', () => {
		shell.showItemInFolder(ogPath);
	}, false);

	// Append elements to containers
	docFrag.appendChild(divImg);
	divImg.appendChild(imageNode);
	divImg.appendChild(imgName);
	imageNode.appendChild(openBtn);
	imageNode.appendChild(img);
	imageNode.appendChild(openTxt);
	openTxt.appendChild(openTxtValue);
	//imgName.appendChild(text);
	openBtn.appendChild(openIcon);
	document.getElementById('asset-feed').appendChild(docFrag);
}

// Adds newly processed files to json file - Can use in initAssets()
function addFiles(array) {
	if (fs.existsSync(jFiles)) {
		fs.readFile(jFiles, (err, data) => {
			if (err) throw err;

			const j = JSON.parse(data),
				  newFiles = j.concat(array);

			fs.writeFile(jFiles, JSON.stringify(newFiles, null, '\t'), (err) => {
				if (err) throw err;

				app.quit();
			});
		});
	} else {
		fs.writeFile(jFiles, JSON.stringify(array, null, '\t'), (err) => {
			if (err) throw err;

			app.quit();
		});
	}
}

// Search assets
function search() {
	let elements = document.getElementsByClassName('asset-img');

	document.getElementById('searchBar').addEventListener('keyup', () => {
		let searchVal = document.getElementById('searchBar').value;

		if (searchVal !== '') {
			for (let i = 0; i < elements.length; i++) {
				elements[i].style.display = 'none';
			}
		} else {
			for (let i = 0; i < elements.length; i++) {
				elements[i].style.display = 'flex';
			}
		}

		pFilterSearch(jsonFiles, searchVal.toLowerCase()).then((results) => {
			console.log(searchVal.toLowerCase());
			for (let i = 0; i < results.length; i++) {
				console.log(results[i]);
				document.getElementById(results[i].id).style.display = "flex";
			}
		});
	});
}

function pFilterSearch(arr, searchString) {
	return new Promise((resolve) => {
		resolve(arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchString))));
	});
}

function filters(option) {
	let elements = document.getElementsByClassName('asset-img');

	for (let i = 0; i < elements.length; i++) {
		elements[i].style.display = 'none';
	}

	pFilterSearch(jsonFiles, option).then((results) => {
		for (let i = 0; i < results.length; i++) {
			document.getElementById(results[i].id).style.display = "flex";
		}
	});
}

function showEl() {
	let elements = document.getElementsByClassName('asset-img');

	for (let i = 0; i < elements.length; i++) {
		elements[i].style.display = 'flex';
	}
}

// Show and update progress bar
function progressBar() {
	let progUp = (progAmt / progTotal) * 100;

	if (progUp.toFixed() != 100) {
		document.getElementById('progCont').style.display = 'block';
		document.getElementById('container').style.top = '160px';
	} else {
		setTimeout(() => {document.getElementById('progCont').style.display = 'none';}, 1000);
		document.getElementById('container').style.top = '110px';
	}

	document.getElementById('progBar').MaterialProgress.setProgress(progUp.toFixed());
}<commit_msg>Improved search by using tags<commit_after>'use strict'

require("babel-core").transform("code");

const {ipcRenderer} = require('electron');
const {shell} = require('electron');
const {requireTaskPool} = require('electron-remote');
const {app} = require('electron').remote;

const remote = require('electron').remote,
	  fs = require('fs'),
	  path = require('path'),
	  pImg = requireTaskPool(require.resolve('./scripts/imgProcess')),
	  jFiles = path.join(app.getPath('userData'), 'files.json'),
	  unFiles = path.join(app.getPath('userData'), 'unprocessed.json'),
	  dirFile = path.join(app.getPath('userData'), 'dir.json');

let docFrag = document.createDocumentFragment(),
	pFiles = [],
	uArray = [],
	jsonFiles = [],
	progTotal = 0,
	progAmt = 0,
	dir;

// Create window controls and browse functionality
(function() {
	document.getElementById('min-btn').addEventListener('click', () => {
		remote.getCurrentWindow().minimize();
	}, false);

	document.getElementById('max-btn').addEventListener('click', () => {
		if (!remote.getCurrentWindow().isMaximized()) {
			remote.getCurrentWindow().maximize();
		} else {
			remote.getCurrentWindow().unmaximize();
		}
	}, false);

	document.getElementById('close-btn').addEventListener('click', () => {

		// Add processed images to files.json if app quit before finishing
		if (pFiles.length > 0) {
			addFiles(pFiles);
		} else {
			app.quit();
		}

		// All images processed? Remove file. If not, save list.
		if (uArray.length === 0) {
			fs.unlink(unFiles, (err) => {
				if (err) throw err;
			});
		} else {
			fs.writeFile(unFiles, JSON.stringify(uArray, null, '\t'), (err) => {
				if (err) console.log(err);
			});
		}

	}, false);

	// Fetch dir chosen by user
	if (fs.existsSync(dirFile)) {
		fs.readFile(dirFile, (err, data) => {
			if (err) throw err;

			dir = JSON.parse(data);
		});
	}

	// If files have been processed, display them
	if (fs.existsSync(jFiles)) {
		jsonDisplay();
	} else {
		document.getElementById('browse').style.display = 'block';
	}

	// If unprocessed images, continue processing them
	if (fs.existsSync(unFiles)) {
		fs.readFile(unFiles, (err, data) => {
			if (err) throw err;

			const unprocessedJson = JSON.parse(data);
			uArray = unprocessedJson;
			initAssets(unprocessedJson, dir[0]);
		});
	}

	// Send message to main process to load files
	document.getElementById('browse-files').addEventListener('click', () => {
		ipcRenderer.send('loadAssets');
	});

	// Add event listener for filter options
	document.getElementById('ftr-clear').addEventListener('click', () => {
		showEl();
	});
	document.getElementById('ftr-stock-photos').addEventListener('click', () => {
		filters("stock");
	});
	document.getElementById('ftr-icons').addEventListener('click', () => {
		filters("icons");
	});
	document.getElementById('ftr-fonts').addEventListener('click', () => {
		filters("fonts");
	});
	document.getElementById('ftr-mockups').addEventListener('click', () => {
		filters("mockups");
	});
	document.getElementById('ftr-ui-elements').addEventListener('click', () => {
		filters("kits");
	});

	// Initially hide progress bar
	document.getElementById('progCont').style.display = 'none';

	search();
})();

// Displays assets once browse btn is clicked
ipcRenderer.on('getAssets', (event, filtered, filePath) => {
	document.getElementById('browse').style.display = 'none';
	let jsonFilePath = [filePath.replace(/\\/g,"\\") + "\\"];

	fs.writeFile(path.join(app.getPath('userData'), 'dir.json'), JSON.stringify(jsonFilePath, null, '\t'), (err) => {
		if (err) console.log(err);
	});

	let aPath = filePath + "\\";
	uArray = filtered;
	initAssets(filtered, aPath);
});

// Process and append each asset
function initAssets(array, aPath) {
	progTotal = array.length;

	for (let i = array.length; i-- > 0;) {
		process(array, i, aPath);

		// If at end of array, save json. Prevent overwritting. Use addFiles()
		if (i === 0) {
			if (fs.existsSync(jFiles)) {
				fs.readFile(jFiles, (err, data) => {
					if (err) throw err;

					const jsonFiles = JSON.parse(data),
						  newFiles = jsonFiles.concat(pFiles);

					fs.writeFile(jFiles, JSON.stringify(newFiles, null, '\t'), (err) => {
						if (err) throw err;
					});
				});
			} else {
				fs.writeFile(jFiles, JSON.stringify(pFiles), (err) => {
					if (err) console.log(err);
				});
			}
		}
	}
}

// Process Images
function process(image, count, aPath) {
	// Format path strings
	let src = image[count].path.replace(/\\/g,"/"),
		fileName = path.basename(image[count].path).replace(/\.[^.]+$/g,""),
		tagPath = image[count].path.replace(aPath, ""), // Remove dir from path
		assetTags = tagPath.toLowerCase().replace(/\W|_/g," ").split(" "); // Create array of tags

	// Process image
	pImg.processImage(src, count).then((path) => {
		let formattedPath = path.replace(/\\/g,"/"),
			assetID = count.toString();

		// Push file info to array
		pFiles.push({id: assetID, file: formattedPath, name: fileName, og: src, tags: assetTags});

		jsonFiles.push({id: assetID, file: formattedPath, name: fileName, og: src, tags: assetTags});

		// Filter out processed image from array
		uArray = uArray.filter(item => item.path != image[count].path);

		// Create html for images
		genHtml(fileName, formattedPath, src, assetID);

		progressBar();

		// Iterate progress
		progAmt++;
	});
};

// Displays processed files
function jsonDisplay() {
	fs.readFile(jFiles, (err, data) => {
		if (err) throw err;

		jsonFiles = JSON.parse(data);

		for (let i = 0; i < jsonFiles.length; i++) {
			genHtml(jsonFiles[i].name, jsonFiles[i].file, jsonFiles[i].og, jsonFiles[i].id);
		}
	});
}

// Create HTML elements and display images
function genHtml(fName, fPath, ogPath, id) {
	// Create html elements
	let divImg = document.createElement('div'),
		imageNode = document.createElement('div'),
		imgName = document.createElement('p'),
		img = document.createElement('img'),
		text = document.createTextNode(fName),
		openBtn = document.createElement('div'),
		openTxt = document.createElement('p'),
		openTxtValue = document.createTextNode('open file location'),
		openIcon = document.createElement('img');

	// Create styles and add file path to div
	divImg.className = 'asset-img';
	divImg.id = id;
	//imgName.className = 'asset-title';
	imageNode.className = 'image-node';
	openBtn.className = 'open-btn';
	openTxt.className = 'open-txt';
	openIcon.classList = 'open-icon';
	openIcon.src = './assets/open-icon.png';
	img.src = fPath;

	// Add hover events
	imageNode.addEventListener('mouseover', () => {
		openBtn.style.display = 'block';
		openTxt.style.display = 'block';
	}, false);
	imageNode.addEventListener('mouseout', () => {
		openBtn.style.display = 'none';
		openTxt.style.display = 'none';
	}, false);

	// Add click events
	imageNode.addEventListener('click', () => {
		shell.showItemInFolder(ogPath);
	}, false);

	// Append elements to containers
	docFrag.appendChild(divImg);
	divImg.appendChild(imageNode);
	divImg.appendChild(imgName);
	imageNode.appendChild(openBtn);
	imageNode.appendChild(img);
	imageNode.appendChild(openTxt);
	openTxt.appendChild(openTxtValue);
	//imgName.appendChild(text);
	openBtn.appendChild(openIcon);
	document.getElementById('asset-feed').appendChild(docFrag);
}

// Adds newly processed files to json file - Can use in initAssets()
function addFiles(array) {
	if (fs.existsSync(jFiles)) {
		fs.readFile(jFiles, (err, data) => {
			if (err) throw err;

			const j = JSON.parse(data),
				  newFiles = j.concat(array);

			fs.writeFile(jFiles, JSON.stringify(newFiles, null, '\t'), (err) => {
				if (err) throw err;

				app.quit();
			});
		});
	} else {
		fs.writeFile(jFiles, JSON.stringify(array, null, '\t'), (err) => {
			if (err) throw err;

			app.quit();
		});
	}
}

// Search assets
function search() {
	let elements = document.getElementsByClassName('asset-img');

	document.getElementById('searchBar').addEventListener('keyup', () => {
		let searchVal = document.getElementById('searchBar').value;

		if (searchVal !== '') {
			for (let i = 0; i < elements.length; i++) {
				elements[i].style.display = 'none';
			}
		} else {
			for (let i = 0; i < elements.length; i++) {
				elements[i].style.display = 'flex';
			}
		}

		pFilterSearch(jsonFiles, searchVal.toLowerCase()).then((results) => {
			for (let i = 0; i < results.length; i++) {
				console.log(results[i]);
				document.getElementById(results[i].id).style.display = "flex";
			}
		});
	});
}

function pFilterSearch(arr, searchString) {
	return new Promise((resolve) => {
		/*resolve(arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchString))));*/
		resolve(arr.filter(obj => obj.tags.some(tag => tag.includes(searchString))));
	});
}

function filters(option) {
	let elements = document.getElementsByClassName('asset-img');

	for (let i = 0; i < elements.length; i++) {
		elements[i].style.display = 'none';
	}

	pFilterSearch(jsonFiles, option).then((results) => {
		for (let i = 0; i < results.length; i++) {
			document.getElementById(results[i].id).style.display = "flex";
		}
	});
}

function showEl() {
	let elements = document.getElementsByClassName('asset-img');

	for (let i = 0; i < elements.length; i++) {
		elements[i].style.display = 'flex';
	}
}

// Show and update progress bar
function progressBar() {
	let progUp = (progAmt / progTotal) * 100;

	if (progUp.toFixed() != 100) {
		document.getElementById('progCont').style.display = 'block';
		document.getElementById('container').style.top = '160px';
	} else {
		setTimeout(() => {document.getElementById('progCont').style.display = 'none';}, 1000);
		document.getElementById('container').style.top = '110px';
	}

	document.getElementById('progBar').MaterialProgress.setProgress(progUp.toFixed());
}<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-rapid-forms'
};
<commit_msg>fix: included hook added<commit_after>/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-rapid-forms',
  included: function(app) {
    this._super.included(...arguments);
  }
};
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

// var path = require('path');

module.exports = {
  name: 'ember-power-select',

  included: function(app) {
    this._super.included(app);
    // Don't include the precompiled css file if the user uses ember-cli-sass
    if (!app.registry.availablePlugins['ember-cli-sass']) {
      var addonConfig = app.options['ember-power-select'];

      if (!addonConfig || !addonConfig.theme) {
        app.import('vendor/ember-power-select.css');
      } else {
        app.import('vendor/ember-power-select-'+addonConfig.theme+'.css');
      }
    }
  },

  contentFor: function(type, config) {
    var emberBasicDropdown = this.addons.filter(function(addon) {
      return addon.name === 'ember-basic-dropdown';
    })[0]
    return emberBasicDropdown.contentFor.apply(this, [type, config]);
  }
};
 <commit_msg>As per @rwjblue advice, do `this._super.included.apply(this, arguments);` instead<commit_after>/* jshint node: true */
'use strict';

// var path = require('path');

module.exports = {
  name: 'ember-power-select',

  included: function(app) {
    this._super.included.apply(this, arguments);
    // Don't include the precompiled css file if the user uses ember-cli-sass
    if (!app.registry.availablePlugins['ember-cli-sass']) {
      var addonConfig = app.options['ember-power-select'];

      if (!addonConfig || !addonConfig.theme) {
        app.import('vendor/ember-power-select.css');
      } else {
        app.import('vendor/ember-power-select-'+addonConfig.theme+'.css');
      }
    }
  },

  contentFor: function(type, config) {
    var emberBasicDropdown = this.addons.filter(function(addon) {
      return addon.name === 'ember-basic-dropdown';
    })[0]
    return emberBasicDropdown.contentFor.apply(this, [type, config]);
  }
};
 <|endoftext|>


<commit_before>/**
 * Plugin dependencies.
 *
 * @type {exports}
 */
var GitHubApi = require('github');
var shorturl = require('shorturl');
var moment = require('moment');
var async = require('async');
var _ = require('lodash');

/**
 * URL log plugin for UniBot
 *
 * @param  {Object} options Plugin options object, description below.
 *   db: {mongoose} the mongodb connection
 *   bot: {irc} the irc bot
 *   web: {connect} a connect + connect-rest webserver
 *   config: {object} UniBot configuration
 *
 * @return  {Function}  Init function to access shared resources
 */
module.exports = function init(options) {
    var config = options.config || {};

    /**
     * Plugin configuration.
     *
     * @type    {{
     *              moment: {
     *                  locale: string,
     *                  format: string
     *              },
     *              gist: {
     *                  message: string,
     *                  noDescription: string
     *              }
     *          }}
     */
    var pluginConfig = {
        "moment": {
            "locale": "",
            "format": "DD.MM.YYYY HH:mm:ss"
        },
        "gist": {
            "message": "${url} - ${date} - ${description}",
            "noDescription": "No description"
        }
    };

    // Merge configuration for plugin
    if (_.isObject(config.plugins) && _.isObject(config.plugins.github)) {
        pluginConfig = _.merge(pluginConfig, config.plugins.github);
    }

    // Set moment locale, if it's set
    if (pluginConfig.moment.locale) {
        moment.locale(pluginConfig.moment.locale);
    }

    // Create GitHub API connection
    var github = new GitHubApi({
        version: '3.0.0'
    });

    return function plugin(channel) {
        return {
            "^!ghGist(?: (\\S+))?(?: (\\d+))?$": function onMatch(from, matches) {
                var username = from;
                var itemCount = 1;

                if (matches[2]) {
                    username = matches[1];
                    itemCount = matches[2];
                } else if (matches[1]) {
                    username = matches[1];
                }

                // Fetch specified user gist data
                github.gists.getFromUser({
                    user: username,
                    per_page: itemCount
                }, function onResult(error, result) {
                    if (error) {
                        channel.say('Oh noes, error - ' + JSON.stringify(error), from);
                    } else {
                        _.forEach(result, function iterator(gist) {
                            var templateVars = {
                                date: moment(gist.created_at < gist.updated_at ? gist.updated_at : gist.created_at).format(pluginConfig.moment.format),
                                description: gist.description || pluginConfig.gist.noDescription,
                                files: gist.files.length
                            };

                            shorturl(gist.html_url, function done(shortUrl) {
                                templateVars.url = shortUrl;

                                channel.say(_.template(pluginConfig.gist.message, templateVars));
                            });
                        });
                    }
                });
            },
            "^!ghOrgMembers(?: (\\S+))$": function onMatch(from, matches) {
                github.orgs.getMembers({
                    org: matches[1],
                    per_page: 300
                }, function onResult(error, result) {
                    if (error) {
                        channel.say('Oh noes, error - ' + JSON.stringify(error), from);
                    } else {
                        async.map(
                            result,
                            function iterator(member, callback) {
                                shorturl(member.html_url, function done(shortUrl) {
                                    callback(null, member.login + ' - ' + shortUrl);
                                });
                            },
                            function callback(error, members) {
                                if (!_.isEmpty(members)) {
                                    channel.say(members.join(', '));
                                }
                            }
                        );
                    }
                });
            },
            "^!ghRepos(?: (\\S+))(?: (\\d+))?$": function onMatch(from, matches) {
                github.repos.getFromUser({
                    user: matches[1],
                    type: 'owner'
                }, function onResult(error, result) {
                    _.each(result, function iterator(repo) {
                        repo._forks = -repo.forks_count;
                        repo._watchers = -repo.watchers_count;
                    });

                    var repoCount = matches[2] ? parseInt(matches[2], 10) : 3;

                    async.map(
                        _.sortBy(result, ['_forks', '_watchers', 'name']).splice(0, repoCount),
                        function iterator(repo, callback) {
                            shorturl(repo.html_url, function done(shortUrl) {
                                callback(null, repo.name + ' - ' + shortUrl);
                            });
                        },
                        function callback(error, repos) {
                            if (!_.isEmpty(repos)) {
                                channel.say(repos.join(', '));
                            }
                        }
                    );
                });
            }
        };
    };
};
<commit_msg>Refactored !ghRepos command.<commit_after>/**
 * Plugin dependencies.
 *
 * @type {exports}
 */
var GitHubApi = require('github');
var shorturl = require('shorturl');
var moment = require('moment');
var async = require('async');
var _ = require('lodash');

/**
 * URL log plugin for UniBot
 *
 * @param  {Object} options Plugin options object, description below.
 *   db: {mongoose} the mongodb connection
 *   bot: {irc} the irc bot
 *   web: {connect} a connect + connect-rest webserver
 *   config: {object} UniBot configuration
 *
 * @return  {Function}  Init function to access shared resources
 */
module.exports = function init(options) {
    var config = options.config || {};

    /**
     * Plugin configuration.
     *
     * @type    {{
     *              moment: {
     *                  locale: string,
     *                  format: string
     *              },
     *              gist: {
     *                  message: string,
     *                  noDescription: string
     *              }
     *          }}
     */
    var pluginConfig = {
        "moment": {
            "locale": "",
            "format": "DD.MM.YYYY HH:mm:ss"
        },
        "gist": {
            "message": "${url} - ${date} - ${description}",
            "noDescription": "No description"
        }
    };

    // Merge configuration for plugin
    if (_.isObject(config.plugins) && _.isObject(config.plugins.github)) {
        pluginConfig = _.merge(pluginConfig, config.plugins.github);
    }

    // Set moment locale, if it's set
    if (pluginConfig.moment.locale) {
        moment.locale(pluginConfig.moment.locale);
    }

    // Create GitHub API connection
    var github = new GitHubApi({
        version: '3.0.0'
    });

    return function plugin(channel) {
        return {
            "^!ghGist(?: (\\S+))?(?: (\\d+))?$": function onMatch(from, matches) {
                var username = from;
                var itemCount = 1;

                if (matches[2]) {
                    username = matches[1];
                    itemCount = matches[2];
                } else if (matches[1]) {
                    username = matches[1];
                }

                // Fetch specified user gist data
                github.gists.getFromUser({
                    user: username,
                    per_page: itemCount
                }, function onResult(error, result) {
                    if (error) {
                        channel.say('Oh noes, error - ' + JSON.stringify(error), from);
                    } else {
                        _.forEach(result, function iterator(gist) {
                            var templateVars = {
                                date: moment(gist.created_at < gist.updated_at ? gist.updated_at : gist.created_at).format(pluginConfig.moment.format),
                                description: gist.description || pluginConfig.gist.noDescription,
                                files: gist.files.length
                            };

                            shorturl(gist.html_url, function done(shortUrl) {
                                templateVars.url = shortUrl;

                                channel.say(_.template(pluginConfig.gist.message, templateVars));
                            });
                        });
                    }
                });
            },
            "^!ghOrgMembers(?: (\\S+))$": function onMatch(from, matches) {
                github.orgs.getMembers({
                    org: matches[1],
                    per_page: 300
                }, function onResult(error, result) {
                    if (error) {
                        channel.say('Oh noes, error - ' + JSON.stringify(error), from);
                    } else {
                        async.map(
                            result,
                            function iterator(member, callback) {
                                shorturl(member.html_url, function done(shortUrl) {
                                    callback(null, member.login + ' - ' + shortUrl);
                                });
                            },
                            function callback(error, members) {
                                if (!_.isEmpty(members)) {
                                    channel.say(members.join(', '));
                                }
                            }
                        );
                    }
                });
            },
            "^!ghRepos(?: (\\S+))?(?: (\\d+))?$": function onMatch(from, matches) {
                var username = from;
                var itemCount = 2;

                if (matches[2]) {
                    username = matches[1];
                    itemCount = matches[2];
                } else if (matches[1]) {
                    username = matches[1];
                }

                github.repos.getFromUser({
                    user: username,
                    type: 'owner'
                }, function onResult(error, result) {
                    _.each(result, function iterator(repo) {
                        repo._forks = -repo.forks_count;
                        repo._watchers = -repo.watchers_count;
                    });

                    async.map(
                        _.sortBy(result, ['_forks', '_watchers', 'name']).splice(0, itemCount),
                        function iterator(repo, callback) {
                            shorturl(repo.html_url, function done(shortUrl) {
                                callback(null, repo.name + ' - ' + shortUrl);
                            });
                        },
                        function callback(error, repos) {
                            if (!_.isEmpty(repos)) {
                                channel.say(repos.join(', '));
                            }
                        }
                    );
                });
            }
        };
    };
};
<|endoftext|>


<commit_before>var repl = require('repl');
var io = require('socket.io');

var randInt = (min, max) => {
  return Math.floor(Math.random() * (max - min)) + min;
};
class Player {
  constructor(server, id) {
    var config = server.config;
    this.id = id;
    this.clan = null;
    this.server = server;
  }
  update() {

  }
  link(socket) {
    this.socket = socket
    socket.on('error', err => {
      console.log(err);
      this.destroy();
    })
    socket.on('disconnect', () => this.destroy());
  }
  destroy() {
    this.server.remove(this.id);
    this.socket.disconnect();
  }
  spawn() {
    this.x = randInt(0, config.mapScale);
    this.y = randInt(0, config.mapScale);
    this.vx = 0;
    this.vy = 0;
  }
}
class Server {
  constructor(config) {
    this.config = config;
    this.players = Array(config.maxPlayers).fill(null);
    setInterval(() => this.update(), config.serverUpdateRate);
  }
  remove(sid) {
    this.players[sid] = null;
  }
  update() {
    for (var i of this.players) {
      if (i != null) {
        i.update();
      }
    }
  }
  handle(connection) {
    for (var i = 0; i < 50; i++) {
      if (this.players[i] == null) {
        this.players[i] = new Player(this, i).link(connection);
        break;
      }
    }
  }
}

var app = new Server({
  mapScale: 14400,
  maxPlayers: 50,
  serverUpdateRate: 9,
});

for (var i = 5000; i <= 5010; i++) {
  io(i).on('connection', socket => app.handle(socket));
}
/*
var teams = [];
var sockets = [];
  io(i).on('connection', function (socket) {
    var emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg);
        socket.emit(...arg);
      } catch (e) {
        sockets.forEach(a => a.emit(...arg));
      }
    };
    sockets.push(socket);
    socket.on('1', function (data) {
      var id = 27;
      var name = data.name.length > 15 ? 'unknown' : data.name;
      socket.emit('id', {
        "teams": teams
      });
      socket.emit('1', id);
      socket.emit('mm', 0);
      socket.emit('3', []);
      var x = randInt(0, config.mapScale);
      var y = randInt(0, config.mapScale);
      var userteam = null;
      var last = 0;
      socket.emit("2", ["a3Pm5dMzeKOjc5gvAJEF", id, name, x, 7200, 0, 100, 100, 35, data.skin], true);
      socket.emit("5", [27, data.name, 9001]); //[5,"RIP",31988,45,"KADEJO503",23404,34,"winter wolf",4821,28,"Godenot",4500,33,"Arena Closer",3000,32,"LightTheif",2940,6,"CarlosKoS-_-16",2800,4,"GD desconhecido",2635,35,"jack black GD",2357,19,"AMIGO BOM",1623])
      socket.emit("6", [
        29, 3115.1, 13592.9, 0, 109.2, 1, null, -1,
        353, 4103, 13436, 0, 80, 2, null, -1,
        339, 2498, 14155, 0, 90, 2, null, -1
      ]);
      socket.emit("8", 2.6, 28);
      socket.on("ch", data => {
        emit("ch", id, data);
      });
      socket.on("8", data => {
        console.log('CLAN CREATE REQUEST:', data);
        teams.push([{
          "sid": data,
          "owner": id
        }]);
        var userteam = data;
        emit("st", data, true);
      });
      socket.on("3", function (data) {
        if (data == null) {
          vx = vy = 0;
          return;
        } else if (x < 0 || x > config.mapScale || y < 0 || y > config.mapScale) {
          x = 7200;
          y = 7200;
        }
        if (y >= 6840 && y <= 7560) {
          x += 0.44;
        }
        var speed = y > 2400 ? 60 * 0.8 : 60;
        vx = Math.cos(data) * speed;
        vy = Math.sin(data) * speed;
        x += vx;
        y += vy;
        socket.emit('a');
        socket.emit("3", [id, x, y, -2.26, -1, 0, 0, null, 0, 0, 0, 0]);
      });
      socket.on("14", function (data) {
        console.log('ping!!!', arguments);
      });
    });
  });
}
*/
repl.start({
  eval: (a, _c, _f, cb) => {
    try {
      cb(null, eval(a)); // jshint ignore: line
    } catch (e) {
      cb(e);
    }
  }
});
<commit_msg>classes<commit_after>var repl = require('repl');
var io = require('socket.io');

var randInt = (min, max) => {
  return Math.floor(Math.random() * (max - min)) + min;
};
class Player {
  constructor(server, id) {
    this.config = server.config;
    this.id = id;
    this.clan = null;
    this.server = server;
    this.kill();
  }
  update(delta) {
    if (this.alive) {
      this.x += this.vx;
      this.y += this.vy;
      this.xv *= Math.pow(this.config.playerDecel, delta);
      this.yv *= Math.pow(this.config.playerDecel, delta);
    }
  }
  link(socket) {
    this.socket = socket;
    socket.once('error', err => {
      console.log(err);
      this.destroy();
    })
    socket.once('disconnect', () => this.destroy());
  }
  destroy() {
    this.kill();
    this.server.remove(this.id);
    this.socket.disconnect();
  }
  kill() {
    this.alive = false;
    this.x = 0;
    this.y = 0;
    this.slowDown();
  }
  slowDown() {
    this.vx = 0;
    this.vy = 0;
  }
  spawn() {
    this.alive = true;
    this.x = randInt(0, config.mapScale);
    this.y = randInt(0, config.mapScale);
    this.slowDown();
  }
}
class Server {
  constructor(config) {
    this.config = config;
    this.players = Array(config.maxPlayers).fill(null);
    this.lastRun = Date.now();
    setInterval(() => this.update(), config.serverUpdateRate);
  }
  remove(sid) {
    this.players[sid] = null;
  }
  update() {
    var now = Date.now();
    var delta = this.lastRun - now;
    this.lastRun = now;
    for (var i of this.players) {
      if (i != null) {
        i.update(delta);
      }
    }
  }
  handle(connection) {
    for (var i = 0; i < 50; i++) {
      if (this.players[i] == null) {
        this.players[i] = new Player(this, i).link(connection);
        break;
      }
    }
  }
}

var app = new Server({
  mapScale: 14400,
  maxPlayers: 50,
  serverUpdateRate: 9,
});

for (var i = 5000; i <= 5010; i++) {
  io(i).on('connection', socket => app.handle(socket));
}
/*
var teams = [];
var sockets = [];
  io(i).on('connection', function (socket) {
    var emit = (...arg) => {
      try {
        socket.broadcast.emit(...arg);
        socket.emit(...arg);
      } catch (e) {
        sockets.forEach(a => a.emit(...arg));
      }
    };
    sockets.push(socket);
    socket.on('1', function (data) {
      var id = 27;
      var name = data.name.length > 15 ? 'unknown' : data.name;
      socket.emit('id', {
        "teams": teams
      });
      socket.emit('1', id);
      socket.emit('mm', 0);
      socket.emit('3', []);
      var x = randInt(0, config.mapScale);
      var y = randInt(0, config.mapScale);
      var userteam = null;
      var last = 0;
      socket.emit("2", ["a3Pm5dMzeKOjc5gvAJEF", id, name, x, 7200, 0, 100, 100, 35, data.skin], true);
      socket.emit("5", [27, data.name, 9001]); //[5,"RIP",31988,45,"KADEJO503",23404,34,"winter wolf",4821,28,"Godenot",4500,33,"Arena Closer",3000,32,"LightTheif",2940,6,"CarlosKoS-_-16",2800,4,"GD desconhecido",2635,35,"jack black GD",2357,19,"AMIGO BOM",1623])
      socket.emit("6", [
        29, 3115.1, 13592.9, 0, 109.2, 1, null, -1,
        353, 4103, 13436, 0, 80, 2, null, -1,
        339, 2498, 14155, 0, 90, 2, null, -1
      ]);
      socket.emit("8", 2.6, 28);
      socket.on("ch", data => {
        emit("ch", id, data);
      });
      socket.on("8", data => {
        console.log('CLAN CREATE REQUEST:', data);
        teams.push([{
          "sid": data,
          "owner": id
        }]);
        var userteam = data;
        emit("st", data, true);
      });
      socket.on("3", function (data) {
        if (data == null) {
          vx = vy = 0;
          return;
        } else if (x < 0 || x > config.mapScale || y < 0 || y > config.mapScale) {
          x = 7200;
          y = 7200;
        }
        if (y >= 6840 && y <= 7560) {
          x += 0.44;
        }
        var speed = y > 2400 ? 60 * 0.8 : 60;
        vx = Math.cos(data) * speed;
        vy = Math.sin(data) * speed;
        x += vx;
        y += vy;
        socket.emit('a');
        socket.emit("3", [id, x, y, -2.26, -1, 0, 0, null, 0, 0, 0, 0]);
      });
      socket.on("14", function (data) {
        console.log('ping!!!', arguments);
      });
    });
  });
}
*/
repl.start({
  eval: (a, _c, _f, cb) => {
    try {
      cb(null, eval(a)); // jshint ignore: line
    } catch (e) {
      cb(e);
    }
  }
});
<|endoftext|>


<commit_before>var app = require('express')();
var archiver = require('archiver');
var config = require('./config.json');
var fs = require('fs');
var request = require('request');
var p = require('path');

var domain = function(res, hash) {
  if (config[hash]) {
    return config[hash];
  } else {
    res.status(404).end();
  }
}

var archive = function(res, domain) {
  var archive = archiver('zip');

  archive.on('error', function(err) {
    console.log('error in archive:\n\n' + err);
    res.status(500).send({error: err.message});
  });

  //set the archive name
  res.attachment('IndieHosted.zip');

  //this is the streaming magic
  archive.pipe(res);
  archive.directory("/data/domains/" + domain, domain);
  archive.finalize();
}

app.get('/:type(download|migrate)/:hash', function(req, res) {
  if (req.params.type === 'download') {
    archive(res, domain(res, req.params.hash));
  } else if (req.params.type === 'migrate') {
    request('http://172.17.0.1:8080/' + req.params.hash, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        archive(res, domain(res, req.params.hash));
      } else {
        res.status(500).send({ error: 'Migration failed.' });
      }
    })
  }
});

app.listen(3000);
<commit_msg>use the right docker gateway<commit_after>var app = require('express')();
var archiver = require('archiver');
var config = require('./config.json');
var fs = require('fs');
var request = require('request');
var p = require('path');

var domain = function(res, hash) {
  if (config[hash]) {
    return config[hash];
  } else {
    res.status(404).end();
  }
}

var archive = function(res, domain) {
  var archive = archiver('zip');

  archive.on('error', function(err) {
    console.log('error in archive:\n\n' + err);
    res.status(500).send({error: err.message});
  });

  //set the archive name
  res.attachment('IndieHosted.zip');

  //this is the streaming magic
  archive.pipe(res);
  archive.directory("/data/domains/" + domain, domain);
  archive.finalize();
}

app.get('/:type(download|migrate)/:hash', function(req, res) {
  if (req.params.type === 'download') {
    archive(res, domain(res, req.params.hash));
  } else if (req.params.type === 'migrate') {
    request('http://172.17.42.1:8080/' + req.params.hash, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        archive(res, domain(res, req.params.hash));
      } else {
        res.status(500).send({ error: 'Migration failed.' });
      }
    })
  }
});

app.listen(3000);
<|endoftext|>


<commit_before>'use strict';

var util = require('./lib/util');

exports = module.exports = Parth;

function Parth(o){
  o = o || {};
  if(this instanceof Parth){
    this.store = {children: {}};
    this.regex = [];
    this.regex.master = /(?:[])/;
    return this;
  }

  return new Parth(o);
}

// ## parth.add(path)
// > path to regex classification
// > TODO: regexp input
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// returns
//  - null for non-supported types
//  - regular expression from the path
//
var paramRE = /(^|\W)\:([^(?#/.: ]+)(\([^)]*?\)+)?/g;

Parth.prototype.add = function(path, o){
  if(typeof path !== 'string'){ return null; }

  o = util.boil(path, o);
  if(this.store.children[o.path]){
    return this.store.children[o.path].regex;
  }

  var sep, def = 0, parsed = '^' +
    o.path.replace(/\S+/g, function(stem){
      sep = (stem.match(/\//) || stem.match(/\./) || ' ')[0].trim();
      return stem.replace(paramRE, function($0, $1, $2, $3){
        if(!$3){ def++; }
        return $1 + ($3 || '([^'+sep+' ]+)');
      });
      // now escape separation tokens outside parens
    }).replace(/(.*?)(?:\(.+?\)+|$)/g, function($0, $1){
      return $0.replace($1, util.escapeRegExp);
    });

  parsed = new RegExp(parsed);
  // attach some metadata before pushing
  parsed.depth = util.boil.argv(o.path).length;
  parsed.path = o.path;
  parsed.cus = (o.path.match(/\(.*?\)+/g) || []).length;
  parsed.def = def;

  this.regex.push(parsed);

  // ## sum up all learned
  // - raw paths (no params) go first
  // - custom regexes before defaults

  this.regex.sort(function(x, y){
    var depthDiff = y.depth - x.depth;
    if(depthDiff){ return depthDiff; }
    return (
      x.def + x.cus - y.def - y.cus
       || (y.source.length*(y.cus + 1) - x.source.length*(x.cus + 1))
    );
  });

  // ## make a giant regex for everything
  // - void groups all groups
  // - make one regex per depth
  // - make a giant regex for everything

  this.regex.master = new RegExp(
    '(' + this.regex.map(util.voidRE).join(')|(') + ')'
  );

  this.store.children[o.path] = o;
  util.defineProperty(o, 'regex', '', parsed);
  o.depth = parsed.depth;

  return parsed;
};

// ## parth.match(path[, options])
// > take a string or array, return the matching path
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// return
//  - null for non-supported types or not matching path
//  - regex with for the matching path
//
Parth.prototype.match = function(path, o){
  if(typeof path !== 'string'){ return null; }

  o = o || {}; o.notFound = true; util.boil(path, o);
  var found = this.regex.master.exec(o.path);
  if(!found){ return null; }

  o.match = found.shift();
  var regex = this.regex[found.indexOf(o.match)];
  o.params = {_: o.path.match(regex).slice(1)};

  var index = -1;
  regex.path.replace(paramRE, function($0, $1, $2){
    o.params[$2] = o.params._[++index];
    o.params._[index] = $2;
  });

  o.notFound = o.path.replace(o.match, '') || false;
  return regex;
};
<commit_msg>- make all checks in boil - parth.store.children should be non enumerable so it avoids deep cloning by accident - give depth in parth.match - got rid of options argument in constructor<commit_after>'use strict';

var util = require('./lib/util');

exports = module.exports = Parth;

function Parth(){
  if(this instanceof Parth){
    this.regex = [];
    this.regex.master = /(?:[])/;
    this.store = {};
    util.defineProperty(this.store, 'children', '', {});
    return this;
  }
  return new Parth();
}

// ## parth.add(path)
// > path to regex classification
// > TODO: give support for regexp input
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// returns
//  - null for non-supported types
//  - regular expression from the path
//
var paramRE = /(^|\W)\:([^(?#/.: ]+)(\([^)]*?\)+)?/g;

Parth.prototype.add = function(path, o){
  o = util.boil(path, o); if(!o){ return null; }

  if(this.store.children[o.path]){
    return this.store.children[o.path].regex;
  }

  var sep, def = 0, parsed = '^' +
    o.path.replace(/\S+/g, function(stem){
      sep = (stem.match(/\//) || stem.match(/\./) || ' ')[0].trim();
      return stem.replace(paramRE, function($0, $1, $2, $3){
        if(!$3){ def++; }
        return $1 + ($3 || '([^'+sep+' ]+)');
      });
      // now escape separation tokens outside parens
    }).replace(/(.*?)(?:\(.+?\)+|$)/g, function($0, $1){
      return $0.replace($1, util.escapeRegExp);
    });

  parsed = new RegExp(parsed);
  // attach some metadata before pushing
  parsed.depth = util.boil.argv(o.path).length;
  parsed.path = o.path;
  parsed.cus = (o.path.match(/\(.*?\)+/g) || []).length;
  parsed.def = def;

  this.regex.push(parsed);

  // ## sum up all learned
  // - raw paths (no params) go first
  // - custom regexes before defaults

  this.regex.sort(function(x, y){
    var depthDiff = y.depth - x.depth;
    if(depthDiff){ return depthDiff; }
    return (
      x.def + x.cus - y.def - y.cus
       || (y.source.length*(y.cus + 1) - x.source.length*(x.cus + 1))
    );
  });

  // ## make a giant regex for everything
  // - void groups all groups
  // - make one regex per depth
  // - make a giant regex for everything

  this.regex.master = new RegExp(
    '(' + this.regex.map(util.voidRE).join(')|(') + ')'
  );

  this.store.children[o.path] = o;
  util.defineProperty(o, 'regex', '', parsed);
  o.depth = parsed.depth;

  return parsed;
};

// ## parth.match(path[, options])
// > take a string or array, return the matching path
//
// arguments
//  - path, type `string`
//  - options, type `object` optional holding all extra information
//
// return
//  - null for non-supported types or not matching path
//  - regex with for the matching path
//
Parth.prototype.match = function(path, o){
  o = util.boil(path, o); if(!o){ return null; }

  o.notFound = true;
  var found = this.regex.master.exec(o.path);
  if(!found){ return null; }

  o.match = found.shift();
  var regex = this.regex[found.indexOf(o.match)];
  o.depth = regex.depth;
  o.params = {_: o.path.match(regex).slice(1)};

  var index = -1;
  regex.path.replace(paramRE, function($0, $1, $2){
    o.params[$2] = o.params._[++index];
    o.params._[index] = $2;
  });

  o.notFound = o.path.replace(o.match, '') || false;
  return regex;
};
<|endoftext|>


<commit_before>#! /usr/bin/env node
var finalizer = require('commander');
var client = require('./lib/client');

finalizer
    .command('create <name>')
    .description('Create a new project.')
    .action(function(name) {
        console.log('Attempting to create project "' + name + '"');
        client.create(name, function(err, body) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(body);
        });
    });

finalizer
    .command('build <name>')
    .description('Run a new project build.')
    .action(function(name) {
        console.log('Attempting to create a new build for "' + name + '"');
        client.build(name, function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('download <name>')
    .description('Download the latest project build.')
    .action(function(name) {
        console.log('Trying to download the latest build for "' + name + '"');
        client.download(name, function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('init')
    .description('Generate a basic finalizer.json file.')
    .action(function() {
        client.init(function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('check')
    .description('Check if connection to the build server is successful.')
    .action(function() {
        client.check(function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer.version('0.1.2');
finalizer.parse(process.argv);
<commit_msg>Bump version.<commit_after>#! /usr/bin/env node
var finalizer = require('commander');
var client = require('./lib/client');

finalizer
    .command('create <name>')
    .description('Create a new project.')
    .action(function(name) {
        console.log('Attempting to create project "' + name + '"');
        client.create(name, function(err, body) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(body);
        });
    });

finalizer
    .command('build <name>')
    .description('Run a new project build.')
    .action(function(name) {
        console.log('Attempting to create a new build for "' + name + '"');
        client.build(name, function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('download <name>')
    .description('Download the latest project build.')
    .action(function(name) {
        console.log('Trying to download the latest build for "' + name + '"');
        client.download(name, function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('init')
    .description('Generate a basic finalizer.json file.')
    .action(function() {
        client.init(function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer
    .command('check')
    .description('Check if connection to the build server is successful.')
    .action(function() {
        client.check(function(err, msg) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(msg);
        });
    });

finalizer.version('0.1.3');
finalizer.parse(process.argv);
<|endoftext|>


<commit_before>#!/usr/bin/env node
require('shelljs/global');

// Creates a changelog for the current build and puts it in the root
// Commits the changelog if it updated
// Does not push commit

function parseGitUri(uri) {
  return uri.match(/https:..github.com\/([^./]+)\/([^./]+).*/) ||
    uri.match(/git@github.com:(.*)\/(.*)\.git/);
}

function verifyChangelog() {
  var diff = exec('git diff HEAD CHANGELOG.md').split('\n');
  var changelog = cat('CHANGELOG.md').split('\n');
  if (changelog[changelog.length - 1] === '') changelog.pop();
  var isOneLine = (changelog.length === 1);
  var deletions = diff.filter(/^-/.test).length;
  var containsErrorMessage = false;
  diff.forEach(function (line) {
    if (line.indexOf('Make a POST first') >= 0) containsErrorMessage = true;
  });
  if (isOneLine) {
    revertChanges();
    console.error('Changelog diff should be more than 1 line long');
    process.exit(3);
  }
  if (deletions > 10) {
    revertChanges();
    console.error('Too many deletions (-' + deletions + '), verify that the changes to CHANGELOG.md are correct');
    process.exit(4);
  }
  if (containsErrorMessage) {
    revertChanges();
    console.error('Changelog contains an error message');
    process.exit(5);
  }
}

function revertChanges() {
  exec('git checkout -- .');
}

function run() {
  echo('...generating changelog (be patient)');
  config.silent = true;
  var urls = exec('git remote show -n origin')
      .grep('Push');
  if (!urls) {
    console.error('Unable to find any URLs you can push to');
    process.exit(1);
  }
  var repoInfo = parseGitUri(urls);
  if (!repoInfo) {
    console.error('Unable to parse your git URL');
    process.exit(2);
  }
  var url = 'github-changelog-api.herokuapp.com/' + repoInfo[1] + '/' + repoInfo[2];
  exec('curl -X POST -s "' + url + '"');
  var newLog;
  do {
    exec('sleep 1');
    newLog = exec('curl "' + url + '"');
  } while (newLog.match(/^Working, try again.*/));
  // Now that the contents are valid, we can write this out to disk
  newLog.to('CHANGELOG.md');

  var changelog_was_updated = false;
  exec('git ls-files --exclude-standard --modified --others').split('\n').forEach(function (file) {
    if (file === 'CHANGELOG.md') changelog_was_updated = true;
  });

  if (changelog_was_updated) {
    echo('...verifying changelog');
    verifyChangelog();
    echo('...committing updated changelog');
    var current_user = exec('git config user.name').trimRight();
    config.silent = false;
    exec('git add CHANGELOG.md');
    exec('git commit -m "docs(changelog): updated by ' + current_user + ' [ci skip]"');
    echo('Done.  You can now \'git push\' the updated changelog.');
  } else {
    echo('CHANGELOG.md already up-to-date.');
  }
}

run();
<commit_msg>Shorten variable name<commit_after>#!/usr/bin/env node
require('shelljs/global');

// Creates a changelog for the current build and puts it in the root
// Commits the changelog if it updated
// Does not push commit

function parseGitUri(uri) {
  return uri.match(/https:..github.com\/([^./]+)\/([^./]+).*/) ||
    uri.match(/git@github.com:(.*)\/(.*)\.git/);
}

function verifyChangelog() {
  var diff = exec('git diff HEAD CHANGELOG.md').split('\n');
  var changelog = cat('CHANGELOG.md').split('\n');
  if (changelog[changelog.length - 1] === '') changelog.pop();
  var isOneLine = (changelog.length === 1);
  var deletions = diff.filter(/^-/.test).length;
  var containsError = false;
  diff.forEach(function (line) {
    if (line.indexOf('Make a POST first') >= 0) containsError = true;
  });
  if (isOneLine) {
    revertChanges();
    console.error('Changelog diff should be more than 1 line long');
    process.exit(3);
  }
  if (deletions > 10) {
    revertChanges();
    console.error('Too many deletions (-' + deletions + '), verify that the changes to CHANGELOG.md are correct');
    process.exit(4);
  }
  if (containsError) {
    revertChanges();
    console.error('Changelog contains an error message');
    process.exit(5);
  }
}

function revertChanges() {
  exec('git checkout -- .');
}

function run() {
  echo('...generating changelog (be patient)');
  config.silent = true;
  var urls = exec('git remote show -n origin')
      .grep('Push');
  if (!urls) {
    console.error('Unable to find any URLs you can push to');
    process.exit(1);
  }
  var repoInfo = parseGitUri(urls);
  if (!repoInfo) {
    console.error('Unable to parse your git URL');
    process.exit(2);
  }
  var url = 'github-changelog-api.herokuapp.com/' + repoInfo[1] + '/' + repoInfo[2];
  exec('curl -X POST -s "' + url + '"');
  var newLog;
  do {
    exec('sleep 1');
    newLog = exec('curl "' + url + '"');
  } while (newLog.match(/^Working, try again.*/));
  // Now that the contents are valid, we can write this out to disk
  newLog.to('CHANGELOG.md');

  var changelog_was_updated = false;
  exec('git ls-files --exclude-standard --modified --others').split('\n').forEach(function (file) {
    if (file === 'CHANGELOG.md') changelog_was_updated = true;
  });

  if (changelog_was_updated) {
    echo('...verifying changelog');
    verifyChangelog();
    echo('...committing updated changelog');
    var current_user = exec('git config user.name').trimRight();
    config.silent = false;
    exec('git add CHANGELOG.md');
    exec('git commit -m "docs(changelog): updated by ' + current_user + ' [ci skip]"');
    echo('Done.  You can now \'git push\' the updated changelog.');
  } else {
    echo('CHANGELOG.md already up-to-date.');
  }
}

run();
<|endoftext|>


<commit_before>var Promise = require('rsvp').Promise;

var System = require('systemjs');
var fs = require('fs');

var asp = require('rsvp').denodeify;

var es6Compiler = require('./compilers/es6');
var registerCompiler = require('./compilers/register');
var amdCompiler = require('./compilers/amd');
var cjsCompiler = require('./compilers/cjs');
var globalCompiler = require('./compilers/global');
var builder = require('./lib/builder');

var path = require('path');

/* Very basic, null-friendly, shallow clone for object attributes only */
function clone(obj) {
  obj = obj || {};
  var copy = {};
  for (var key in obj) {
    copy[key] = obj[key];
  }
  return copy;
}

function Builder(cfg) {
  this.System = System;
  this.loader = null;
  this.reset();
  if (typeof cfg == "string")
    this.loadConfigSync(cfg);
  else if (typeof cfg == "object")
    this.config(cfg);
}

Builder.prototype.reset = function() {
  var loader = this.loader = new Loader(System);
  loader.baseURL = System.baseURL;
  loader.paths = { '*': '*.js' };
  loader.config = System.config;

  var pluginLoader = new Loader(System);
  pluginLoader.baseURL = System.baseURL;
  pluginLoader.paths = { '*': '*.js' };
  pluginLoader.config = System.config;
  pluginLoader.trace = true;
  pluginLoader.import = loader.import = System.import;

  pluginLoader._nodeRequire = loader._nodeRequire = require;

  loader.trace = true;
  loader.execute = false;
  loader.pluginLoader = pluginLoader;

  loader.set('@empty', loader.newModule({}));
  pluginLoader.set('@empty', loader.newModule({}));

  amdCompiler.attach(loader);
  amdCompiler.attach(pluginLoader);
};

Builder.prototype.build = function(moduleName, outFile, opts) {
  var self = this;
  opts = opts || {};

  return this.trace(moduleName, opts.config)
  .then(function(trace) {
    return self.buildTree(trace.tree, outFile, opts);
  });
};

var operatorFunctions = {
  '+': builder.addTrees,
  '-': builder.subtractTrees
};

Builder.buildExpression = function(firstModule, operations, cfg) {
  builder = new Builder();

  return Promise.resolve(builder.trace(firstModule, cfg))
  .then(function(trace) {
    // if there are no other operations, then we have the final tree
    if (!operations.length)
      return trace.tree;

    var applyOperation = function(promise, op) {
      promise.then(function(curTree) {
        return builder.trace(op.moduleName);
      })
      .then(function(nextTrace) {
        var operatorFunction = operatorFunction[op.operator];
        if (!operatorFunction)
          throw 'Unknown operator ' + op.operator;
        return operatorFunction(curTree, nextTrace.tree);
      });
    };

    // chain the operations, applying them with the trace of the next module
    return operations.reduce(applyOperation, Promise.resolve(trace.tree));
  });
};

var compilerMap = {
  'amd':      amdCompiler,
  'cjs':      cjsCompiler,
  'es6':      es6Compiler,
  'global':   globalCompiler,
  'register': registerCompiler
};

function compileLoad(loader, load, opts, compilers) {
  return Promise.resolve()
  .then(function() {
    // note which compilers we used
    compilers = compilers || {};
    var format = load.metadata.format;
    if (load.metadata.build === false) {
      return {};
    }
    else if (format in compilerMap) {
      compilers[format] = true;
      return compilerMap[format].compile(load, opts, loader);
    }
    else if (format == 'defined') {
      return {source: ''};
    }
    else {
      throw "unknown format " + format;
    }
  });
}

function buildOutputs(loader, tree, opts, sfxCompilers) {
  var names = Object.keys(tree);
  // store plugins with a bundle hook to allow post-processing
  var plugins = {};
  var outputs = [];

  return Promise.all(names.map(function(name) {
    var load = tree[name];

    if (sfxCompilers && load.metadata.plugin && (load.metadata.build === false || load.metadata.plugin.build === false))
      outputs.push('System.register("' + load.name + '", [], false, function() { console.log("SystemJS Builder - Plugin for ' + load.name + ' does not support sfx builds"); });\n');

    // support plugin "bundle" reduction hook
    var plugin = load.metadata.plugin;
    if (plugin && load.metadata.build !== false) {
      var entry = plugins[load.metadata.pluginName] = plugins[load.metadata.pluginName] || {
        loads: [],
        bundle: plugin.bundle
      };
      entry.loads.push(load);
    }

    return Promise.resolve(compileLoad(loader, load, opts, sfxCompilers))
    .then(outputs.push.bind(outputs));
  }))
  .then(function() {
    // apply plugin "bundle" hook
    return Promise.all(Object.keys(plugins).map(function(pluginName) {
      var entry = plugins[pluginName];
      if (entry.bundle)
      return Promise.resolve(entry.bundle.call(loader.pluginLoader, entry.loads, opts))
      .then(outputs.push.bind(outputs));
    }));
  })
  .then(function() {
    return outputs;
  });
}

Builder.prototype.buildTree = function(tree, outFile, opts) {
  var loader = this.loader;

  opts = clone(opts);
  opts.outFile = outFile;

  return buildOutputs(loader, tree, opts, false)
  .then(function(outputs) {
    outputs.unshift('"format register";\n');
    return builder.writeOutput(opts, outputs, loader.baseURL);
  });
};

Builder.prototype.buildSFX = function(moduleName, outFile, opts) {
  var loader = this.loader;

  opts = clone(opts);
  opts.outFile = outFile;

  var config = opts.config;

  var outputs;

  var compilers = {};
  opts.normalize = true;
  return this.trace(moduleName, config)
  .then(function(trace) {
    moduleName = trace.moduleName;
    return buildOutputs(loader, trace.tree, opts, compilers);
  })
  .then(function(_outputs) {
    outputs = _outputs;
  })
  // next add sfx headers for formats at the beginning
  .then(function() {
    Object.keys(compilers).forEach(function(format) {
      compiler = compilerMap[format];
      if (compiler.sfx)  {
        var sfx = compiler.sfx(loader);
        if (sfx) outputs.push(sfx);
      }
    });
  })
  // next wrap with the core code
  .then(function() {
    return asp(fs.readFile)(path.resolve(__dirname, './sfx/sfx-core.js'));
  })
  .then(function(sfxcore) {
    outputs.unshift("('" + moduleName + "', function(System) {\n");
    outputs.unshift(sfxcore.toString());
  })
  .then(function() {
    outputs.push("});");
  })
  .then(function() {
    return builder.writeOutput(opts, outputs, loader.baseURL);
  });
};

function executeConfigFile(loader, source) {
  var curSystem = global.System;
  global.System = {
    config: function(cfg) {
      loader.config(cfg);
      loader.pluginLoader.config(cfg);
    }
  };
  // jshint evil:true
  new Function(source.toString()).call(global);
  global.System = curSystem;
}

var resolvePath = path.resolve.bind(path, process.cwd());

Builder.prototype.loadConfig = function(configFile) {
  var self = this;
  return asp(fs.readFile)(resolvePath(configFile))
    .then(executeConfigFile.bind(null, this.loader))
    .then(function() { return self; });
};

Builder.prototype.loadConfigSync = function(configFile) {
  var source = fs.readFileSync(resolvePath(configFile));
  executeConfigFile(this.loader, source);
};

Builder.prototype.config = function(config) {
  var loader = this.loader;
  var pluginLoader = loader.pluginLoader;

  var cfg = {};
  for (var p in config) {
    if (p != 'bundles')
      cfg[p] = config[p];
  }
  loader.config(cfg);
  pluginLoader.config(cfg);
};

// returns a new tree containing tree1 n tree2
Builder.prototype.intersectTrees = function(tree1, tree2) {
  var name;
  var intersectTree = {};

  var tree1Names = [];
  for (name in tree1)
    tree1Names.push(name);

  for (name in tree2) {
    if (tree1Names.indexOf(name) == -1)
      continue;

    intersectTree[name] = tree1[name];
  }

  return intersectTree;
};

// returns a new tree containing tree1 + tree2
Builder.prototype.addTrees = function(tree1, tree2) {
  var name;
  var unionTree = {};

  for (name in tree2)
    unionTree[name] = tree2[name];

  for (name in tree1)
    unionTree[name] = tree1[name];

  return unionTree;
};

// returns a new tree containing tree1 - tree2
Builder.prototype.subtractTrees = function(tree1, tree2) {
  var name;
  var subtractTree = {};

  for (name in tree1)
    subtractTree[name] = tree1[name];

  for (name in tree2)
    delete subtractTree[name];

  return subtractTree;
};

// copies a subtree out of the tree
Builder.prototype.extractTree = function(tree, moduleName) {
  var outTree = {};
  return visitTree(tree, moduleName, null, function(load) {
    outTree[load.name] = load;
  })
  .then(function() {
    return outTree;
  });
};

Builder.prototype.trace = function(moduleName, config, includePlugins) {
  var loader = this.loader;
  var pluginLoader = loader.pluginLoader;

  if (config) {
    this.config(config);
  }

  var System = loader.global.System;
  loader.global.System = loader;

  var traceTree = {};

  return loader.import(moduleName)
  .then(function() {
    return loader.normalize(moduleName);
  })
  .then(function(_moduleName) {
    moduleName = _moduleName;
    loader.global.System = System;
    return visitTree(loader.loads, moduleName, includePlugins && pluginLoader, function(load) {
      traceTree[load.name] = load;
    });
  })
  .then(function() {
    return {
      moduleName: moduleName,
      tree: traceTree
    };
  })
  .catch(function(e) {
    loader.global.System = System;
    throw e;
  });
};

function visitTree(tree, moduleName, pluginLoader, visit, seen) {
  seen = seen || [];

  if (seen.indexOf(moduleName) != -1)
    return;

  seen.push(moduleName);

  var load = tree[moduleName];

  if (!load)
    return Promise.resolve();

  // visit the deps first
  return Promise.all(load.deps.map(function(dep) {
    return visitTree(tree, load.depMap[dep], pluginLoader, visit, seen);
  })).then(function() {
    if (!pluginLoader)
      return;

    var pluginName = load.metadata.pluginName;
    if (pluginName) {
      return visitTree(pluginLoader.loads, pluginName, pluginLoader, visit, seen);
    }
  })
  .then(function() {
    // if we are the bottom of the tree, visit
    return visit(load);
  });
}

Builder.legacy = new Builder();

module.exports = Builder;
<commit_msg>From simplified to correct<commit_after>var Promise = require('rsvp').Promise;

var System = require('systemjs');
var fs = require('fs');

var asp = require('rsvp').denodeify;

var es6Compiler = require('./compilers/es6');
var registerCompiler = require('./compilers/register');
var amdCompiler = require('./compilers/amd');
var cjsCompiler = require('./compilers/cjs');
var globalCompiler = require('./compilers/global');
var builder = require('./lib/builder');

var path = require('path');

/* Very basic, null-friendly, shallow clone for object attributes only */
function clone(obj) {
  obj = obj || {};
  var copy = {};
  for (var key in obj) {
    copy[key] = obj[key];
  }
  return copy;
}

function Builder(cfg) {
  this.System = System;
  this.loader = null;
  this.reset();
  if (typeof cfg == "string")
    this.loadConfigSync(cfg);
  else if (typeof cfg == "object")
    this.config(cfg);
}

Builder.prototype.reset = function() {
  var loader = this.loader = new Loader(System);
  loader.baseURL = System.baseURL;
  loader.paths = { '*': '*.js' };
  loader.config = System.config;

  var pluginLoader = new Loader(System);
  pluginLoader.baseURL = System.baseURL;
  pluginLoader.paths = { '*': '*.js' };
  pluginLoader.config = System.config;
  pluginLoader.trace = true;
  pluginLoader.import = loader.import = System.import;

  pluginLoader._nodeRequire = loader._nodeRequire = require;

  loader.trace = true;
  loader.execute = false;
  loader.pluginLoader = pluginLoader;

  loader.set('@empty', loader.newModule({}));
  pluginLoader.set('@empty', loader.newModule({}));

  amdCompiler.attach(loader);
  amdCompiler.attach(pluginLoader);
};

Builder.prototype.build = function(moduleName, outFile, opts) {
  var self = this;
  opts = opts || {};

  return this.trace(moduleName, opts.config)
  .then(function(trace) {
    return self.buildTree(trace.tree, outFile, opts);
  });
};

Builder.prototype.lookupOperatorFn = function(symbol) {
  if (symbol == '+')
    return this.addTrees;
  else if (symbol == '-')
    return this.subtractTrees;
  else
    throw 'Unknown operator ' + op.operator;
};

Builder.buildExpression = function(firstModule, operations, cfg) {
  builder = new Builder();

  return Promise.resolve(builder.trace(firstModule, cfg))
  .then(function(trace) {
    // if there are no other operations, then we have the final tree
    if (!operations.length)
      return trace.tree;

    var applyOperation = function(promise, op) {
      return promise.then(function(curTree) {
        return builder.trace(op.moduleName)
        .then(function(nextTrace) {
          var operatorFn = builder.lookupOperatorFn(op.operator);
          return operatorFn.call(builder, curTree, nextTrace.tree);
        });
      });
    };

    // chain the operations, applying them with the trace of the next module
    return operations.reduce(applyOperation, Promise.resolve(trace.tree));
  });
};

var compilerMap = {
  'amd':      amdCompiler,
  'cjs':      cjsCompiler,
  'es6':      es6Compiler,
  'global':   globalCompiler,
  'register': registerCompiler
};

function compileLoad(loader, load, opts, compilers) {
  return Promise.resolve()
  .then(function() {
    // note which compilers we used
    compilers = compilers || {};
    var format = load.metadata.format;
    if (load.metadata.build === false) {
      return {};
    }
    else if (format in compilerMap) {
      compilers[format] = true;
      return compilerMap[format].compile(load, opts, loader);
    }
    else if (format == 'defined') {
      return {source: ''};
    }
    else {
      throw "unknown format " + format;
    }
  });
}

function buildOutputs(loader, tree, opts, sfxCompilers) {
  var names = Object.keys(tree);
  // store plugins with a bundle hook to allow post-processing
  var plugins = {};
  var outputs = [];

  return Promise.all(names.map(function(name) {
    var load = tree[name];

    if (sfxCompilers && load.metadata.plugin && (load.metadata.build === false || load.metadata.plugin.build === false))
      outputs.push('System.register("' + load.name + '", [], false, function() { console.log("SystemJS Builder - Plugin for ' + load.name + ' does not support sfx builds"); });\n');

    // support plugin "bundle" reduction hook
    var plugin = load.metadata.plugin;
    if (plugin && load.metadata.build !== false) {
      var entry = plugins[load.metadata.pluginName] = plugins[load.metadata.pluginName] || {
        loads: [],
        bundle: plugin.bundle
      };
      entry.loads.push(load);
    }

    return Promise.resolve(compileLoad(loader, load, opts, sfxCompilers))
    .then(outputs.push.bind(outputs));
  }))
  .then(function() {
    // apply plugin "bundle" hook
    return Promise.all(Object.keys(plugins).map(function(pluginName) {
      var entry = plugins[pluginName];
      if (entry.bundle)
      return Promise.resolve(entry.bundle.call(loader.pluginLoader, entry.loads, opts))
      .then(outputs.push.bind(outputs));
    }));
  })
  .then(function() {
    return outputs;
  });
}

Builder.prototype.buildTree = function(tree, outFile, opts) {
  var loader = this.loader;

  opts = clone(opts);
  opts.outFile = outFile;

  return buildOutputs(loader, tree, opts, false)
  .then(function(outputs) {
    outputs.unshift('"format register";\n');
    return builder.writeOutput(opts, outputs, loader.baseURL);
  });
};

Builder.prototype.buildSFX = function(moduleName, outFile, opts) {
  var loader = this.loader;

  opts = clone(opts);
  opts.outFile = outFile;

  var config = opts.config;

  var outputs;

  var compilers = {};
  opts.normalize = true;
  return this.trace(moduleName, config)
  .then(function(trace) {
    moduleName = trace.moduleName;
    return buildOutputs(loader, trace.tree, opts, compilers);
  })
  .then(function(_outputs) {
    outputs = _outputs;
  })
  // next add sfx headers for formats at the beginning
  .then(function() {
    Object.keys(compilers).forEach(function(format) {
      compiler = compilerMap[format];
      if (compiler.sfx)  {
        var sfx = compiler.sfx(loader);
        if (sfx) outputs.push(sfx);
      }
    });
  })
  // next wrap with the core code
  .then(function() {
    return asp(fs.readFile)(path.resolve(__dirname, './sfx/sfx-core.js'));
  })
  .then(function(sfxcore) {
    outputs.unshift("('" + moduleName + "', function(System) {\n");
    outputs.unshift(sfxcore.toString());
  })
  .then(function() {
    outputs.push("});");
  })
  .then(function() {
    return builder.writeOutput(opts, outputs, loader.baseURL);
  });
};

function executeConfigFile(loader, source) {
  var curSystem = global.System;
  global.System = {
    config: function(cfg) {
      loader.config(cfg);
      loader.pluginLoader.config(cfg);
    }
  };
  // jshint evil:true
  new Function(source.toString()).call(global);
  global.System = curSystem;
}

var resolvePath = path.resolve.bind(path, process.cwd());

Builder.prototype.loadConfig = function(configFile) {
  var self = this;
  return asp(fs.readFile)(resolvePath(configFile))
    .then(executeConfigFile.bind(null, this.loader))
    .then(function() { return self; });
};

Builder.prototype.loadConfigSync = function(configFile) {
  var source = fs.readFileSync(resolvePath(configFile));
  executeConfigFile(this.loader, source);
};

Builder.prototype.config = function(config) {
  var loader = this.loader;
  var pluginLoader = loader.pluginLoader;

  var cfg = {};
  for (var p in config) {
    if (p != 'bundles')
      cfg[p] = config[p];
  }
  loader.config(cfg);
  pluginLoader.config(cfg);
};

// returns a new tree containing tree1 n tree2
Builder.prototype.intersectTrees = function(tree1, tree2) {
  var name;
  var intersectTree = {};

  var tree1Names = [];
  for (name in tree1)
    tree1Names.push(name);

  for (name in tree2) {
    if (tree1Names.indexOf(name) == -1)
      continue;

    intersectTree[name] = tree1[name];
  }

  return intersectTree;
};

// returns a new tree containing tree1 + tree2
Builder.prototype.addTrees = function(tree1, tree2) {
  var name;
  var unionTree = {};

  for (name in tree2)
    unionTree[name] = tree2[name];

  for (name in tree1)
    unionTree[name] = tree1[name];

  return unionTree;
};

// returns a new tree containing tree1 - tree2
Builder.prototype.subtractTrees = function(tree1, tree2) {
  var name;
  var subtractTree = {};

  for (name in tree1)
    subtractTree[name] = tree1[name];

  for (name in tree2)
    delete subtractTree[name];

  return subtractTree;
};

// copies a subtree out of the tree
Builder.prototype.extractTree = function(tree, moduleName) {
  var outTree = {};
  return visitTree(tree, moduleName, null, function(load) {
    outTree[load.name] = load;
  })
  .then(function() {
    return outTree;
  });
};

Builder.prototype.trace = function(moduleName, config, includePlugins) {
  var loader = this.loader;
  var pluginLoader = loader.pluginLoader;

  if (config) {
    this.config(config);
  }

  var System = loader.global.System;
  loader.global.System = loader;

  var traceTree = {};

  return loader.import(moduleName)
  .then(function() {
    return loader.normalize(moduleName);
  })
  .then(function(_moduleName) {
    moduleName = _moduleName;
    loader.global.System = System;
    return visitTree(loader.loads, moduleName, includePlugins && pluginLoader, function(load) {
      traceTree[load.name] = load;
    });
  })
  .then(function() {
    return {
      moduleName: moduleName,
      tree: traceTree
    };
  })
  .catch(function(e) {
    loader.global.System = System;
    throw e;
  });
};

function visitTree(tree, moduleName, pluginLoader, visit, seen) {
  seen = seen || [];

  if (seen.indexOf(moduleName) != -1)
    return;

  seen.push(moduleName);

  var load = tree[moduleName];

  if (!load)
    return Promise.resolve();

  // visit the deps first
  return Promise.all(load.deps.map(function(dep) {
    return visitTree(tree, load.depMap[dep], pluginLoader, visit, seen);
  })).then(function() {
    if (!pluginLoader)
      return;

    var pluginName = load.metadata.pluginName;
    if (pluginName) {
      return visitTree(pluginLoader.loads, pluginName, pluginLoader, visit, seen);
    }
  })
  .then(function() {
    // if we are the bottom of the tree, visit
    return visit(load);
  });
}

Builder.legacy = new Builder();

module.exports = Builder;
<|endoftext|>


<commit_before>function handler(event) {
  if event.target.type.includes("password") {
    navigator.clipboard.writeText("").then(
      function() {
        /* clipboard successfully set */
        event.stopImmediatePropagation();
      },
      function() {
        /* clipboard write failed */
        console.error("ClipSafe: Failed to write clipboard. Have you enabled the clipboard-write permission?");
      });
  }
}

function handlePermission() {
  navigator.permissions.query({name:'clipboard-write'}).then(function(result) {
    if (result.state == 'granted' || result.state == 'prompt') {
      document.addEventListener('paste', handler);
    }
    else if (result.state == 'denied') {
      console.error("ClipSafe: Clipboard write access explicitly denied.");
    }
    else {
      console.error("ClipSafe: Permissions API returned: " + result.state);
    }
    result.onchange = handlePermission;
  },
  function(error) {
    console.error("ClipSafe Error: " + error);
  });
}

handlePermission();

/* TODO
 * handle Permission API .request() method once it becomes available :(
 */
<commit_msg>Pending further FF changes<commit_after>function handler(event) {
  if event.target.type.includes("password") {
    navigator.clipboard.writeText("").then(
      function() {
        /* clipboard successfully set */
        event.stopImmediatePropagation();
      },
      function() {
        /* clipboard write failed */
        console.error("ClipSafe: Failed to write clipboard. Have you enabled the clipboard-write permission?");
      });
  }
}

function handlePermission() {
  navigator.permissions.query({name:'clipboard-write'}).then(function(result) {
    if (result.state == 'granted' || result.state == 'prompt') {
      document.addEventListener('paste', handler);
    }
    else if (result.state == 'denied') {
      console.error("ClipSafe: Clipboard write access explicitly denied.");
    }
    else {
      console.error("ClipSafe: Permissions API returned: " + result.state);
    }
    result.onchange = handlePermission;
  },
  function(error) {
    console.error("ClipSafe Error: " + error);
  });
}

handlePermission();

/* TODO
 * handle Permission API .request() method once it becomes available :(
 * Ugh do I need to deal with contenteditable? execCommand copy to clear the cb?
 * Double ugh, do I need to be a background script to make content editable?
 * So unclear & inconsistent - there's definitely a lot of churn around this
 * feature set right now. Probably best to wait until that cools down.
 */
<|endoftext|>


<commit_before>/*eslint strict:0*/
/*jshint strict:false */

var childProcess = require('child_process');
var os = require('os');
var fs = require('fs');
var net = require('net');
var path = require('path');

/* App Name */
/* -------- */
// Be sure to change this or your data might be stored
// somewhere you don't want it to be.
var appName = 'GrandView';

var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.

var dirname = __dirname;
console.log(dirname); // The name of the directory that the currently executing script resides in.

// Before starting a local server, freePort will find an available port by letting
// the OS find it.
function freePort (callback) {
  var server = net.createServer();
  var port = 0;

  server.on('listening', function () {
    port = server.address().port;
    server.close();
  });
  server.on('close', function () {
    callback(null, port);
  });

  server.listen(0, '127.0.0.1');
}

// Write something about Start method
function start (callback) {
  if (process.env.NODE_ENV === 'development') {
    console.log('Running in Dev mode.');
    callback('http://localhost:3000');
  } else {
    process.stdout.write('Starting production server\n');

    var appPath = '',
        dataPath = '',
        bundlePath = '';
    if (os.platform() === 'darwin') {
      appPath = path.join(process.env.HOME, 'Library/Application Support/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    } else if (os.platform() === 'win32') {
      appPath = path.join(process.env.HOMEPATH, 'AppData/Local/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    } else if (os.platform() === 'linux') {
      appPath = path.join(process.env.HOME, '/.config/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    }

    // If file paths don't yet exist, create them
    if (!fs.existsSync(appPath)) {
      fs.mkdirSync(appPath);
    }

    if (!fs.existsSync(dataPath)) {
      fs.mkdirSync(dataPath);
    }

    if (!fs.existsSync(bundlePath)) {
      fs.mkdirSync(bundlePath);
    }

    freePort(function (err, webPort) {
      freePort(function (err, mongoPort) {
        console.log('MongoPort: ', mongoPort);
        console.log('WebPort: ', webPort);

        // Be sure to change the PURPOSE to be the name of your app
        var command = '';
        if (os.platform() === 'darwin' || os.platform === 'linux') {
          command = 'rm -rf ' + path.join(dataPath, 'mongod.lock');
        } else if (os.platform() === 'win32') {
          childProcess.exec('rm -rf ' + path.join(dataPath, 'mongod.lock'));
        }

        childProcess.exec(command, function (err, stdout, stderr) {

          // Path to mongod command bundled with app.
          var mongodPath = path.join(dirname, 'resources', 'mongod');

          // Arguments passed to mongod command.
          var mongodArgs = [
            '--bind_ip',
            '127.0.0.1',
            '--dbpath',
            dataPath,
            '--port',
            mongoPort,
            '--unixSocketPrefix',
            dataPath,
            '--smallfiles'
          ];

          if (os.platform() === 'win32') {
            mongodArgs = [
              '--bind_ip',
              '127.0.0.1',
              '--dbpath',
              dataPath,
              '--port',
              mongoPort,
              '--smallfiles'
            ];
          }

          // Start the Mongo process.
          var mongoChild = childProcess.spawn(mongodPath, mongodArgs, {
            env: {
              PURPOSE: 'MY_ELECTROMETEOR_APP'
            }
          });

          mongoChild.stderr.setEncoding('utf8');
          mongoChild.stderr.on('data', function (data) {
            console.log(data);
          });

          var started = false;
          mongoChild.stdout.setEncoding('utf8');
          mongoChild.stdout.on('data', function (data) {
            console.log(data);

            if (data.indexOf('waiting for connections on port ' + mongoPort)) {
              if (!started) {
                started = true;
              } else {
                return;
              }

              console.log('Starting node child...');
              var rootURL = 'http://localhost';
              var userEnv = process.env;
              userEnv.ROOT_URL = rootURL;
              userEnv.PORT = webPort;
              userEnv.BIND_IP = '127.0.0.1';
              userEnv.DB_PATH = dataPath;
              userEnv.MONGO_URL = 'mongodb://localhost:' + mongoPort + '/meteor';
              userEnv.DIR = dirname;
              userEnv.NODE_ENV = 'production';
              userEnv.NODE_PATH = path.join(dirname, 'node_modules');

              var nodePath = path.join(dirname, 'resources', 'node');
              var nodeArgs = path.join(dirname, 'bundle', 'main.js');
              var nodeChild = childProcess.spawn(nodePath, [nodeArgs], {
                env: userEnv
              });

              var opened = false;

              // listen for errors
              nodeChild.stderr.setEncoding('utf8');
              nodeChild.stderr.on('data', function (nodeData) {
                console.log('stderr: ', nodeData);
              });

              nodeChild.stdout.setEncoding('utf8');
              nodeChild.stdout.on('data', function (nodeData) {
                console.log(nodeData);

                if (data.indexOf('Meteor app started.') !== -1) {
                  if (!opened) {
                    opened = true;
                  } else {
                    return;
                  }

                  setTimeout(function () {
                    var fullURL = rootURL + ':' + webPort;
                    callback(fullURL, nodeChild, mongoChild);
                  }, 100);
                }
              });
            }
          });
        });
      });
    });
  }
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.

// This is to let ESLint know that it's ok to have a global and 'true' allows it to be read/write
/*global mainWindow:true*/
mainWindow = null;

// Emitted when the application is activated while there is no opened windows.
// It usually happens when a user has closed all of application's windows and then
// click on the application's dock icon.
app.on('activate-with-no-open-windows', function () {
  if (mainWindow) {
    mainWindow.show();
  }

  return false;
});

// Emitted when Electron has done all of the initialization.
app.on('ready', function () {
  start(function (url, nodeChild, mongoChild) {
    console.log('App occupying ', url);
    var cleanup = function () {
      app.quit();
    };
    // Create the browser window.
    var windowOptions = {
      width: 1200,
      height: 800,
      "min-width": 1000,
      "min-height": 800,
      resizeable: true,
      frame: true
    };
    mainWindow = new BrowserWindow(windowOptions);
    mainWindow.focus();
    mainWindow.loadUrl(url);

    process.on('uncaughtException', cleanup);

    // Emitted when all windows have been closed and the application will quit.
    // Calling event.preventDefault() will prevent the default behaviour, which is
    // terminating the application.
    app.on('will-quit', function (event) {
      console.log(event);
      console.log('Cleaning up children.');

      if (nodeChild) {
        console.log('cleaning up node child');
        nodeChild.kill('SIGTERM');
      }

      if (mongoChild) {
        console.log('cleaning up mongo child');
        mongoChild.kill('SIGTERM');
      }

    });

    app.on('window-all-closed', function() {
      cleanup();
    });
  });
});
<commit_msg>Revert the index.js file<commit_after>/*eslint strict:0*/
var childProcess = require('child_process');
var os = require('os');
var fs = require('fs');
var net = require('net');
var path = require('path');
var exec = childProcess.exec;

/* App Name */
/* -------- */
// Be sure to change this or your data might be stored
// somewhere you don't want it to be.
var appName = 'GrandView';

var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.

var dirname = __dirname;
console.log(dirname); // The name of the directory that the currently executing script resides in.

// Before starting a local server, freePort will find an available port by letting
// the OS find it.
function freePort (callback) {
  var server = net.createServer();
  var port = 0;

  server.on('listening', function () {
    port = server.address().port;
    server.close();
  });
  server.on('close', function () {
    callback(null, port);
  });

  server.listen(0, '127.0.0.1');
}

// Write something about Start method
function start (callback) {
  if (process.env.NODE_ENV === 'development') {
    console.log('Running in Dev mode.');
    callback('http://localhost:3000');
  } else {
    process.stdout.write('Starting production server\n');

    var appPath = '',
        dataPath = '',
        bundlePath = '';
    if (os.platform() === 'darwin') {
      appPath = path.join(process.env.HOME, 'Library/Application Support/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    } else if (os.platform() === 'win32') {
      appPath = path.join(process.env.HOMEPATH, 'AppData/Local/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    } else if (os.platform() === 'linux') {
      appPath = path.join(process.env.HOME, '/.config/', appName, '/');
      dataPath = path.join(appPath, 'data');
      bundlePath = path.join(appPath, 'bundle');
    }

    // If file paths don't yet exist, create them
    if (!fs.existsSync(appPath)) {
      fs.mkdirSync(appPath);
    }

    if (!fs.existsSync(dataPath)) {
      fs.mkdirSync(dataPath);
    }

    if (!fs.existsSync(bundlePath)) {
      fs.mkdirSync(bundlePath);
    }

    freePort(function (err, webPort) {
      freePort(function (err, mongoPort) {
        console.log('MongoPort: ', mongoPort);
        console.log('WebPort: ', webPort);

        // Be sure to change the PURPOSE to be the name of your app
        var command = '';
        if (os.platform() === 'darwin' || os.platform === 'linux') {
          command = 'rm -rf ' + path.join(dataPath, 'mongod.lock');
        } else if (os.platform() === 'win32') {
          childProcess.exec('rm -rf ' + path.join(dataPath, 'mongod.lock'));
        }

        childProcess.exec(command, function (err, stdout, stderr) {

          // Path to mongod command bundled with app.
          var mongodPath = path.join(dirname, 'resources', 'mongod');

          // Arguments passed to mongod command.
          var mongodArgs = ['--bind_ip', '127.0.0.1', '--dbpath', dataPath, '--port', mongoPort, '--unixSocketPrefix', dataPath, '--smallfiles'];
          if (os.platform() === 'win32') {
            mongodArgs = ['--bind_ip', '127.0.0.1', '--dbpath', dataPath, '--port', mongoPort, '--smallfiles'];
          }

          // Start the Mongo process.
          var mongoChild = childProcess.spawn(mongodPath, mongodArgs, {
            env: {
              PURPOSE: 'MY_ELECTROMETEOR_APP'
            }
          });

          mongoChild.stderr.setEncoding('utf8');
          mongoChild.stderr.on('data', function (data) {
            console.log(data);
          });

          var started = false;
          mongoChild.stdout.setEncoding('utf8');
          mongoChild.stdout.on('data', function (data) {
            console.log(data);

            if (data.indexOf('waiting for connections on port ' + mongoPort)) {
              if (!started) {
                started = true;
              } else {
                return;
              }

              console.log('Starting node child...');
              var rootURL = 'http://localhost';
              var userEnv = process.env;
              userEnv.ROOT_URL = rootURL;
              userEnv.PORT = webPort;
              userEnv.BIND_IP = '127.0.0.1';
              userEnv.DB_PATH = dataPath;
              userEnv.MONGO_URL = 'mongodb://localhost:' + mongoPort + '/meteor';
              // user_env.METEOR_SETTINGS = fs.readFileSync(path.join(dirname, 'resources', 'settings.json'), 'utf8');
              userEnv.DIR = dirname;
              userEnv.NODE_ENV = 'production';
              userEnv.NODE_PATH = path.join(dirname, 'node_modules');

              var nodePath = path.join(dirname, 'resources', 'node');
              var nodeArgs = path.join(dirname, 'bundle', 'main.js');
              var nodeChild = childProcess.spawn(nodePath, [nodeArgs], {
                env: userEnv
              });

              var opened = false;

              // listen for errors
              nodeChild.stderr.setEncoding('utf8');
              nodeChild.stderr.on('data', function (nodeData) {
                console.log('stderr: ', nodeData);
              });

              nodeChild.stdout.setEncoding('utf8');
              nodeChild.stdout.on('data', function (nodeData) {
                console.log(nodeData);

                if (data.indexOf(!'Meteor app started.' === -1)) {
                  if (!opened) {
                    opened = true;
                  } else {
                    return;
                  }

                  setTimeout(function () {
                    var fullURL = rootURL + ':' + webPort;
                    callback(fullURL, nodeChild, mongoChild);
                  }, 100);
                }
              });
            }
          });
        });
      });
    });
  }
}

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.

/*global mainWindow:true*/ // <-- This is to let ESLint know that it's ok to have a global and 'true' allows it to be read/write
mainWindow = null;

// Emitted when the application is activated while there is no opened windows.
// It usually happens when a user has closed all of application's windows and then
// click on the application's dock icon.
app.on('activate-with-no-open-windows', function () {
  if (mainWindow) {
    mainWindow.show();
  }

  return false;
});

// Emitted when Electron has done all of the initialization.
app.on('ready', function () {
  start(function (url, nodeChild, mongoChild) {
    console.log('App occupying ', url);
    var cleanup = function () {
      app.quit();
    };
    // Create the browser window.
    var windowOptions = {
      width: 1200,
      height: 800,
      "min-width": 1000,
      "min-height": 800,
      resizeable: true,
      frame: true
    };
    mainWindow = new BrowserWindow(windowOptions);
    mainWindow.focus();
    mainWindow.loadUrl(url);

    process.on('uncaughtException', cleanup);

    // Emitted when all windows have been closed and the application will quit.
    // Calling event.preventDefault() will prevent the default behaviour, which is
    // terminating the application.
    app.on('will-quit', function (event) {
      console.log(event);
      console.log('Cleaning up children.');

      if (nodeChild) {
        console.log('cleaning up node child');
        nodeChild.kill('SIGTERM');
      }

      if (mongoChild) {
        console.log('cleaning up mongo child');
        mongoChild.kill('SIGTERM');
      }

    });

    app.on('window-all-closed', function() {
      cleanup();
    });
  });
});
<|endoftext|>