Example #1
0
 	co(function *() {
  	let tplName = yield prompt('Template name: ')
  	let projectName = yield prompt('Project name: ')
  	let gitUrl
  	let branch

		if (!config.tpl[tplName]) {
    	console.log(chalk.red('\n × Template does not exit!'))
    	process.exit()
    }
		gitUrl = config.tpl[tplName].url
		branch = config.tpl[tplName].branch

    let cmdStr = `git clone ${gitUrl} ${projectName} && cd ${projectName} && git checkout ${branch}`

	  console.log(chalk.white('\n Start generating...'))

	  exec(cmdStr, (error, stdout, stderr) => {
      if (error) {
        console.log(error)
        process.exit()
      }
      console.log(chalk.green('\n √ Generation completed!'))
      console.log(`\n cd ${projectName} && npm install \n`)
      process.exit()
	  })
  })
        co(function *() {              
            var pluginVersion = yield prompt('\nWhat is the new version of the plugin?');
            pluginVersion = semver.valid(pluginVersion)

            if (pluginVersion === null || pluginVersion === 'undefined' || pluginVersion === "") {
                console.error('\nValid plugin version is required, exiting.');
                process.exit(1);
            }
            console.log('\nUpdating plugin version to: %s', pluginVersion)
            replacePluginVersion(pluginVersion, pluginXMLFilePath)
            replacePluginVersionJSON(pluginVersion, packageJSONFilePath)

            var androidVerson = yield prompt('\nWhat Android SDK version should this version use? (leave blank if no update is required): ');
            androidVerson = semver.valid(androidVerson)

            console.log(androidVerson)
            if (androidVerson === null || androidVerson === 'undefined' || androidVerson === "") {
                console.log('\nSkipping Android SDK update, no valid version provided')
            } else {
                console.log('\nUpdating Android SDK version to: %s', androidVerson)
                replaceAndroidLibVersion(androidVerson, buildExtrasFilePath)
            }
            
            var iOSVersion = yield prompt('\nWhat iOS Plugin version should this version use? (leave blank if no update is required): ');
            iOSVersion = semver.valid(iOSVersion)

            if (iOSVersion === null || iOSVersion === 'undefined' || iOSVersion === "") {
                console.log('\nSkipping iOS SDK update, no valid version provided')
            } else {
                console.log('\nUpdating iOS SDK version to: %s', iOSVersion)
                replaceHeaders(iOSVersion, pluginXMLFilePath)
                replaceiOSLibVersion(iOSVersion, pluginXMLFilePath)
            }
        });
Example #3
0
function *project(projects) {
  if (projects.length) {
    process.stdout.write("choose a project or create a new one:\n");
    process.stdout.write(projects.join(", ") + "\n");
  }
  var name = yield prompt("project name: ");
  if (_.contains(projects, name)) return {name: name};

  return {
    name: name,
    currency: (yield prompt("currency: [usd] ")) || "usd",
    rate: (yield prompt("cost per hour: [0] ")) || "0"
  };
}
Example #4
0
      co(function * () {
        const sources = yield prompt(blue('Source folder: '));
        const destination = yield prompt(blue('Destination folder: '));

          // Gather the options
        config = {
          debug: log,
          source: source || sources || './css',
          output: (folder) ? '' : `${folder}/${(output || destination || 'dist')}`
        };

        process.stdin.pause();
        const Guide = new StyleGuide(config);
        Guide.create();
      });
Example #5
0
  return function*() {
    var credentials = {};
    if (opts.username && opts.password) {
      credentials.login = opts.username;
      credentials.password = opts.password;
    } else if (opts.username) {
      credentials.login = opts.username;
      credentials.password = yield prompt.password('Bugzilla password: '******'api-dev.bugzilla.mozilla.org'];
      if (!credentials) {
        credentials.login = yield prompt('Bugzilla username: '******'Bugzilla password: ');
      }
    }

    var client = bz.createClient({
      username: credentials.login,
      password: credentials.password,
      test: opts.test
    });

    return {
      bugAttachments: co.wrap(client.bugAttachments, client),
      createAttachment: co.wrap(client.createAttachment, client),
      updateAttachment: co.wrap(client.updateAttachment, client)
    };
  };
