Skip to content

Instantly share code, notes, and snippets.

@folknor
Created April 9, 2018 18:40
Show Gist options
  • Save folknor/ed8d36a1f4c5e279b02534b05050bc6c to your computer and use it in GitHub Desktop.
Save folknor/ed8d36a1f4c5e279b02534b05050bc6c to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
var electron = require('./')
var proc = require('child_process')
var child = proc.spawn(electron, process.argv.slice(2), {stdio: 'inherit'})
child.on('close', function (code) {
process.exit(code)
})
#!/usr/bin/env node
'use strict';
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
var chalk = require('chalk');
var semver = require('semver');
var archy = require('archy');
var Liftoff = require('liftoff');
var tildify = require('tildify');
var interpret = require('interpret');
var v8flags = require('v8flags');
var completion = require('../lib/completion');
var argv = require('minimist')(process.argv.slice(2));
var taskTree = require('../lib/taskTree');
// Set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();
var cli = new Liftoff({
name: 'gulp',
completions: completion,
extensions: interpret.jsVariants,
v8flags: v8flags,
});
// Exit with 0 or 1
var failed = false;
process.once('exit', function(code) {
if (code === 0 && failed) {
process.exit(1);
}
});
// Parse those args m8
var cliPackage = require('../package');
var versionFlag = argv.v || argv.version;
var tasksFlag = argv.T || argv.tasks;
var tasks = argv._;
var toRun = tasks.length ? tasks : ['default'];
// This is a hold-over until we have a better logging system
// with log levels
var simpleTasksFlag = argv['tasks-simple'];
var shouldLog = !argv.silent && !simpleTasksFlag;
if (!shouldLog) {
gutil.log = function() {};
}
cli.on('require', function(name) {
gutil.log('Requiring external module', chalk.magenta(name));
});
cli.on('requireFail', function(name) {
gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});
cli.on('respawn', function(flags, child) {
var nodeFlags = chalk.magenta(flags.join(', '));
var pid = chalk.magenta(child.pid);
gutil.log('Node flags detected:', nodeFlags);
gutil.log('Respawned to PID:', pid);
});
cli.launch({
cwd: argv.cwd,
configPath: argv.gulpfile,
require: argv.require,
completion: argv.completion,
}, handleArguments);
// The actual logic
function handleArguments(env) {
if (versionFlag && tasks.length === 0) {
gutil.log('CLI version', cliPackage.version);
if (env.modulePackage && typeof env.modulePackage.version !== 'undefined') {
gutil.log('Local version', env.modulePackage.version);
}
process.exit(0);
}
if (!env.modulePath) {
gutil.log(
chalk.red('Local gulp not found in'),
chalk.magenta(tildify(env.cwd))
);
gutil.log(chalk.red('Try running: npm install gulp'));
process.exit(1);
}
if (!env.configPath) {
gutil.log(chalk.red('No gulpfile found'));
process.exit(1);
}
// Check for semver difference between cli and local installation
if (semver.gt(cliPackage.version, env.modulePackage.version)) {
gutil.log(chalk.red('Warning: gulp version mismatch:'));
gutil.log(chalk.red('Global gulp is', cliPackage.version));
gutil.log(chalk.red('Local gulp is', env.modulePackage.version));
}
// Chdir before requiring gulpfile to make sure
// we let them chdir as needed
if (process.cwd() !== env.cwd) {
process.chdir(env.cwd);
gutil.log(
'Working directory changed to',
chalk.magenta(tildify(env.cwd))
);
}
// This is what actually loads up the gulpfile
require(env.configPath);
gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));
var gulpInst = require(env.modulePath);
logEvents(gulpInst);
process.nextTick(function() {
if (simpleTasksFlag) {
return logTasksSimple(env, gulpInst);
}
if (tasksFlag) {
return logTasks(env, gulpInst);
}
gulpInst.start.apply(gulpInst, toRun);
});
}
function logTasks(env, localGulp) {
var tree = taskTree(localGulp.tasks);
tree.label = 'Tasks for ' + chalk.magenta(tildify(env.configPath));
archy(tree)
.split('\n')
.forEach(function(v) {
if (v.trim().length === 0) {
return;
}
gutil.log(v);
});
}
function logTasksSimple(env, localGulp) {
console.log(Object.keys(localGulp.tasks)
.join('\n')
.trim());
}
// Format orchestrator errors
function formatError(e) {
if (!e.err) {
return e.message;
}
// PluginError
if (typeof e.err.showStack === 'boolean') {
return e.err.toString();
}
// Normal error
if (e.err.stack) {
return e.err.stack;
}
// Unknown (string, number, etc.)
return new Error(String(e.err)).stack;
}
// Wire up logging events
function logEvents(gulpInst) {
// Total hack due to poor error management in orchestrator
gulpInst.on('err', function() {
failed = true;
});
gulpInst.on('task_start', function(e) {
// TODO: batch these
// so when 5 tasks start at once it only logs one time with all 5
gutil.log('Starting', '\'' + chalk.cyan(e.task) + '\'...');
});
gulpInst.on('task_stop', function(e) {
var time = prettyTime(e.hrDuration);
gutil.log(
'Finished', '\'' + chalk.cyan(e.task) + '\'',
'after', chalk.magenta(time)
);
});
gulpInst.on('task_err', function(e) {
var msg = formatError(e);
var time = prettyTime(e.hrDuration);
gutil.log(
'\'' + chalk.cyan(e.task) + '\'',
chalk.red('errored after'),
chalk.magenta(time)
);
gutil.log(msg);
});
gulpInst.on('task_not_found', function(err) {
gutil.log(
chalk.red('Task \'' + err.task + '\' is not in your gulpfile')
);
gutil.log('Please check the documentation for proper gulpfile formatting');
process.exit(1);
});
}
#!/usr/bin/env node
var os = require("os"),
child = require("child_process"),
readline = require("readline");
var queue = require("queue-async"),
optimist = require("optimist");
var fs = require("fs");
var quote = require("../lib/gistup/quote"),
getSettings = require("../lib/gistup/get-settings"),
unless = require("../lib/gistup/unless"),
api = require("../lib/gistup/api"),
UserError = require("../lib/gistup/user-error");
var crossPlatform = require("../lib/gistup/cross-platform");
var argv = optimist.usage("Usage: \033[1mgistup\033[0m [options] -- [file …]" + os.EOL + os.EOL
+ "Version: " + require("../package.json").version + os.EOL + os.EOL
+ "Uploads the specified files to create a new Gist. If no files are specified," + os.EOL
+ "all files in the current directory are uploaded.")
.options("public", {
default: true,
describe: "true for a public gist; false for a secret one"
})
.options("private", {
default: false,
describe: "alias for --no-public"
})
.options("description", {
alias: "m",
default: "",
describe: "an optional description for your gist"
})
.options("interactive", {
alias: "i",
default: false,
describe: "request confirmation of every file before adding"
})
.options("exclude", {
alias: "x",
default: ".DS_Store",
describe: "skip files matching pattern; may use wildcards"
})
.options("open", {
default: "https://gist.github.com/",
describe: "URL to open in your web browser after creating gist"
})
.options("norepo", {
default: false,
describe: "Create a repo in the current directory"
})
.options("remote", {
default: "origin",
describe: "name of the git remote"
})
.options("version", {
default: false,
describe: "print the current version of gistup"
})
.options("help", {
alias: "h",
describe: "display this useful message"
})
.check(function(argv) {
if (argv.help) optimist.showHelp(), process.exit(0);
if (argv.version) console.log(require("../package.json").version), process.exit(0);
if (argv.private) argv.public = false;
if (argv.exclude === false) argv.exclude = [];
else if (!Array.isArray(argv.exclude)) argv.exclude = [argv.exclude];
})
.argv;
queue()
.defer(getSettings)
.await(function (error, settings) {
unless(error);
if (!argv.norepo) {
queue(1)
.defer(gitInit)
.defer(gitConfig, settings.gitConfigs)
.defer(gitRemoteDoesNotExist)
.defer(gitListUntrackedFiles)
.await(function(error, _, _, _, files) {
unless(error)
.defer(confirmFiles, files)
.defer(gitAdd, files)
.defer(gitCommit)
.defer(createGistFromFileList, settings.token, files)
.await(function(error, _, _, _, id) {
unless(error)
.defer(gitRemoteAdd, id)
// .defer(gitPush)
.defer(openBrowser, argv.open && settings.open, id)
.await(unless);
});
});
} else {
queue(1)
.defer(createGistFromFileList, settings.token, argv._)
.await(function(error,id) {
unless(error)
.defer(openBrowser, argv.open && settings.open, id)
.await(unless);
});
}
})
function gitInit(callback) {
child.exec("git init", function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git init failed.");
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
}
function gitConfig(gitConfigs, callback) {
gitConfigs.forEach(function(config){
console.log(config)
child.exec("git config " + config, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git config " + config + " failed.");
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
});
callback(null);
}
function gitRemoteDoesNotExist(callback) {
child.exec('git config --get remote.' + crossPlatform.envVal('remoteName') + '.url || '+ crossPlatform.rEcho(),{ env: crossPlatform.newEnvVal('remoteName', argv.remote)}, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git config failed.");
if (!error && stdout) error = new UserError("the remote \"" + argv.remote + "\" already exists." + os.EOL + os.EOL + "Are you trying to run gistup in a directory that already has a git" + os.EOL + "repository? This would overwrite your existing remote, which points to:" + os.EOL + os.EOL + " " + stdout + os.EOL + "If you’ve previously run gistup in this directory and you want to update" + os.EOL + "the contents of this gist, just push to the existing git remote:" + os.EOL + os.EOL + " git push" + os.EOL + os.EOL + "Or, if want to rename this gist:" + os.EOL + os.EOL + " gistup-rename 'New Description'" + os.EOL + os.EOL + "If you don’t need this remote anymore (say, if you cloned someone else’s" + os.EOL + "gist), gistup will replace it with a new one if you first run:" + os.EOL + os.EOL + " git remote rm " + argv.remote + os.EOL + os.EOL + "Lastly, you can also specify a different remote name for gistup, so that" + os.EOL + "you can push to multiple git remotes:" + os.EOL + os.EOL + " gistup --remote=gist" + os.EOL + os.EOL + "Please do one of the above and try again.");
callback(error);
});
}
function gitListUntrackedFiles(callback) {
if (argv._.length) return void callback(null, argv._);
files = argv.exclude.map(function(x) { return ' -x ' + crossPlatform.double(x); })
child.exec('git ls-files --others --exclude-standard --directory' + crossPlatform.envVal('files') + ' -x "*/"',{ env: crossPlatform.newEnvVal('files', files)}, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git ls-files failed.");
callback(error, error ? null : stdout.split(os.EOL).filter(Boolean));
});
}
function confirmFiles(files, callback) {
if (!argv.interactive) return void callback(null);
var readin = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var q = queue(1);
files.forEach(function(file) {
q.defer(confirmFile, file);
});
q.awaitAll(function(error) {
readin.close();
callback(error);
});
function confirmFile(file, callback) {
readin.question("add " + file + "? ", function(answer) {
if (/^y|yes$/i.test(answer)) return void callback(null);
if (/^n|no$/i.test(answer)) return files.splice(files.indexOf(file), 1), void callback(null);
confirmFile(file, callback);
});
}
}
function gitAdd(files, callback) {
if (typeof files[0] == 'function') return void callback(null);
if (!files.length) return void callback(null);
if(process.platform === "win32"){
var fileList = files.map(crossPlatform.double).join(" ");
child.exec("git add " + crossPlatform.envVal('files'), { env: crossPlatform.newEnvVal('files', fileList)}, function(error, stdout, stderr) {
if (!error && stderr) {
process.stderr.write(stderr)
if (stderr.match(/^((warning: (LF|CRLF))(.*((\S\s)((The file).*(\S\s)).*)*(working directory\S\s)))$/g) === null){
if (stderr) error = new Error("git add failed.");
}
}
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
} else {
child.exec("git add " + files.map(quote.double).join(" "), function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git add failed.");
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
}
}
function gitCommit(callback) {
child.exec('git commit --allow-empty -m "' + crossPlatform.envVal('msg') + '"', { env: crossPlatform.newEnvVal('msg', 'Initial gistup commit')}, function(error, stdout, stderr) {
if (!error && stderr) {
process.stderr.write(stderr);
if(stderr.match(/^((warning: (LF|CRLF))(.*((\S\s)((The file).*(\S\s)).*)*(working directory\S\s)))$/g) === null){
error = new Error("git commit failed.");
} else {
console.log(stderr);
}
}
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
}
function gistCreated(error, response, callback) {
var id = null;
if (!error && !/^[0-9a-f]+$/i.test(id = response.id)) error = new Error("invalid gist id: " + id); // for safety
if (!error) {
console.log("gist " + id + " created!");
console.log(response.html_url);
}
callback(error, id);
}
function createGist(token, fileContents, callback) {
api("POST", "/gists", token, {
"description": argv.description,
"public": argv.public,
"files": fileContents
}, function (error, response) {
gistCreated(error, response, callback);
});
}
function winFiles(files){
console.log("files")
console.log(files)
console.log(files.length)
if(files.length === 1){
files = files[0].split('\n');
for (i in files);
if(files[i] === "")
delete files[i];
}
if(!Boolean(files.length) || files[0] === '*'){
files = [];
listing = fs.readdirSync('./');
l = listing.length;
for(i=0; i<l; i++){
file = listing[i];
stats = fs.statSync(file);
if(stats.isFile()){
files.push(file);
}
}
}
return files;
}
function createGistFromFileList(token, files, callback) {
if(process.platform === 'win32'){
files = winFiles(files);
}
if (!files.length) {
unless(new UserError("File list must be provided since current directory has no files "));
}
var fileContents = {},
fileRead = queue();
files.forEach(function (filename) {
fileRead.defer(function (callback) {
fs.readFile(filename, {encoding: "utf8"}, function (error, content) {
if (error) {
return callback(error);
}
filename = filename.replace(/^.*[\\\/]/, '')
fileContents[filename] = {content: content};
callback(null);
});
});
});
fileRead.await(function (error) {
unless(error)
.defer(createGist, token, fileContents, callback)
.await(unless);
});
}
function gitRemoteAdd(id, callback) {
child.exec("git remote add --track master " + crossPlatform.envVal('remoteName') + " [email protected]:" + id + ".git", { env: crossPlatform.newEnvVal('remoteName', argv.remote)}, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git remote failed.");
if (!error && stdout) process.stdout.write(stdout);
callback(error);
});
}
function openBrowser(open, id, callback) {
if (!open) return void callback(null);
child.exec(open + " " + argv.open + id, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr); // ignore errors
process.exit(1);
});
}
#!/usr/bin/env node
var os = require("os"),
child = require("child_process");
var queue = require("queue-async"),
optimist = require("optimist");
var quote = require("../lib/gistup/quote"),
getSettings = require("../lib/gistup/get-settings"),
unless = require("../lib/gistup/unless"),
UserError = require("../lib/gistup/user-error");
var crossPlatform = require("../lib/gistup/cross-platform");
var argv = optimist.usage("Usage: \033[1mgistup-open\033[0m" + os.EOL + os.EOL
+ "Version: " + require("../package.json").version + os.EOL + os.EOL
+ "Opens the gist in the current directory.")
.options("version", {
default: false,
describe: "print the current version of gistup"
})
.options("open", {
default: "https://gist.github.com/",
describe: "URL to open in your web browser after creating gist"
})
.options("remote", {
default: "origin",
describe: "name of the git remote"
})
.options("help", {
alias: "h",
describe: "display this useful message"
})
.check(function(argv) {
if (argv.help) optimist.showHelp(), process.exit(0);
if (argv.version) console.log(require("../package.json").version), process.exit(0);
if (argv._.length) throw new Error("requires exactly zero arguments");
})
.argv;
queue(1)
.defer(getSettings)
.defer(getGistId)
.await(function(error, settings, id) {
unless(error)
.defer(openBrowser, settings.open, id)
.await(unless);
});
function getGistId(callback) {
child.exec('git config --get remote.' + crossPlatform.envVal('remoteName') + '.url',{ env: crossPlatform.newEnvVal('remoteName', argv.remote)}, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git config failed.");
if (error) return void callback(error);
var match = /^git@gist\.github\.com:([0-9a-f]+)\.git$/.exec(stdout = stdout.trim());
if (!match) return void callback(new UserError("the remote \"" + argv.remote + "\" looks funny." + os.EOL + "I was expecting something like" + os.EOL + os.EOL + " [email protected]:123456789.git" + os.EOL + os.EOL + "but instead the remote URL is" + os.EOL + os.EOL + " " + stdout + os.EOL + os.EOL + "so I’m giving up. Sorry."));
callback(null, match[1]);
});
}
function openBrowser(open, id, callback) {
child.exec(open + " " + argv.open + id, callback);
}
#!/usr/bin/env node
var os = require("os"),
child = require("child_process");
var queue = require("queue-async"),
optimist = require("optimist");
var quote = require("../lib/gistup/quote"),
getSettings = require("../lib/gistup/get-settings"),
unless = require("../lib/gistup/unless"),
api = require("../lib/gistup/api"),
UserError = require("../lib/gistup/user-error");
var crossPlatform = require("../lib/gistup/cross-platform");
var argv = optimist.usage("Usage: \033[1mgistup-rename\033[0m description" + os.EOL + os.EOL
+ "Version: " + require("../package.json").version + os.EOL + os.EOL
+ "Updates the description of the gist in the current directory.")
.options("version", {
default: false,
describe: "print the current version of gistup"
})
.options("remote", {
default: "origin",
describe: "name of the git remote"
})
.options("help", {
alias: "h",
describe: "display this useful message"
})
.check(function(argv) {
if (argv.help) optimist.showHelp(), process.exit(0);
if (argv.version) console.log(require("../package.json").version), process.exit(0);
if (argv._.length !== 1) throw new Error("requires exactly one argument");
})
.argv;
queue(1)
.defer(getSettings)
.defer(getGistId)
.await(function(error, settings, id) {
unless(error)
.defer(renameGist, settings.token, id)
.await(unless);
});
function getGistId(callback) {
child.exec('git config --get remote.' + crossPlatform.envVal('remoteName') + '.url',{ env: crossPlatform.newEnvVal('remoteName', argv.remote)}, function(error, stdout, stderr) {
if (!error && stderr) process.stderr.write(stderr), error = new Error("git config failed.");
if (error) return void callback(error);
var match = /^git@gist\.github\.com:([0-9a-f]+)\.git$/.exec(stdout = stdout.trim());
if (!match) return void callback(new UserError("the remote \"" + argv.remote + "\" looks funny." + os.EOL + "I was expecting something like" + os.EOL + os.EOL + " [email protected]:123456789.git" + os.EOL + os.EOL + "but instead the remote URL is" + os.EOL + os.EOL + " " + stdout + os.EOL + os.EOL + "so I’m giving up. Sorry."));
callback(null, match[1]);
});
}
function renameGist(token, id, callback) {
api("PATCH", "/gists/" + id, token, {
"description": argv._[0]
}, function(error, response) {
if (!error) console.log("gist " + id + " renamed!");
callback(error);
});
}
#!/usr/bin/env node
;(function () { // wrapper in case we're in module_context mode
// windows: running "npm blah" in this folder will invoke WSH, not node.
/*global WScript*/
if (typeof WScript !== 'undefined') {
WScript.echo(
'npm does not work when run\n' +
'with the Windows Scripting Host\n\n' +
"'cd' to a different directory,\n" +
"or type 'npm.cmd <args>',\n" +
"or type 'node npm <args>'."
)
WScript.quit(1)
return
}
process.title = 'npm'
var unsupported = require('../lib/utils/unsupported.js')
unsupported.checkForBrokenNode()
var log = require('npmlog')
log.pause() // will be unpaused when config is loaded.
log.info('it worked if it ends with', 'ok')
unsupported.checkForUnsupportedNode()
if (!unsupported.checkVersion(process.version).unsupported) {
var updater = require('update-notifier')
var pkg = require('../package.json')
updater({pkg: pkg}).notify({defer: true})
}
var path = require('path')
var npm = require('../lib/npm.js')
var npmconf = require('../lib/config/core.js')
var errorHandler = require('../lib/utils/error-handler.js')
var output = require('../lib/utils/output.js')
var configDefs = npmconf.defs
var shorthands = configDefs.shorthands
var types = configDefs.types
var nopt = require('nopt')
// if npm is called as "npmg" or "npm_g", then
// run in global mode.
if (path.basename(process.argv[1]).slice(-1) === 'g') {
process.argv.splice(1, 1, 'npm', '-g')
}
log.verbose('cli', process.argv)
var conf = nopt(types, shorthands)
npm.argv = conf.argv.remain
if (npm.deref(npm.argv[0])) npm.command = npm.argv.shift()
else conf.usage = true
if (conf.version) {
console.log(npm.version)
return errorHandler.exit(0)
}
if (conf.versions) {
npm.command = 'version'
conf.usage = false
npm.argv = []
}
log.info('using', 'npm@%s', npm.version)
log.info('using', 'node@%s', process.version)
process.on('uncaughtException', errorHandler)
if (conf.usage && npm.command !== 'help') {
npm.argv.unshift(npm.command)
npm.command = 'help'
}
// now actually fire up npm and run the command.
// this is how to use npm programmatically:
conf._exit = true
npm.load(conf, function (er) {
if (er) return errorHandler(er)
npm.commands[npm.command](npm.argv, function (err) {
// https://www.youtube.com/watch?v=7nfPu8qTiQU
if (!err && npm.config.get('ham-it-up') && !npm.config.get('json') && !npm.config.get('parseable') && npm.command !== 'completion') {
output('\n 🎡 I Have the Honour to Be Your Obedient Servant,🎡 ~ npm πŸ“œπŸ–‹\n')
}
errorHandler.apply(this, arguments)
})
})
})()
#!/usr/bin/env node
const npx = require('libnpx')
const path = require('path')
const NPM_PATH = path.join(__dirname, 'npm-cli.js')
npx(npx.parseArgs(process.argv, NPM_PATH))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment