<commit_before> 'use strict';

var build       = module.exports = {};
var fs          = require('fs-sync');
var node_path   = require('path');
var hum         = require('hum');
var semver      = require('semver');
var async       = require('async');
var putin       = require('put-in');
var pkg_helper  = require('../util/package');
var semver_helper = require('../util/semver');
var lang        = require('../util/lang');
var spawns      = require('spawns');
var npm_dir     = require('npm-dir');


// @param {Object} options
//      see ./lib/option/build.js for details
build.run = function(options, callback){
    // if the destination is not specified by user
    if ( !options.dest ) {
        options.dest = this.context.profile.get('built_root');
    }

    var self = this;
    var pkg = pkg_helper.get_package_json(options.cwd);

    if ( pkg.err ) {
        return callback(pkg.err);
    }

    options.pkg = pkg.cortex;
    this.MESSAGE = this.context.locale.require('command-build');

    async.series([
        function (done) {
            self.run_preinstall_script(options, done);
        },

        function (done) {
            // run custom build script
            self.run_prebuild_script(options, done);
        },

        function (done) {
            // determine build tasks
            self.determine_tasks(options, done);
        },

        function (done) {
            // real building
            self.build(options, done);
        }

    ], function (err) {
        callback(err);
    });
};


// Run custom build scripts, such as 'grunt'
build.run_preinstall_script = function (options, callback) {
    if ( !options.preinstall ) {
        return callback(null);
    }

    this.run_script('preinstall', options, callback);
};


// Run custom build scripts, such as 'grunt'
build.run_prebuild_script = function (options, callback) {
    if ( !options.prebuild ) {
        return callback(null);
    }

    this.run_script('prebuild', options, callback);
};


build.run_script = function (script, options, callback) {
    var pkg = options.pkg;
    var scripts = lang.makeArray( pkg.scripts && pkg.scripts[script] )
        // skip empty scripts
        .filter(Boolean);

    if ( !scripts.length ) {
        return callback(null);
    }

    var self = this;

    this.logger.info('{{cyan run}} "scripts.' + script + '" ...');

    spawns( scripts, {
        cwd: options.cwd,
        stdio: 'inherit'

    }).on('spawn', function (command) {
        self.logger.info(' - {{cyan exec}} "' + command + '" ...');
        
    }).on('close', function (code, signal) {
        if ( code ) {
            callback({
                code: 'EBUILDSCRIPT',
                message: 'build step "scripts.' + script + '" executes as a failure. exit code: ' + code,
                data: {
                    code: code,
                    signal: signal,
                    script: script
                }
            });
        } else {
            callback(null);
        }

    }).on('error', function (err) {
        self.logger.warn('"scripts.' + script + '" let out an error: ' + err);
    });
};


build.determine_tasks = function (options, callback) {
    var cache_root  = this.context.profile.get('cache_root');
    var tasks       = options.tasks = {};
    var name        = options.pkg.name;
    var version     = options.pkg.version;
    var built_root  = options.dest;

    var parsed      = semver_helper.parse(version);

    if ( !parsed ) {
        return callback({
            code: 'EINVALIDVER',
            message: 'invalid semantic version "' + version + '" in package.json, see http://semver.org for details.',
            data: {
                version: version
            }
        });
    }

    // tasks[version] = node_path.join(built_root, name, version);
    var without_prerelease = semver_helper.remove_prerelease(version);
    tasks[without_prerelease] = node_path.join(built_root, name, without_prerelease);

    var self = this;

    if ( options.ranges ) {
        pkg_helper.get_module_document({
            name: name,
            cache_root: cache_root<commit_msg>fixes #219: complete cortex build;<commit_after> 'use strict';

var build       = module.exports = {};
var fs          = require('fs-sync');
var node_path   = require('path');
var hum         = require('hum');
var semver      = require('semver');
var async       = require('async');
var putin       = require('put-in');
var pkg_helper  = require('../util/package');
var semver_helper = require('../util/semver');
var lang        = require('../util/lang');
var spawns      = require('spawns');
var npm_dir     = require('npm-dir');


// @param {Object} options
//      see ./lib/option/build.js for details
build.run = function(options, callback){
    // if the destination is not specified by user
    if ( !options.dest ) {
        options.dest = this.context.profile.get('built_root');
    }

    this.MESSAGE = this.context.locale.require('command-build');

    var self = this;
    async.series([
        function (done) {
            self.read_package_json(options, done);
        },

        function (done) {
            self.run_preinstall_script(options, done);
        },

        function (done) {
            // run custom build script
            self.run_prebuild_script(options, done);
        },

        function (done) {
            // determine build tasks
            self.determine_tasks(options, done);
        },

        function (done) {
            // real building
            self.build(options, done);
        }

    ], function (err) {
        callback(err);
    });
};


build.read_package_json = function (options, callback) {
    pkg_helper.get_original_package(options.cwd, function (err, pkg) {
        options.pkg = pkg;
        callback(err);
    });
};


// Run custom build scripts, such as 'grunt'
build.run_preinstall_script = function (options, callback) {
    if ( !options.preinstall ) {
        return callback(null);
    }

    this.run_script('preinstall', options, callback);
};


// Run custom build scripts, such as 'grunt'
build.run_prebuild_script = function (options, callback) {
    if ( !options.prebuild ) {
        return callback(null);
    }

    this.run_script('prebuild', options, callback);
};


build.run_script = function (script, options, callback) {
    var pkg = options.pkg;
    var scripts = lang.makeArray( pkg.scripts && pkg.scripts[script] )
        // skip empty scripts
        .filter(Boolean);

    if ( !scripts.length ) {
        return callback(null);
    }

    var self = this;

    this.logger.info('{{cyan run}} "scripts.' + script + '" ...');

    spawns( scripts, {
        cwd: options.cwd,
        stdio: 'inherit'

    }).on('spawn', function (command) {
        self.logger.info(' - {{cyan exec}} "' + command + '" ...');
        
    }).on('close', function (code, signal) {
        if ( code ) {
            callback({
                code: 'EBUILDSCRIPT',
                message: 'build step "scripts.' + script + '" executes as a failure. exit code: ' + code,
                data: {
                    code: code,
                    signal: signal,
                    script: script
                }
            });
        } else {
            callback(null);
        }

    }).on('error', function (err) {
        self.logger.warn('"scripts.' + script + '" let out an error: ' + err);
    });
};


build.determine_tasks = function (options, callback) {
    var cache_root  = this.context.profile.get('cache_root');
    var tasks       = options.tasks = {};
    var name        = options.pkg.name;
    var version     = options.pkg.version;
    var built_root  = options.dest;

    var parsed      = semver_helper.parse(version);

    if ( !parsed ) {
        return callback({
            code: 'EINVALIDVER',
            message: 'invalid semantic version "' + version + '" in package.json, see http://semver.org for details.',
            data: {
                version: version
            }
        });
    }

    // Cortex will no longer publish prerelease versions into the registry,
    // so use the original version directly.
    tasks[version] = node_path.join(built_root, name, version);

    var self = this;

    if ( options.ranges ) {
        pkg_helper.get_cached_document({
            name: name,
            cache_root: cache_root
{'fraction_non_alphanumeric': 0.1371707782147539, 'fraction_numerical': 0.0003575259206292456, 'mean_word_length': 1.995003568879372, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2056405', 'n_tokens_mistral': 2471, 'n_tokens_neox': 2369, 'n_words': 586}