导航栏: 首页 评论列表

hui init

默认分类 2014/11/09 08:22

package.json 完整代码

{
    "name": "hpm",
    "version": "0.0.1",
    "description": "Create hui package.json",
    "preferGlobal": "true",
    "bin": {
        "hpm": "bin\\hpm.js"
    },
    "author": "haiyang5210",
    "engines": {
        "node": "*"
    }
}

hui/bin/hui.js 完整代码:

#!/usr/bin/env node

'use strict';
var fs = require('fs');
var path = require('path');

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var pkg;
var ctx;

/** 
 * @name 对目标字符串进行格式化
 * @public
 * @param {String} source 目标字符串
 * @param {Object|String...} opts 提供相应数据的对象或多个字符串
 * @return {String} 格式化后的字符串
 */
function format(source, opts) {
    source = String(source);
    var data = Array.prototype.slice.call(arguments, 1),
        toString = Object.prototype.toString;
    if (data.length) {
        data = (data.length == 1 ?
            /* ie 下 Object.prototype.toString.call(null) == '[object Object]' */
            (opts !== null && (/\[object (Array|Object)\]/.test(toString.call(opts))) ? opts : data) : data);
        return source.replace(/#\{(.+?)\}/g, function (match, key) {
            var parts = key.split('.'),
                part = parts.shift(),
                cur = data,
                variable;
            while (part) {
                if (cur[part] !== undefined) {
                    cur = cur[part];
                }
                else {
                    cur = undefined;
                    break;
                }
                part = parts.shift();
            }
            variable = cur;

            if ('[object Function]' === toString.call(variable)) {
                variable = variable(key);
            }
            return (undefined === variable ? '' : variable);
        });
    }
    return source;
};

function formatDate(date, fmt) {
    if (!date) date = new Date();
    fmt = fmt || 'yyyy-MM-dd HH:mm';
    var o = {
        'M+': date.getMonth() + 1, //月份      
        'd+': date.getDate(), //日      
        'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, //小时      
        'H+': date.getHours(), //小时      
        'm+': date.getMinutes(), //分      
        's+': date.getSeconds(), //秒      
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度      
        'S': date.getMilliseconds() //毫秒      
    };
    var week = {
        '0': '/u65e5',
        '1': '/u4e00',
        '2': '/u4e8c',
        '3': '/u4e09',
        '4': '/u56db',
        '5': '/u4e94',
        '6': '/u516d'
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + week[date.getDay() + '']);
    }
    for (var k in o) {
        if (o.hasOwnProperty(k) && new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt;
};

// var pkgjson_src = path.resolve(__dirname, 'package.json');
var pkgjson_src = path.resolve(process.cwd(), 'package.json');

var basename = path.basename(path.dirname(pkgjson_src));

var pkgjson = [
    'name', basename,
    'version', '0.0.1',
    'description', 'This is \'' + basename + '\' Control.',
    'main', basename + '.js',
    // 'test', 'echo "Error: no test specified" && exit 1',
    // 'repository', 'git|http://github.com/' + basename,
    // 'keywords', 'javascript|node',
    // 'license', 'ISC',
    'author', 'haiyang2014'
];

var pkgdata = {};
for (var i = 0, len = pkgjson.length; i < len; i += 2) {
    pkgdata[pkgjson[i]] = pkgjson[i + 1];
}

function readPkgJson() {
    fs.readFile(pkgjson_src, 'utf8', function (er, d) {
        if (er) ctx = {};
        try {
            ctx = JSON.parse(d);
            pkg = JSON.parse(d);
        }
        catch (e) {
            ctx = {};
        }

        for (var i in ctx) {
            pkgdata[i] = ctx[i];
        }

        console.log(ctx);

        console.log([
            'This utility will walk you through creating a package.json file.',
            'It only covers the most common items, and tries to guess sane defaults.',
            '',
            'See `npm help json` for definitive documentation on these fields',
            'and exactly what they do.',
            '',
            'Use `npm install <pkg> --save` afterwards to install a package and',
            'save it as a dependency in the package.json file.',
            '',
            'Press ^C at any time to quit.'
        ].join('\n'));


        promptPkgjson.index = 0;
        promptPkgjson();

    });
}

function promptPkgjson() {
    var k = pkgjson[promptPkgjson.index],
        v = pkgjson[promptPkgjson.index + 1];
    rl.question(k + ': ' + (!!v ? '(' + v + ') ' : ''), function (answer) {
        pkgdata[pkgjson[promptPkgjson.index]] = answer || pkgjson[promptPkgjson.index + 1];

        promptPkgjson.index += 2;
        if (promptPkgjson.index >= pkgjson.length) {
            finishPrompt();
        }
        else {
            promptPkgjson();
        }

    });
}
promptPkgjson.index = 0;

function finishPrompt() {
    var d = JSON.stringify(pkgdata, null, 2) + '\n';
    console.log('About to write to %s:\n\n%s\n', pkgjson_src, d);
    rl.question('Is this ok? (yes)', function (ok) {
        rl.close();

        ok = String(ok).toLowerCase().trim();
        if (ok && ok.charAt(0) !== 'y') {
            console.log('Aborted.');
        }
        else {
            fs.writeFile(pkgjson_src, d, 'utf8', function (er) {
                if (er) throw er;
                console.log('ok');
            });

            if (pkgdata.main) {
                var main_src = path.resolve(process.cwd(), pkgdata.main);
                var main_init = [
                    '\'use strict\';',
                    '\/\**',
                    ' * @name #{name}',
                    ' * @public',
                    ' * @author #{author}',
                    ' * @date #{date}',
                    ' *\/',
                    'hui.define(\'hui_#{name}\', [\'hui\'], function () {',
                    '    ',
                    '});'
                ].join('\n');
                fs.writeFile(main_src, format(main_init, {
                    name: basename,
                    author: 'haiyang5210',
                    date: formatDate(new Date())
                }), 'utf8', function (er) {
                    if (er) throw er;
                    console.log('main ok');
                });
            }
        }
    });
}

var args = process.argv.splice(2);
if (args[0] === 'init') {
    readPkgJson();
    // console.log('init');
    // rl.close();
}
else {
    console.log(args);
    rl.close();
}


// [Example]
// {
//   "name": "npm-init",
//   "version": "0.0.0",
//   "description": "This is npm-init",
//   "main": "index.js",
//   "author": "haiyang2014"
// }


>> 留言评论