Example #6
0
/**
 *
 */
function promptMessage(message, callback) {
  repl.pause();
  coprompt(message)(function(err, res) {
    repl.resume();
    callback(err, res);
  });
}
 co(function *() {
   var yn = yield prompt('Migrating instances from ' + fromBroccoli + ' to ' + toBroccoli + '? [y/n]: ');
   if (yn == "y") {
     request
       .get(fromBroccoli + '/api/v1/instances')
       .end(function (err, res) {
         if (err) {
           console.error('Error retrieving the instances from %s: %s', fromBroccoli, err);
         } else {
           var instances = res.body;
           instances.forEach(function (instance){
             console.log('Migrating: %s', instance.id);
             var instanceCreation = {
               "templateId": instance.template.id,
               "parameters": instance.parameterValues
             };
             request
               .post(toBroccoli + '/api/v1/instances')
               .send(instanceCreation)
               .end(function (err, res) {
                 if (err) {
                   console.error('Error putting the instance %s to %s: %s', instance.id, toBroccoli, err);
                 }
               });
           });
         }
       });
   } else {
     console.log('Exiting.');
   }
   process.stdin.pause();
 }).catch(function(err) {
const parseValues = co(function *() {
	const config = {};
	let counter = 0;
	
	types.forEach((type) => {
		config[type] = program[type];
		if (!program[type]) {
			counter++;
		}
	});
	
	if (counter === types.length || (counter === types.length - 1 && config[constants.types.PATH])) {
		// if no arguments or only path provided run prompts
		config[constants.types.MODULE] = yield prompt(`Enter the name of ${constants.types.MODULE} *: `);
		if (!config[constants.types.MODULE] || '' === config[constants.types.MODULE]) {
			console.log(chalk.bold.red(`The name is required`));
			process.exit(0);
		}
		if (!config[constants.types.PATH]) {
			config[constants.types.PATH] = yield prompt(chalk.bold.cyan(`Optional path, we recommend to leave blank(will default to /src/[modules|components]):`));
		}
	}
	
	return config;
}).catch((error) => {
Example #9
0
 return function*() {
   var description = yield prompt('One-line description: ');
   if (!description) {
     console.error('Patch description is required');
     process.exit(1);
   }
   return description;
 };
Example #10
0
function *credentials() {
  process.stdout.write("Initializing Git Time Tracker\n");
  return {
    user: yield prompt.confirm("do have a gtt account? "),
    email: yield prompt("email: "),
    password: yield prompt.password("password: ")
  };
}
Example #11
0
        co(function *() {
            console.log(clc.message("This guide will help you to create your Harmonic configuration file\nJust hit enter if you are ok with the default values.\n\n"));

            var templateObj = {
                "name": "Awesome website",
                "title": "My awesome static website",
                "domain": "http://awesome.com",
                "subtitle": "Powered by Harmonic",
                "author": "Jaydson",
                "description": "This is the description",
                "bio": "Thats me",
                "template": "default",
                "posts_permalink" : ":year/:month/:title",
                "pages_permalink" : "pages/:title"
            };

            var config = {
                name : (yield prompt(clc.message('Site name: (' + templateObj.name + ')'))) || templateObj.name,
                title : (yield prompt(clc.message('Title: (' + templateObj.title + ')'))) || templateObj.title,
                subtitle : (yield prompt(clc.message('Subtitle: (' + templateObj.subtitle + ')'))) || templateObj.subtitle,
                description : (yield prompt(clc.message('Description: (' + templateObj.description + ')'))) || templateObj.description,
                author : (yield prompt(clc.message('Author: (' + templateObj.author + ')'))) || templateObj.author,
                bio : (yield prompt(clc.message('Author bio: (' + templateObj.bio + ')'))) || templateObj.bio,
                template : (yield prompt(clc.message('Template: (' + templateObj.template + ')'))) || templateObj.template
            }

            /* create the configuration file */
            fs.writeFile('./config.json', JSON.stringify(_.extend(templateObj, config), null, 4), function (err) {
                if (err) throw err;
                console.log(clc.info('Config file was successefuly created/updated'));
            });
            
            process.stdin.pause();

        })();
Example #12
0
 co(function*() {
     let leafs
     if (options !== undefined && options.leafs % 1 === 0) {
         leafs = options.leafs
     } else {
         leafs = yield prompt('No. of leafs?: ')
     }
     return leafs
 }).then(leafs => {
Example #13
0
 co(function * () {
   var notebookPath = yield prompt(emojic.greenBook + '  Where would you like to store your notebook? (leave blank for ' + home + '/notebook.txt): ')
   newConfigFile.notebooks.default = notebookPath ? notebookPath : newConfigFile.notebooks.default
   fs.closeSync(fs.openSync(defaultConfigPath, 'w'))
   fs.writeFileSync(defaultConfigPath, JSON.stringify(newConfigFile, '', 2))
   var entry = yield prompt('[' + emojic.pencil2 + "  Start writing your entry. When you're done press return to save your entry]\n")
   // Check to see if the file already exists
   fs.stat(newConfigFile.notebooks.default, function (err) {
     if (!err) {
       fs.appendFileSync(newConfigFile.notebooks.default, timeUtilities.getTime() + ' ' + entry + '\n\n')
       console.log('[' + emojic.v + '  Your entry was added to your notebook]')
     } else {
       fs.writeFileSync(newConfigFile.notebooks.default, timeUtilities.getTime() + ' ' + entry + '\n\n')
       console.log('[' + emojic.v + '  Your first entry was added to your notebook]')
     }
     process.exit()
   })
 })
Example #14
0
	co(function *() {
		const repo = yield prompt('Enter the URL to the repo (used in `git clone ${url}`): ')
		const master = yield prompt('Name of production branch (default master): ')
		const boson = yield prompt('Name of boson branch (default boson): ')
		const fermion = yield prompt('Name of fermion branch (default fermion): ')

		const site = {
			repo,
			master: master || 'master',
			boson: boson || 'boson',
			fermion: fermion || 'fermion'
		}

		console.log(`Registering site as ${options.name}`)
		options.settings.sites[options.name] = site

		process.stdin.pause()
		cb(options.settings)
	})
Example #15
0
 co(function *() {
   var secret = yield prompt('secret: ');
   console.log(
     'secretToUse: %s strToEncode: %s encodedTo: %s',
     secret,
     strToEncode,
     mapIndexed(XOR(strToEncode, secret), strToEncode).join("")
   )
   process.exit(1);
 })
Example #16
0
co(function* () {
  let body = cli.flags.body
  if (!body) {
    body = yield prompt(`> this.body = ${chalk.gray('(hello world)')} `)
  }

  let url = cli.flags.url
  if (!url) {
    url = yield prompt(`> options.url = ${chalk.gray('(/)')} `)
  }

  let port = cli.flags.port
  if (!port) {
    port = yield prompt(`> options.port = ${chalk.gray('(4000)')} `)
  }
  main({
    body,
    port,
    url
  })
}).catch(e => console.log(e.stack))
Example #17
0
	co(function *() {
		const portRangeMin = yield prompt(`Enter the minimum port number (default ${defaultPortRangeMin}): `)
		const portRangeMax = yield prompt(`Enter the maximum port number (default ${defaultPortRangeMax}): `)
		const deployFolder = yield prompt('Enter the folder name where `git clone` happens: ')
		const nginxFolder = yield prompt('Enter the folder where nginx.conf files should go: ')

		try {
			const settings = create({
				portRangeMin: parseInt(portRangeMin, 10) || defaultPortRangeMin,
				portRangeMax: parseInt(portRangeMax, 10) || defaultPortRangeMax,
				deployFolder,
				nginxFolder
			})
			console.log('Done!')
			process.stdin.pause()
			cb(settings)
		} catch (e) {
			console.log(e)
			process.exit(1)
		}
	})
Example #18
0
 co(function*() {
   if (username === undefined) {
     username = yield prompt('username: '******'password: ');
   }
   try {
     client.register(username, password);
   } catch (ex) {
     console.error(ex.stack);
   }
 });
Example #19
0
 return function*() {
   flags = [];
   for (var flag in availableFlags) {
     if (!availableFlags.hasOwnProperty(flag)) {
       continue;
     }
     var requestee = yield prompt(flag + '? ');
     if (requestee) {
       flags.push(new Flag(flag, requestee));
     }
   }
   return flags;
 };
HerokuKafkaClusters.prototype.checkConfirmation = function* (context, message) {
  if (context.flags.confirm !== context.app) {
    console.log(message);
    var confirm = yield prompt('> ');
    if (confirm === context.app) {
      return true;
    } else {
      console.log(`  !    Confirmation did not match ${context.app}. Aborted.`);
      return false;
    }
  } else {
    return true;
  }
};
Example #21
0
 	co(function *(){
 		var username = yield prompt(' username: '******' password: '******' uploading [:bar] :percent :etas', barOpts);
		fileStream.on('data', function (chunk) {
		bar.tick(chunk.length);
		});





		request
		 .post('https://api.bitbucket.org/2.0/snippets/')
		 .auth(username,password)
		 .attach('file',file)
		 .set('Accept','application/json')
		 .end(function(err,res){
		 	if(!err && res.ok){
		 		var link = res.body.links.html.href;
		 		console.log(chalk.bold.green('Snippet created: ' + link));
		 		process.exit(0);
		 	}
		 	var errormsg;
		 	if(res && res.status===401){
		 		errormsg='Bad Username/Password';
		 	}else if(err){
		 		errormsg=err;
		 	}else{
		 		errormsg=res.text;
		 	}
		 	console.error(chalk.bold.red('Error encountered:'+errormsg));
		 	process.exit(1);
		 }) 		
 	});
Example #22
0
    co(function *() {
        // 接收用户输入的参数
        let tplName = yield prompt('Template name: ')

        // 删除对应的模板
        if (config.tpl[tplName]) {
            config.tpl[tplName] = undefined
        } else {
            console.log(chalk.red('Template does not exist!'))
            process.exit()
        }
        
        // 写入template.json
        fs.writeFile(__dirname + '/../templates.json', JSON.stringify(config),     'utf-8', (err) => {
            if (err) console.log(err)
            console.log(chalk.green('Template deleted!'))
            console.log(chalk.grey('The last template list is: \n'))
            console.log(config)
            console.log('\n')
            process.exit()
        })
    })
Example #23
0
function* configure() {
  // Current configuration for the deploy...
  var currentConfig = {};

  // Load the config file if it exists to override the defaults...
  if (fs.existsSync(CONFIG)) {
    currentConfig = require(CONFIG);
  }

  // Prompt for all the configurations.
  for (var key in VARIABLES) {
    var desc = VARIABLES[key].description;
    var defaultValue = currentConfig[key] || VARIABLES[key].value

    var humanDesc =
      color.white(key + ': ') +
      color.cyanBright(
        desc + (defaultValue ? ' (' + defaultValue + ')' : '') + ': '
      );

    currentConfig[key] = (yield prompt(humanDesc)) || defaultValue;
  }

  console.log();
  console.log(util.inspect(currentConfig, { colors: true }));
  console.log();

  // Yeah bad things will happen if rejected too often...
  if (!(yield prompt.confirm("Does this look right? "))) {
    return yield configure();
  }

  // Stop waiting for user input so the process will exit.
  process.stdin.end();
  return currentConfig;
}
Example #24
0
function* question(field, desc) {
  return yield prompt(
    '  ' + color.cyan(field) + ' (' + color.white(desc) + ') : '
  );
}
Example #25
0
co(function *() {
  var screen_name = config.TWITTER_SCREEN_NAME;

  var me = yield User.findOne({ screen_name: screen_name });
  if (!me) {
    me = { screen_name: 'andyjiang', cursor: -1, index: 0 };
    yield User.insert(me);
  }


  var res = yield Twitter.friends(me.screen_name, me.cursor);
  var users = _.filter(res.data.users, { 'muting': false });
  var cursor = res.data.next_cursor_str;
  me.cursor = cursor;
  // save cursor to db

  var ans = 'n';
  for (var i = 0; i < users.length; i++) {
    var res_tweets = yield Twitter.tweets(users[i].id_str);
    var tweets = res_tweets.data;
    var originality = Twitter.originality(tweets);

    console.log();
    console.log(users[i].name + ' (@' + users[i].screen_name + ')');
    if (users[i].verified) console.log('verified');
    console.log('bio: ' + users[i].description);
    console.log('location: ' + users[i].location);
    console.log('following/followers: ' + users[i].friends_count + '/' + users[i].followers_count);
    console.log('original/retweets (out of 100): ' + originality);
    console.log('recent tweets:');
    for (var j = 0; j < 5; j++) {
      if (j === tweets.length) break;
      console.log();
      console.log('    ' + tweets[j].text);
      console.log('        ' + tweets[j].created_at);
      console.log();
    }

    // Get user input.
    ans = yield prompt('[n]ext/[m]ute/[u]nfollow/[q]uit: ');

    // Do the right thing.
    if (ans === 'm') {
      yield Twitter.mute(users[i].id_str);
    } else if (ans === 'u') {
      yield Twitter.unfollow(users[i].id_str);
    }

    // save micro cursor to db, which is the

    // if users < X, update cursor and get more users.
    if (ans === 'q') {
      me.index = i - 1;
      yield User.upsert(me);
      break;
    }

    if (users.length - i < 10) {
      var res_new_users = yield Twitter.friends(screen_name, me.cursor);
      var new_users = _.filter(res_new_users.data.users, { 'muting': false });
      users = users.concat(new_users);
      cursor = res_new_users.data.next_cursor_str;
      me.cursor = cursor;
    }
  }

  process.exit(0);
});
Example #26
0
 co(function * () {
   var entry = yield prompt('[' + emojic.pencil2 + "  Start writing your entry. When you're done press return to save your entry]\n")
   fs.appendFileSync(obj.notebooks.default, timeUtilities.getTime() + ' ' + entry + '\n\n')
   console.log('[' + emojic.v + '  Your entry was added to your notebook]')
   process.exit()
 })
Example #27
0
 co(function* () {
     let pathValidator = /^(([A-z0-9\-]+\/)*[A-z0-9\-]+$)/g, pathFileValidator = /^(([A-z0-9\-]+\/)*[A-z0-9\-]+(.ts)+$)/g, ynValidator = /^([yn]|(yes)|(no))$/ig, appName, toReturn, introMessage = (format) => `\nPlease enter a path matching the following format: ${chalk.green(format)}\nDon't add a leading or trailing slash to the path.\n`, prompts = [
         {
             name: "appFolder",
             question: "App Folder: (app) ",
             value: "app",
             message: "something/foo/bar",
             validator: pathValidator
         },
         {
             name: "bootFile",
             question: "Location of bootstrap file: (boot.ts) ",
             value: "boot.ts",
             message: "something/foo/bar.ts",
             validator: pathFileValidator
         },
         {
             name: "componentsFolder",
             question: "Components Folder: (common/components) ",
             value: "common/components",
             message: "something/foo/bar",
             validator: pathValidator
         },
         {
             name: "servicesFolder",
             question: "Services Folder: (common/services) ",
             value: "common/services",
             message: "something/foo/bar",
             validator: pathValidator
         },
         {
             name: "directivesFolder",
             question: "Directives Folder: (common/directives) ",
             value: "common/directives",
             message: "something/foo/bar",
             validator: pathValidator
         },
         {
             name: "pipesFolder",
             question: "Pipes Folder: (common/pipes) ",
             value: "common/pipes",
             message: "something/foo/bar",
             validator: pathValidator
         }
     ], values = {
         appFolder: "app",
         bootFile: "boot.ts",
         componentsFolder: "common/components",
         servicesFolder: "common/services",
         directivesFolder: "common/directives",
         pipesFolder: "common/pipes"
     }, generateApp = (yield prompt("Create starter app? (Y/n) ")) || "Y";
     while (generateApp.search(ynValidator) === -1) {
         console.log(chalk.red("\nOnly Y,N,yes and no are valid inputs.\n"));
         generateApp = (yield prompt("Create starter app? (Y/n) ")) || "Y";
     }
     generateApp = /^(y|(yes))$/ig.test(generateApp);
     if (generateApp) {
         let appTypeQuestion = `What kind of starting structure do you want to generate?\n(input the number associated with the app type)\n\n    1 - standard\n    2 - npm library\n\nStructure (1): `, appNameQuestion = `App name: (test-app) `, appType = (yield prompt(appTypeQuestion)) || "1", appTypeName, allowedFlagsValidator, allowedFlags = {
             "standard": [["t", "tslint"], ["g", "gulpfile"], ["a", "standard api service"], ["r", "basic routing"], ["l", "basic login"], ["s", "basic signup"]],
             "npmLibrary": [["t", "tslint"], ["g", "gulpfile"]]
         };
         while (appType.search(/^(1|2)$/g) === -1) {
             console.log(chalk.red("\nPlease provide a number between 1 and 2\n"));
             appType = (yield prompt(appTypeQuestion)) || "1";
         }
         appTypeName = appType === "1" ? "standard" : "npmLibrary";
         appName = (yield prompt(appNameQuestion)) || "test-app";
         while (appName.search(/^[0-9a-z-]+$/ig) === -1) {
             console.log(chalk.red("\nPlease provide a valid name\n"));
             appName = (yield prompt(appNameQuestion)) || "test-app";
         }
         toReturn = {
             json: {
                 appName: appName,
                 appType: appTypeName
             },
             generateApp: generateApp
         };
     }
     else {
         for (let i = 0; i < prompts.length; i++) {
             values[prompts[i].name] = (yield prompt(prompts[i].question)) || prompts[i].value;
             while (values[prompts[i].name].search(prompts[i].validator) === -1) {
                 if (prompts[i].message)
                     console.log(chalk.red(introMessage(prompts[i].message)));
                 values[prompts[i].name] = (yield prompt(prompts[i].question)) || prompts[i].value;
             }
         }
     }
     toReturn.json.appFolder = values.appFolder;
     toReturn.json.bootLocation = values.bootFile;
     toReturn.json.defaultFolders = {
         components: values.componentsFolder,
         services: values.servicesFolder,
         directives: values.directivesFolder,
         pipes: values.pipesFolder
     };
     return toReturn;
 }).then(values => {
Example #28
0
co(function*(){

  var bugzilla = yield getAuthenticatedBugzillaClient();

  if (!opts.bug) {
    opts.bug = yield getBugNumber();
  }

  if (!opts.description) {
    opts.description = yield getDescription();
  }

  if (!opts.comment || opts.comment === '') {
    opts.comment = yield getComment();
  }

  if (opts.flag) {
    opts.flag = opts.flag.map(parseFlag);
  } else {
    opts.flag = yield getFlags();
  }

  // obsolete old patches
  // XXX ideally, the bugAttachments request would happen in parallel with the 
  // user writing the comment
  console.log('Getting existing attachments…');
  var prevAttachments = yield bugzilla.bugAttachments(opts.bug);
  var prevPatches = prevAttachments.filter(function(attachment) {
    return attachment.is_patch && !attachment.is_obsolete;
  });
  if (prevPatches.length) {
    prevPatches.forEach(function(patch, i) {
      console.log('  '  + (i + 1) + ') ' + patch.description +
                  ' (by ' + patch.attacher.name + ')'); });
    var toObsolete = yield prompt('Patch numbers to obsolete ' +
                                  '(space-separated, Enter for none)? ');
    toObsolete = toObsolete.split(' ').filter(function(part) {
      return part !== '';
    });
    var okResponses = yield toObsolete.map(function(index) {
      var patch = prevPatches[parseInt(index) - 1];
      patch.is_obsolete = true;
      return bugzilla.updateAttachment(patch.id, patch);
    });
    console.log(okResponses.length + ' obsoleted.');
  }

  // create patch
  var diff = yield exec('git diff ' + opts.range);
  var attachment = {
    file_name: opts.bug + '.patch',
    is_patch: true,
    data: new Buffer(diff).toString('base64'),
    encoding: 'base64',
    description: opts.description,
    comments: [{
      text: opts.comment
    }],
    flags: opts.flag
  }

  // post
  console.log('Submitting the patch…');
  var att = yield bugzilla.createAttachment(opts.bug, attachment);
  console.log('Patch submitted!');
  console.log('  https://bugzilla.mozilla.org/attachment.cgi?id=' + att + 
              '&action=edit');
  process.exit(0);
});