<commit_before>var CloudCommander, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = {
    load: (function(pParent){ /* function loads CodeMirror js and css files */

        /* function shows editor */
        var createEditorDiv = function(){
            if (!document.getElementById('CloudEditor')) {
                var lEditor=document.createElement('div');
                lEditor.id ='CloudEditor';
                var lFM = document.getElementById('fm');

                if(lFM){
                    lFM.appendChild(lEditor);
                }else console.log('Error. Something went wrong FM not found');

                pParent.show();
            }
        };
        /* function loads css files
         * of CodeMirror
         */
        var loadAll = function(pParent) {
            return function(){
                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
                });

                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/night.pack.css'
                });

                CloudCommander.cssSet({id:'editor',
                    inner : '.CodeMirror{'                          +
                                'font-family:\'Droid Sans Mono\';'  +
                                'font-size:15px;'                   +
                                'resize:vertical;'                  +
                                'padding:20px;'                     +
                            '}'                                     +
                            '.CodeMirror-scroll{'                   +
                                'height: 660px;'                    +
                            '}'                                     +
                            '.CodeMirror-scrollbar{'                +
                                 'overflow-y:auto'                  +
                            '}'
                });

                CloudCommander.jsload('lib/client/editor/codemirror/pack/xml.pack.js',
                    createEditorDiv);
            };
        };

        /* load CodeMirror main module */
        CloudCommander.jsload('lib/client/editor/codemirror/pack/codemirror.pack.js', loadAll(this));
    }),

    show : (function(){ /* function shows CodeMirror editor */
            /* if CloudEditor is not loaded - loading him */
            if(!document.getElementById('CloudEditor'))
                return this.load(this);
              /* removing keyBinding if set */
            CloudCommander.keyBinded = false;

            var lLeft           = this.getById('left');
            var lCloudEditor    = this.getById('CloudEditor');

            lLeft   &&
                (lLeft.className = 'panel hidden');

            CodeMirror(lCloudEditor,{
                            mode        : 'javascript',
                            value       : '',
                            theme       : 'night',
                            lineNumbers : true,
                            //переносим длинные строки
                            lineWrapping: true,
                            autofocus   : true,
                            extraKeys: {
                              //Сохранение
                              "Esc": this.hide(this)
                            }
            });

            lCloudEditor    &&
                (lCloudEditor.className  = '');
        }),
    hide :  (function(pParent) {
                return function(){
                    CloudCommander.keyBinded = true;

                    var lLeft           = pParent.getById('left');
                    var lCloudEditor    = pParent.getById('CloudEditor');

                    lCloudEditor &&
                        (lCloudEditor.className  = 'hidden');

                    lLeft       &&
                        (lLeft.className         = 'panel');

                    var lCodeMirror = pParent.getByClass('CodeMirror');
                    if(lCodeMirror.length)
                        lCloudEditor
                            .removeChild(lCodeMirror[0]);
                };
            }),
    getById     : function(pId){return document.getElementById(pId);},

    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    },

    getPanel    : function(){
        var lCurrent = document.getElementsByClassName('current-file');
        lCurrent.length &&
            (lCurrent = lCurrent[0].parentElement);

        return lCurrent && lCurrent.id;
    }
};
CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    CloudCommander.Editor.CodeMirror.show(CloudCommander.Editor.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<commit_msg>minor changes<commit_after>var CloudCommander, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = {
    load: (function(pParent){ /* function loads CodeMirror js and css files */

        /* function shows editor */
        var createEditorDiv = function(){
            if (!document.getElementById('CloudEditor')) {
                var lEditor=document.createElement('div');
                lEditor.id ='CloudEditor';
                var lFM = document.getElementById('fm');

                if(lFM){
                    lFM.appendChild(lEditor);
                }else console.log('Error. Something went wrong FM not found');

                pParent.show();
            }
        };
        /* function loads css files
         * of CodeMirror
         */
        var loadAll = function(pParent) {
            return function(){
                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
                });

                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/night.pack.css'
                });

                CloudCommander.cssSet({id:'editor',
                    inner : '.CodeMirror{'                          +
                                'font-family:\'Droid Sans Mono\';'  +
                                'font-size:15px;'                   +
                                'resize:vertical;'                  +
                                'padding:20px;'                     +
                            '}'                                     +
                            '.CodeMirror-scroll{'                   +
                                'height: 660px;'                    +
                            '}'                                     +
                            '.CodeMirror-scrollbar{'                +
                                 'overflow-y:auto'                  +
                            '}'
                });

                CloudCommander.jsload('lib/client/editor/codemirror/pack/xml.pack.js',
                    createEditorDiv);
            };
        };

        /* load CodeMirror main module */
        CloudCommander.jsload('lib/client/editor/codemirror/pack/codemirror.pack.js', loadAll(this));
    }),

    show : (function(){ /* function shows CodeMirror editor */
            /* if CloudEditor is not loaded - loading him */
            if(!document.getElementById('CloudEditor'))
                return this.load(this);
              /* removing keyBinding if set */
            CloudCommander.keyBinded = false;

            var lLeft           = this.getById('left');
            var lCloudEditor    = this.getById('CloudEditor');

            lLeft   &&
                (lLeft.className = 'panel hidden');

            CodeMirror(lCloudEditor,{
                            mode        : 'xml',
                            value       : '',
                            theme       : 'night',
                            lineNumbers : true,
                            //переносим длинные строки
                            lineWrapping: true,
                            autofocus   : true,
                            extraKeys: {
                              //Сохранение
                              "Esc": this.hide(this)
                            }
            });

            lCloudEditor    &&
                (lCloudEditor.className  = '');
        }),
    hide :  (function(pParent) {
                return function(){
                    CloudCommander.keyBinded = true;

                    var lLeft           = pParent.getById('left');
                    var lCloudEditor    = pParent.getById('CloudEditor');

                    lCloudEditor &&
                        (lCloudEditor.className  = 'hidden');

                    lLeft       &&
                        (lLeft.className         = 'panel');

                    var lCodeMirror = pParent.getByClass('CodeMirror');
                    if(lCodeMirror.length)
                        lCloudEditor
                            .removeChild(lCodeMirror[0]);
                };
            }),
    getById     : function(pId){return document.getElementById(pId);},

    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    },

    getPanel    : function(){
        var lCurrent = document.getElementsByClassName('current-file');
        lCurrent.length &&
            (lCurrent = lCurrent[0].parentElement);

        return lCurrent && lCurrent.id;
    }
};
CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    CloudCommander.Editor.CodeMirror.show(CloudCommander.Editor.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<|endoftext|>


<commit_before>var utils = require('./utils');

// Event stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];
    stream._b = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // buffer data in paused mode
        if (this._p) {
            this._b.push([err, data]);
            return this;
        }

        var newData;

        // call custom write handler
        if (typeof this._write === 'function') {
            newData = this._write(err, data, this);

            // overwrite data with transformed data
            if (newData !== undefined) {
                data = newData;
            }
        }

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, stream, handlers; o < ol; ++o) {

            // get ouputs input handlers
            stream = this._o[o];
            handlers = stream._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = handlers.length; i < l; ++i) {

                // call data handler with stream instance as function scope
                // and overwrite data with transformed data
                newData = handlers[i][0].call(stream._, err, data, stream, handlers[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            // end input stream if all outputs ended
            if (!this._i[i][0]._o.length) {
                this._i[i][0].end();
            } else {
                this._i[i][0]._o.splice(this._i[i][1], 1);
            }
        }

        // remove refs
        this._ = this._i = this._o = this._b = [];

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }

        return this;
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    },

    // buffer writes
    pause: function () {

        // enable pause mode
        this._p = true;

        return this;
    },

    // write bufferd data
    resume: function () {

        // disable pause mode
        this._p = false;

        // write bufferd data
        if (this._b.length) {
            for (var i = 0, l = this._b.length; i < l; ++i) {
                this.write(this._b[0], this._b[1]);
            }
        }

        return this;
    }
};
<commit_msg>Fixed buffered data writing in resume method.<commit_after>var utils = require('./utils');

// Event stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];
    stream._b = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // buffer data in paused mode
        if (this._p) {
            this._b.push([err, data]);
            return this;
        }

        var newData;

        // call custom write handler
        if (typeof this._write === 'function') {
            newData = this._write(err, data, this);

            // overwrite data with transformed data
            if (newData !== undefined) {
                data = newData;
            }
        }

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, stream, handlers; o < ol; ++o) {

            // get ouputs input handlers
            stream = this._o[o];
            handlers = stream._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = handlers.length; i < l; ++i) {

                // call data handler with stream instance as function scope
                // and overwrite data with transformed data
                newData = handlers[i][0].call(stream._, err, data, stream, handlers[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            // end input stream if all outputs ended
            if (!this._i[i][0]._o.length) {
                this._i[i][0].end();
            } else {
                this._i[i][0]._o.splice(this._i[i][1], 1);
            }
        }

        // remove refs
        this._ = this._i = this._o = this._b = [];

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }

        return this;
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    },

    // buffer writes
    pause: function () {

        // enable pause mode
        this._p = true;

        return this;
    },

    // write bufferd data
    resume: function () {

        // disable pause mode
        this._p = false;

        // write bufferd data
        if (this._b.length) {
            for (var i = 0, l = this._b.length; i < l; ++i) {
                this.write(this._b[i][0], this._b[i][1]);
            }
        }

        return this;
    }
};
<|endoftext|>


<commit_before>var util    = require('util');
var Command = require('./command/index.js');
var CommandCode = require('../constants/commands.js');
var Packet  = require('../packets/packet.js');

function Quit(callback)
{
  this.done = callback;
  Command.call(this);
}
util.inherits(Quit, Command);

Quit.prototype.start = function(packet, connection) {
  connection._closing = true;
  var quit = new Packet(0, new Buffer([0, 0, 0, 0, CommandCode.QUIT]));
  if (this.done)
    this.done();
  connection.writePacket(quit);
  return null;
};

module.exports = Quit;
<commit_msg>fix module path<commit_after>var util        = require('util');
var Command     = require('./command.js');
var CommandCode = require('../constants/commands.js');
var Packet      = require('../packets/packet.js');

debugger
function Quit(callback)
{
  this.done = callback;
  Command.call(this);
}
util.inherits(Quit, Command);

Quit.prototype.start = function(packet, connection) {
  connection._closing = true;
  var quit = new Packet(0, new Buffer([0, 0, 0, 0, CommandCode.QUIT]));
  if (this.done)
    this.done();
  connection.writePacket(quit);
  return null;
};

module.exports = Quit;
<|endoftext|>


<commit_before>/* global process, Promise */

/**
 * Role commands
 */

function registerRole (cli, options, done) {
  var roleCmd = cli.command('role')

  /**
   * API Error Response Handler
   */

  function apiError (err) {
    if (err.statusCode && [401, 403].indexOf(err.statusCode) !== -1) {
      cli.log.error('Please login to the issuer.')
    } else {
      console.log(err)
    }

    process.exit(1)
  }

  roleCmd
    .handler(function (data, flags, done) {
      cli.log('Usage:')
      cli.log(
        '  nvl role:register [<id>] [--issuer | -i <issuer id>] [--name | -n <name>]'
      )

      cli.log('  nvl role:list [--issuer | -i <issuer id>]')

      cli.log('  nvl role:info [<id>] [--issuer | -i <issuer id>]')

      cli.log(
        '  nvl role:update [<id>] [--issuer | -i <issuer id>] [--name | -n <name>]'
      )

      cli.log('  nvl role:delete [<id>] [--issuer | -i <issuer id>]')

      done()
    })

  /**
   * Role registration
   */

  roleCmd
    .task('register')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            cli.prompt([
              {
                type: 'input',
                name: 'name',
                message: 'Name',
                value: flags['name'] || flags.n,
                trim: true
              }
            ], function (answers) {
              // register the role
              anvil.roles.create(answers, { token: anvil.tokens.access_token })
                .then(function (registration) {
                  cli.log.json(registration)
                  done()
                })
                // registration error
                .catch(apiError)
            })
          })
          // discover error
          .catch(apiError)
      })
    })

  /**
   * Role list
   */

  roleCmd
    .task('list')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return anvil.roles.list({ token: anvil.tokens.access_token })
          })
          .then(function (roles) {
            var roleList = []
            roles.forEach(function (role) {
              roleList.push(role.name)
            })
            cli.log.json(roleList)

            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role info
   */

  roleCmd
    .task('info')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            return anvil.roles.get(roleName, { token: anvil.tokens.access_token })
          })
          .then(function (data) {
            cli.log.json(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role update
   */

  roleCmd
    .task('update')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            return anvil.roles.get(roleName, { token: anvil.tokens.access_token })
          })
          .then(function (role) {
            return new Promise(function (resolve, reject) {
              cli.prompt([
                {
                  type: 'input',
                  name: 'name',
                  message: 'Name',
                  value: flags['name'] || flags.n,
                  default: role.name,
                  trim: true
                }
              ], function (update) {
                resolve({
                  role: role,
                  update: update
                })
              })
            })
          })
          .then(function (data) {
            // Don't allow updating of required roles
            if (['authority'].indexOf(data.role.name) !== -1) {
              throw new Error('This role cannot be updated')
            }

            return anvil.roles.update(data.role.name, data.update, { token: anvil.tokens.access_token })
          })
          .then(function (data) {
            cli.log.json(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role delete
   */

  roleCmd
    .task('delete')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            // Don't allow deletion of required roles
            if (['authority'].indexOf(roleName) !== -1) {
              throw new Error('This role cannot be deleted')
            }

            return anvil.roles.delete(roleName, { token: anvil.tokens.access_token })
          })
          .then(function () {
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Scope list
   */

  roleCmd
    .task('scopes')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // prompt for role
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })

          // get the scopes
          .then(function (role) {
            return anvil.roles.scopes.list(role, { token: token })
          })

          // display the scopes
          .then(function (scopes) {
            scopes.forEach(function (scope) {
              cli.log.json({
                'name': scope.name,
                'description': scope.description,
                'restricted': scope.restricted
              })
            })

            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Permit
   */

  roleCmd
    .task('permit')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // get role and user choices
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              // command arguments for user and role
              if (data[0] && data[1]) {
                resolve({
                  roleName: data[0],
                  scopeName: data[1]
                })

              // prompt for user and role
              } else {
                Promise.all([
                  anvil.roles.list({ token: token }),
                  anvil.scopes.list({ token: token })
                ])
                .then(function (data) {
                  var roles = data[0]
                  var scopes = data[1]

                  cli.prompt([
                    {
                      type: 'list',
                      name: 'roleName',
                      message: 'Select a role',
                      choices: roles.map(function (role) {
                        return {
                          name: role.name,
                          value: role.name
                        }
                      })
                    },
                    {
                      type: 'list',
                      name: 'scopeName',
                      message: 'Select a scope to permit',
                      choices: scopes.map(function (scope) {
                        return {
                          name: scope.name,
                          value: scope.name
                        }
                      })
                    }
                  ], function (answers) {
                    resolve(answers)
                  })
                })
                .catch(reject)
              }
            })
          })

          // try to add the role
          .then(function (data) {
            var role = data.roleName
            var scope = data.scopeName

            return anvil.roles.scopes.add(role, scope, { token: token })
          })

          // display the result
          .then(function (response) {
            if (response.added) {
              console.log('The scope is now permitted')
            }
            done()
          })

          // handle error
          .catch(apiError)
      })
    })

  /**
   * Permit
   */

  roleCmd
    .task('forbid')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // get role and user choices
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              // command arguments for user and role
              if (data[0] && data[1]) {
                resolve({
                  roleName: data[0],
                  scopeName: data[1]
                })

              // prompt for user and role
              } else {
                Promise.all([
                  anvil.roles.list({ token: token }),
                  anvil.scopes.list({ token: token })
                ])
                .then(function (data) {
                  var roles = data[0]
                  var scopes = data[1]

                  cli.prompt([
                    {
                      type: 'list',
                      name: 'roleName',
                      message: 'Select a role',
                      choices: roles.map(function (role) {
                        return {
                          name: role.name,
                          value: role.name
                        }
                      })
                    },
                    {
                      type: 'list',
                      name: 'scopeName',
                      message: 'Select a scope to forbid',
                      choices: scopes.map(function (scope) {
                        return {
                          name: scope.name,
                          value: scope.name
                        }
                      })
                    }
                  ], function (answers) {
                    resolve(answers)
                  })
                })
                .catch(reject)
              }
            })
          })

          // try to add the role
          .then(function (data) {
            var role = data.roleName
            var scope = data.scopeName

            return anvil.roles.scopes.delete(role, scope, { token: token })
          })

          // display the result
          .then(function (response) {
            console.log('The scope is no longer permitted')
            done()
          })

          // handle error
          .catch(apiError)
      })
    })

  done()
}

/**
 * Exports
 */

module.exports = registerRole
<commit_msg>chore(role): update useage to include role commands scopes, permit and forbid<commit_after>/* global process, Promise */

/**
 * Role commands
 */

function registerRole (cli, options, done) {
  var roleCmd = cli.command('role')

  /**
   * API Error Response Handler
   */

  function apiError (err) {
    if (err.statusCode && [401, 403].indexOf(err.statusCode) !== -1) {
      cli.log.error('Please login to the issuer.')
    } else {
      console.log(err)
    }

    process.exit(1)
  }

  roleCmd
    .handler(function (data, flags, done) {
      cli.log('Usage:')
      cli.log(
        '  nvl role:register [<id>] [--issuer | -i <issuer id>] [--name | -n <name>]'
      )

      cli.log('  nvl role:list [--issuer | -i <issuer id>]')

      cli.log('  nvl role:info [<id>] [--issuer | -i <issuer id>]')

      cli.log(
        '  nvl role:update [<id>] [--issuer | -i <issuer id>] [--name | -n <name>]'
      )

      cli.log('  nvl role:delete [<id>] [--issuer | -i <issuer id>]')

      cli.log('  nvl role:scopes [<role name>] [--issuer | -i <issuer id>]')

      cli.log('  nvl role:permit [<role name> <scope name>] [--issuer | -i <issuer id>]')

      cli.log('  nvl role:forbid [<role name> <scope name>] [--issuer | -i <issuer id>]')

      done()
    })

  /**
   * Role registration
   */

  roleCmd
    .task('register')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            cli.prompt([
              {
                type: 'input',
                name: 'name',
                message: 'Name',
                value: flags['name'] || flags.n,
                trim: true
              }
            ], function (answers) {
              // register the role
              anvil.roles.create(answers, { token: anvil.tokens.access_token })
                .then(function (registration) {
                  cli.log.json(registration)
                  done()
                })
                // registration error
                .catch(apiError)
            })
          })
          // discover error
          .catch(apiError)
      })
    })

  /**
   * Role list
   */

  roleCmd
    .task('list')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return anvil.roles.list({ token: anvil.tokens.access_token })
          })
          .then(function (roles) {
            var roleList = []
            roles.forEach(function (role) {
              roleList.push(role.name)
            })
            cli.log.json(roleList)

            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role info
   */

  roleCmd
    .task('info')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            return anvil.roles.get(roleName, { token: anvil.tokens.access_token })
          })
          .then(function (data) {
            cli.log.json(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role update
   */

  roleCmd
    .task('update')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            return anvil.roles.get(roleName, { token: anvil.tokens.access_token })
          })
          .then(function (role) {
            return new Promise(function (resolve, reject) {
              cli.prompt([
                {
                  type: 'input',
                  name: 'name',
                  message: 'Name',
                  value: flags['name'] || flags.n,
                  default: role.name,
                  trim: true
                }
              ], function (update) {
                resolve({
                  role: role,
                  update: update
                })
              })
            })
          })
          .then(function (data) {
            // Don't allow updating of required roles
            if (['authority'].indexOf(data.role.name) !== -1) {
              throw new Error('This role cannot be updated')
            }

            return anvil.roles.update(data.role.name, data.update, { token: anvil.tokens.access_token })
          })
          .then(function (data) {
            cli.log.json(data)
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Role delete
   */

  roleCmd
    .task('delete')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: anvil.tokens.access_token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })
          .then(function (roleName) {
            // Don't allow deletion of required roles
            if (['authority'].indexOf(roleName) !== -1) {
              throw new Error('This role cannot be deleted')
            }

            return anvil.roles.delete(roleName, { token: anvil.tokens.access_token })
          })
          .then(function () {
            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Scope list
   */

  roleCmd
    .task('scopes')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // prompt for role
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              if (data[0]) {
                resolve(data[0])
              } else {
                anvil.roles.list({ token: token })
                  .then(function (roles) {
                    cli.prompt([
                      {
                        type: 'list',
                        name: 'roleName',
                        message: 'Select a role',
                        choices: roles.map(function (role) {
                          return {
                            name: role.name,
                            value: role.name
                          }
                        })
                      }
                    ], function (answers) {
                      resolve(answers.roleName)
                    })
                  })
                  .catch(reject)
              }
            })
          })

          // get the scopes
          .then(function (role) {
            return anvil.roles.scopes.list(role, { token: token })
          })

          // display the scopes
          .then(function (scopes) {
            scopes.forEach(function (scope) {
              cli.log.json({
                'name': scope.name,
                'description': scope.description,
                'restricted': scope.restricted
              })
            })

            done()
          })
          .catch(apiError)
      })
    })

  /**
   * Permit
   */

  roleCmd
    .task('permit')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // get role and user choices
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              // command arguments for user and role
              if (data[0] && data[1]) {
                resolve({
                  roleName: data[0],
                  scopeName: data[1]
                })

              // prompt for user and role
              } else {
                Promise.all([
                  anvil.roles.list({ token: token }),
                  anvil.scopes.list({ token: token })
                ])
                .then(function (data) {
                  var roles = data[0]
                  var scopes = data[1]

                  cli.prompt([
                    {
                      type: 'list',
                      name: 'roleName',
                      message: 'Select a role',
                      choices: roles.map(function (role) {
                        return {
                          name: role.name,
                          value: role.name
                        }
                      })
                    },
                    {
                      type: 'list',
                      name: 'scopeName',
                      message: 'Select a scope to permit',
                      choices: scopes.map(function (scope) {
                        return {
                          name: scope.name,
                          value: scope.name
                        }
                      })
                    }
                  ], function (answers) {
                    resolve(answers)
                  })
                })
                .catch(reject)
              }
            })
          })

          // try to add the role
          .then(function (data) {
            var role = data.roleName
            var scope = data.scopeName

            return anvil.roles.scopes.add(role, scope, { token: token })
          })

          // display the result
          .then(function (response) {
            if (response.added) {
              console.log('The scope is now permitted')
            }
            done()
          })

          // handle error
          .catch(apiError)
      })
    })

  /**
   * Permit
   */

  roleCmd
    .task('forbid')
    .handler(function (data, flags, done) {
      cli.issuers.prompt(flags['issuer'] || flags.i, function (err, issuer) {
        if (err) {
          cli.log.error(err)
          process.exit(1)
        }

        try {
          var anvil = cli.client.create(issuer)
          var token = anvil.tokens.access_token
        } catch (e) {
          cli.log.error(e)
          process.exit(1)
        }

        anvil.discover()

          // get role and user choices
          .then(function (configuration) {
            return new Promise(function (resolve, reject) {
              // command arguments for user and role
              if (data[0] && data[1]) {
                resolve({
                  roleName: data[0],
                  scopeName: data[1]
                })

              // prompt for user and role
              } else {
                Promise.all([
                  anvil.roles.list({ token: token }),
                  anvil.scopes.list({ token: token })
                ])
                .then(function (data) {
                  var roles = data[0]
                  var scopes = data[1]

                  cli.prompt([
                    {
                      type: 'list',
                      name: 'roleName',
                      message: 'Select a role',
                      choices: roles.map(function (role) {
                        return {
                          name: role.name,
                          value: role.name
                        }
                      })
                    },
                    {
                      type: 'list',
                      name: 'scopeName',
                      message: 'Select a scope to forbid',
                      choices: scopes.map(function (scope) {
                        return {
                          name: scope.name,
                          value: scope.name
                        }
                      })
                    }
                  ], function (answers) {
                    resolve(answers)
                  })
                })
                .catch(reject)
              }
            })
          })

          // try to add the role
          .then(function (data) {
            var role = data.roleName
            var scope = data.scopeName

            return anvil.roles.scopes.delete(role, scope, { token: token })
          })

          // display the result
          .then(function (response) {
            console.log('The scope is no longer permitted')
            done()
          })

          // handle error
          .catch(apiError)
      })
    })

  done()
}

/**
 * Exports
 */

module.exports = registerRole
<|endoftext|>


<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint node: true, newcap: false */
'use strict';

var di = require('di');
var os = require('os');

module.exports = loggerFactory;

di.annotate(loggerFactory, new di.Provide('Logger'));
di.annotate(loggerFactory,
    new di.Inject(
        'Constants',
        'Assert',
        'Protocol.Logging',
        'LogEvent',
        'Services.Waterline',
        'Services.Configuration',
        'Tracer',
        'Q',
        '_',
        'Util'
    )
);

/**
 * loggerFactory returns a Logger instance.
 * @private
 * @param  {postal} postal Postal Instance.
 * * @param  {configuration} configuration Configuration Instance.
 * * @param  {Q} Q Q Instance.
 * * @param  {di.Injector} injector Dependency Injector.
 * @return {Logger} a Logger instance.
 */
function loggerFactory(
    Constants,
    assert,
    loggingProtocol,
    LogEvent,
    waterline,
    configuration,
    tracer,
    Q,
    _,
    util
) {
    var levels = _.keys(Constants.Logging.Levels);

    /**
     * Logger is a logger class which provides methods for logging based
     * on log levels with mesages & metadata provisions.  The Logger sends
     * all log method calls to the logger postal channel for consumption by other
     * services.
     *  logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'});
     * @constructor
     */
    function Logger (module) {
        var provides = util.provides(module);

        if (provides !== undefined) {
            this.module = provides;
        } else {
            if (_.isFunction(module)) {
                this.module = module.name;
            } else {
                this.module = module || 'No Module';
            }
        }
    }

    /**
     * _log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     * @private
     */
    Logger.prototype.log = function (level, message, context) {
        var self = this;

        assert.isIn(level, levels);
        assert.string(message, 'message');

        return LogEvent.create(
            self.module, level, message, context || {}
        ).then(function (log) {
            return log.print();
        }).then(function (log) {
            loggingProtocol.publishLog(log.level, log);
            return log;
        }).then(function(log) {
            return waterline.logs.create({
                module: self.module,
                level: level,
                message: message,
                context: log.context,
                trace: log.trace,
                timestamp: log.timestamp,
                caller: log.caller,
                subject: log.subject,
                host: os.hostname()
            }).catch(function(error) {
                console.log("Error persisting log message: " + error);
            });
        }).catch(function (error) {
            /* istanbul ignore next */
            console.log(error);

            /* istanbul ignore next */
            console.log(error.stack);
        });
    };

    // Iterate the available levels and create the appropriate prototype function.
    _.keys(Constants.Logging.Levels).forEach(function(level) {
        /**
         * level - Helper method to allow logging by using the specific level
         * as the method instead of calling log directly.
         * @param {string} message Log Message
         * @param {object} metadata Log Metadata (Optional)
         */
        Logger.prototype[level] = function (message, context) {
            this.log(level, message, context);
        };
    });

    Logger.initialize = function (module) {
        return new Logger(module);
    };

    return Logger;
}
<commit_msg>ignore log statement in logger coverage<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint node: true, newcap: false */
'use strict';

var di = require('di');
var os = require('os');

module.exports = loggerFactory;

di.annotate(loggerFactory, new di.Provide('Logger'));
di.annotate(loggerFactory,
    new di.Inject(
        'Constants',
        'Assert',
        'Protocol.Logging',
        'LogEvent',
        'Services.Waterline',
        'Services.Configuration',
        'Tracer',
        'Q',
        '_',
        'Util'
    )
);

/**
 * loggerFactory returns a Logger instance.
 * @private
 * @param  {postal} postal Postal Instance.
 * * @param  {configuration} configuration Configuration Instance.
 * * @param  {Q} Q Q Instance.
 * * @param  {di.Injector} injector Dependency Injector.
 * @return {Logger} a Logger instance.
 */
function loggerFactory(
    Constants,
    assert,
    loggingProtocol,
    LogEvent,
    waterline,
    configuration,
    tracer,
    Q,
    _,
    util
) {
    var levels = _.keys(Constants.Logging.Levels);

    /**
     * Logger is a logger class which provides methods for logging based
     * on log levels with mesages & metadata provisions.  The Logger sends
     * all log method calls to the logger postal channel for consumption by other
     * services.
     *  logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'});
     * @constructor
     */
    function Logger (module) {
        var provides = util.provides(module);

        if (provides !== undefined) {
            this.module = provides;
        } else {
            if (_.isFunction(module)) {
                this.module = module.name;
            } else {
                this.module = module || 'No Module';
            }
        }
    }

    /**
     * _log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     * @private
     */
    Logger.prototype.log = function (level, message, context) {
        var self = this;

        assert.isIn(level, levels);
        assert.string(message, 'message');

        return LogEvent.create(
            self.module, level, message, context || {}
        ).then(function (log) {
            return log.print();
        }).then(function (log) {
            loggingProtocol.publishLog(log.level, log);
            return log;
        }).then(function(log) {
            return waterline.logs.create({
                module: self.module,
                level: level,
                message: message,
                context: log.context,
                trace: log.trace,
                timestamp: log.timestamp,
                caller: log.caller,
                subject: log.subject,
                host: os.hostname()
            }).catch(function(error) {
                /* istanbul ignore next */
                console.log("Error persisting log message: " + error);
            });
        }).catch(function (error) {
            /* istanbul ignore next */
            console.log(error);

            /* istanbul ignore next */
            console.log(error.stack);
        });
    };

    // Iterate the available levels and create the appropriate prototype function.
    _.keys(Constants.Logging.Levels).forEach(function(level) {
        /**
         * level - Helper method to allow logging by using the specific level
         * as the method instead of calling log directly.
         * @param {string} message Log Message
         * @param {object} metadata Log Metadata (Optional)
         */
        Logger.prototype[level] = function (message, context) {
            this.log(level, message, context);
        };
    });

    Logger.initialize = function (module) {
        return new Logger(module);
    };

    return Logger;
}
<|endoftext|>


<commit_before>// Dependencies
var Which = require("which")
  , Exec = require("child_process").exec
  , OArgv = require("oargv")
  , Path = require("path")
  ;

/**
 * CheckCobc
 * Checks if `cobc` exists as executable.
 *
 * @name CheckCobc
 * @function
 * @param {Function} callback The callback function.
 */
var _cobcExists = false;
function CheckCobc(callback) {
    if (_cobcExists) {
        return process.nextTick(function () {
            callback(_cobcExists);
        });
    }
    Which("cobc", function (err) {
        _cobcExists = !err;
        callback(_cobcExists);
    });
}

/**
 * Compile
 * Compiles the cobol file.
 *
 * @name Compile
 * @function
 * @param {String} input The path to the cobol file.
 * @param {Object} options An object containing the following fields:
 * @param {Function} callback The callback function.
 */
function Compile(input, options, callback) {
    if (options.precompiled) {
      var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));
      callback(null, output);
    } else {
      CheckCobc(function (exists) {
          if (!exists) {
              return callback(new Error("Couldn't find the cobc executable in the PATH. Make sure you installed Open Cobol."));
          }

          var args = {
              x: true
            , _: input
          };
          if (options.free) {
              args.free = options.free;
          }

          Exec(OArgv(args, "cobc"), {
              cwd: options.cwd
          }, function (err, stdout, stderr) {
              if (stderr || err) {
                  return callback(stderr || err);
              }
              var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));
              callback(null, output);
          });
      });
    }
}

module.exports = Compile;
<commit_msg>Moved output outside if statement<commit_after>// Dependencies
var Which = require("which")
  , Exec = require("child_process").exec
  , OArgv = require("oargv")
  , Path = require("path")
  ;

/**
 * CheckCobc
 * Checks if `cobc` exists as executable.
 *
 * @name CheckCobc
 * @function
 * @param {Function} callback The callback function.
 */
var _cobcExists = false;
function CheckCobc(callback) {
    if (_cobcExists) {
        return process.nextTick(function () {
            callback(_cobcExists);
        });
    }
    Which("cobc", function (err) {
        _cobcExists = !err;
        callback(_cobcExists);
    });
}

/**
 * Compile
 * Compiles the cobol file.
 *
 * @name Compile
 * @function
 * @param {String} input The path to the cobol file.
 * @param {Object} options An object containing the following fields:
 * @param {Function} callback The callback function.
 */
function Compile(input, options, callback) {

    var output = Path.join(options.cwd, Path.basename(input).slice(0, -4));

    if (options.precompiled) {
      callback(null, output);
    } else {
      CheckCobc(function (exists) {
          if (!exists) {
              return callback(new Error("Couldn't find the cobc executable in the PATH. Make sure you installed Open Cobol."));
          }

          var args = {
              x: true
            , _: input
          };
          if (options.free) {
              args.free = options.free;
          }

          Exec(OArgv(args, "cobc"), {
              cwd: options.cwd
          }, function (err, stdout, stderr) {
              if (stderr || err) {
                  return callback(stderr || err);
              }
              callback(null, output);
          });
      });
    }
}

module.exports = Compile;
<|endoftext|>


<commit_before>// Copyright (c) 2017, Patrick Quist
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

var Compile = require('../base-compiler'),
    logger = require('../logger').logger,
    utils = require('../utils'),
    fs = require("fs"),
    path = require("path");

function compileFPC(info, env) {
    var compiler = new Compile(info, env);
    compiler.supportsOptOutput = false;

    var originalExecBinary = compiler.execBinary;

    var symbolcache = {};
    var sortedsymbolcache = [];
    var fixedsymbols = {};
    var ignoredsymbols = [];

    fixedsymbols['OUTPUT_$$_init'] = 'unit_initialization';
    fixedsymbols['OUTPUT_$$_finalize'] = 'unit_finalization';
    fixedsymbols['OUTPUT_$$_init_implicit'] = 'unit_initialization_implicit';
    fixedsymbols['OUTPUT_$$_finalize_implicit'] ='unit_finalization_implicit';

    ignoredsymbols = [
        ".L", "VMT_$", "INIT_$", "INIT$_$", "FINALIZE$_$", "RTTI_$", "_$",
        "DEBUGSTART_$", "DEBUGEND_$", "DBG_$", "DBG2_$", "DBGREF_$"];

    var addDemangleToCache = function(text) {
        if (text.endsWith(':')) {
            if (shouldIgnoreSymbol(text)) {
                return;
            }

            for (var k in fixedsymbols) {
                if (text.startsWith(k)) {
                    text = text.replace(k, fixedsymbols[k]);
                    symbolcache[k] = fixedsymbols[k];
                    return;
                }
            }

            text = text.substr(0, text.length - 1);

            if (text.startsWith("U_$OUTPUT_$$_")) {
                var unmangledglobalvar = text.substr(13).toLowerCase();
                symbolcache[text] = unmangledglobalvar;
                return;
            }

            var idx, paramtype = "", signature = "", phase = 0;
            var unitname = "", classname = "", methodname = "", params = "", resulttype = "";

            idx = text.indexOf("$_$");
            if (idx != -1) {
                unitname = text.substr(0, idx - 1);
                classname = text.substr(idx + 3, text.indexOf("_$_", idx + 2) - idx - 3);
            }

            signature = "";
            idx = text.indexOf("_$$_");
            if (idx != -1) {
                if (unitname == "") unitname = text.substr(0, idx - 1);
                signature =  text.substr(idx + 3);
            }

            if (unitname == "") {
                idx = text.indexOf("OUTPUT_");
                if (idx != -1) {
                    unitname = "OUTPUT";

                    idx = text.indexOf("_$__");
                    if (idx != -1) {
                        classname = text.substr(7, idx - 7);
                        signature = text.substr(idx + 3);
                    } else {
                        signature = text.substr(6);
                    }
                }
            }

            if (signature != "") {
                for (idx = 1; idx < signature.length; idx++) {
                    if (signature[idx] == '$') {
                        if (phase == 0) phase = 1;
                        else if (phase == 1) {
                            if (paramtype == "") phase = 2;
                            else if (params != "") {
                                params = params + "," + paramtype;
                                paramtype = "";
                            } else if (params == "") {
                                params = paramtype;
                                paramtype = "";
                            }
                        }
                    } else {
                        if (phase == 0) methodname = methodname + signature[idx];
                        else if (phase == 1) paramtype = paramtype + signature[idx];
                        else if (phase == 2) resulttype = resulttype + signature[idx];
                    }
                }

                if (paramtype != "") {
                    if (params != "") params = params + "," + paramtype;
                    else params = paramtype;
                }
            }

            symbolcache[text] = composeReadableMethodSignature(unitname, classname, methodname, params);
        }
    };

    var composeReadableMethodSignature = function (unitname, classname, methodname, params) {
        var signature = "";

        if (classname != "") signature = classname.toLowerCase() + ".";

        signature = signature + methodname.toLowerCase();
        signature = signature + "(" + params.toLowerCase() + ")";

        return signature;
    };

    var shouldIgnoreSymbol = function(text) {
        for (var k in ignoredsymbols) {
            if (text.startsWith(ignoredsymbols[k])) {
                return true;
            }
        }

        return false;
    };

    var demangleIfNeeded = function(text) {
        if (text.includes('$')) {
            if (shouldIgnoreSymbol(text)) {
                return text;
            }

            for (var idx in sortedsymbolcache) {
                text = text.replace(sortedsymbolcache[idx][0], sortedsymbolcache[idx][1]);
            }

            return text;
        } else {
            return text;
        }
    };

    var buildOrderedCache = function () {
        sortedsymbolcache = [];
        for (var symbol in symbolcache) {
           sortedsymbolcache.push([symbol, symbolcache[symbol]]);
        }

        sortedsymbolcache = sortedsymbolcache.sort(function(a, b) {
            return b[0].length - a[0].length;
        });

        symbolcache = {};
    };

    compiler.postProcessAsm = function (result) {
        if (!result.okToCache) return result;

        for (var i = 0; i < result.asm.length; ++i) {
            addDemangleToCache(result.asm[i].text);
        }

        buildOrderedCache();

        for (var i = 0; i < result.asm.length; ++i)
            result.asm[i].text = demangleIfNeeded(result.asm[i].text);

        return result;
    };

    compiler.optionsForFilter = function (filters, outputFilename, userOptions) {
        return ['@/opt/compiler-explorer/fpc/fpc.cfg', '-a', '-g'];
    };

    var saveDummyProjectFile = function (filename) {
        fs.writeFile(filename,
            "program prog; " +
            "uses output in 'output.pas'; " +
            "begin " +
            "end.");
    };

    compiler.objdump = function (outputFilename, result, maxSize, intelAsm, demangle) {
         outputFilename = path.join(path.dirname(outputFilename), "prog");

         var args = ["-d", outputFilename, "-l", "--insn-width=16"];
         if (demangle) args = args.concat(["-C"]);
         if (intelAsm) args = args.concat(["-M", "intel"]);
         return this.exec(this.compiler.objdumper, args, {maxOutput: maxSize})
            .then(function (objResult) {
                result.asm = objResult.stdout;
                var relevantAsmStartsAt = result.asm.indexOf("<OUTPUT");
                if (relevantAsmStartsAt != -1) {
                    var lastLinefeedBeforeStart = result.asm.lastIndexOf("\n", relevantAsmStartsAt);
                    if (lastLinefeedBeforeStart != -1) {
                        result.asm =
                            result.asm.substr(0, result.asm.indexOf("00000000004")) + "\n" +
                            result.asm.substr(lastLinefeedBeforeStart + 1);
                    } else {
                        result.asm =
                            result.asm.substr(0, result.asm.indexOf("00000000004")) + "\n" +
                            result.asm.substr(relevantAsmStartsAt);
                    }
                }

                if (objResult.code !== 0) {
                    result.asm = "<No output: objdump returned " + objResult.code + ">";
                }
                return result;
            });
    };

    compiler.runCompiler = function (compiler, options, inputFilename, execOptions) {
        if (!execOptions) {
            execOptions = this.getDefaultExecOptions();
        }

        var projectFile = path.join(path.dirname(inputFilename), "prog.dpr");

        saveDummyProjectFile(projectFile);

        options.pop();
        options.push('-B');
        options.push(projectFile);

        return this.exec(compiler, options, execOptions).then(function (result) {
            result.inputFilename = inputFilename;
            result.stdout = utils.parseOutput(result.stdout, inputFilename);
            result.stderr = utils.parseOutput(result.stderr, inputFilename);
            return result;
        });
    };

    compiler.execBinary = function (executable, result, maxSize) {
        executable = path.join(path.dirname(executable), "prog");

        originalExecBinary(executable, result, maxSize);
    };

    return compiler.initialise();
}

module.exports = compileFPC;
<commit_msg>linter fixes<commit_after>// Copyright (c) 2017, Patrick Quist
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

var Compile = require('../base-compiler'),
    logger = require('../logger').logger,
    utils = require('../utils'),
    fs = require("fs"),
    path = require("path");

function compileFPC(info, env) {
    var compiler = new Compile(info, env);
    compiler.supportsOptOutput = false;

    var originalExecBinary = compiler.execBinary;

    var symbolcache = {};
    var sortedsymbolcache = [];
    var fixedsymbols = {};
    var ignoredsymbols = [];

    fixedsymbols.OUTPUT_$$_init = 'unit_initialization';
    fixedsymbols.OUTPUT_$$_finalize = 'unit_finalization';
    fixedsymbols.OUTPUT_$$_init_implicit = 'unit_initialization_implicit';
    fixedsymbols.OUTPUT_$$_finalize_implicit ='unit_finalization_implicit';

    ignoredsymbols = [
        ".L", "VMT_$", "INIT_$", "INIT$_$", "FINALIZE$_$", "RTTI_$", "_$",
        "DEBUGSTART_$", "DEBUGEND_$", "DBG_$", "DBG2_$", "DBGREF_$"];

    var addDemangleToCache = function(text) {
        if (text.endsWith(':')) {
            if (shouldIgnoreSymbol(text)) {
                return;
            }

            for (var k in fixedsymbols) {
                if (text.startsWith(k)) {
                    text = text.replace(k, fixedsymbols[k]);
                    symbolcache[k] = fixedsymbols[k];
                    return;
                }
            }

            text = text.substr(0, text.length - 1);

            if (text.startsWith("U_$OUTPUT_$$_")) {
                var unmangledglobalvar = text.substr(13).toLowerCase();
                symbolcache[text] = unmangledglobalvar;
                return;
            }

            var idx, paramtype = "", signature = "", phase = 0;
            var unitname = "", classname = "", methodname = "", params = "", resulttype = "";

            idx = text.indexOf("$_$");
            if (idx != -1) {
                unitname = text.substr(0, idx - 1);
                classname = text.substr(idx + 3, text.indexOf("_$_", idx + 2) - idx - 3);
            }

            signature = "";
            idx = text.indexOf("_$$_");
            if (idx != -1) {
                if (unitname == "") unitname = text.substr(0, idx - 1);
                signature =  text.substr(idx + 3);
            }

            if (unitname == "") {
                idx = text.indexOf("OUTPUT_");
                if (idx != -1) {
                    unitname = "OUTPUT";

                    idx = text.indexOf("_$__");
                    if (idx != -1) {
                        classname = text.substr(7, idx - 7);
                        signature = text.substr(idx + 3);
                    } else {
                        signature = text.substr(6);
                    }
                }
            }

            if (signature != "") {
                for (idx = 1; idx < signature.length; idx++) {
                    if (signature[idx] == '$') {
                        if (phase == 0) phase = 1;
                        else if (phase == 1) {
                            if (paramtype == "") phase = 2;
                            else if (params != "") {
                                params = params + "," + paramtype;
                                paramtype = "";
                            } else if (params == "") {
                                params = paramtype;
                                paramtype = "";
                            }
                        }
                    } else {
                        if (phase == 0) methodname = methodname + signature[idx];
                        else if (phase == 1) paramtype = paramtype + signature[idx];
                        else if (phase == 2) resulttype = resulttype + signature[idx];
                    }
                }

                if (paramtype != "") {
                    if (params != "") params = params + "," + paramtype;
                    else params = paramtype;
                }
            }

            symbolcache[text] = composeReadableMethodSignature(unitname, classname, methodname, params);
        }
    };

    var composeReadableMethodSignature = function (unitname, classname, methodname, params) {
        var signature = "";

        if (classname != "") signature = classname.toLowerCase() + ".";

        signature = signature + methodname.toLowerCase();
        signature = signature + "(" + params.toLowerCase() + ")";

        return signature;
    };

    var shouldIgnoreSymbol = function(text) {
        for (var k in ignoredsymbols) {
            if (text.startsWith(ignoredsymbols[k])) {
                return true;
            }
        }

        return false;
    };

    var demangleIfNeeded = function(text) {
        if (text.includes('$')) {
            if (shouldIgnoreSymbol(text)) {
                return text;
            }

            for (var idx in sortedsymbolcache) {
                text = text.replace(sortedsymbolcache[idx][0], sortedsymbolcache[idx][1]);
            }

            return text;
        } else {
            return text;
        }
    };

    var buildOrderedCache = function () {
        sortedsymbolcache = [];
        for (var symbol in symbolcache) {
           sortedsymbolcache.push([symbol, symbolcache[symbol]]);
        }

        sortedsymbolcache = sortedsymbolcache.sort(function(a, b) {
            return b[0].length - a[0].length;
        });

        symbolcache = {};
    };

    compiler.postProcessAsm = function (result) {
        if (!result.okToCache) return result;

        for (var i = 0; i < result.asm.length; ++i) {
            addDemangleToCache(result.asm[i].text);
        }

        buildOrderedCache();

        for (var j = 0; j < result.asm.length; ++j)
            result.asm[j].text = demangleIfNeeded(result.asm[j].text);

        return result;
    };

    compiler.optionsForFilter = function (filters, outputFilename, userOptions) {
        return ['@/opt/compiler-explorer/fpc/fpc.cfg', '-a', '-g'];
    };

    var saveDummyProjectFile = function (filename) {
        fs.writeFile(filename,
            "program prog; " +
            "uses output in 'output.pas'; " +
            "begin " +
            "end.");
    };

    compiler.objdump = function (outputFilename, result, maxSize, intelAsm, demangle) {
         outputFilename = path.join(path.dirname(outputFilename), "prog");

         var args = ["-d", outputFilename, "-l", "--insn-width=16"];
         if (demangle) args = args.concat(["-C"]);
         if (intelAsm) args = args.concat(["-M", "intel"]);
         return this.exec(this.compiler.objdumper, args, {maxOutput: maxSize})
            .then(function (objResult) {
                result.asm = objResult.stdout;
                var relevantAsmStartsAt = result.asm.indexOf("<OUTPUT");
                if (relevantAsmStartsAt != -1) {
                    var lastLinefeedBeforeStart = result.asm.lastIndexOf("\n", relevantAsmStartsAt);
                    if (lastLinefeedBeforeStart != -1) {
                        result.asm =
                            result.asm.substr(0, result.asm.indexOf("00000000004")) + "\n" +
                            result.asm.substr(lastLinefeedBeforeStart + 1);
                    } else {
                        result.asm =
                            result.asm.substr(0, result.asm.indexOf("00000000004")) + "\n" +
                            result.asm.substr(relevantAsmStartsAt);
                    }
                }

                if (objResult.code !== 0) {
                    result.asm = "<No output: objdump returned " + objResult.code + ">";
                }
                return result;
            });
    };

    compiler.runCompiler = function (compiler, options, inputFilename, execOptions) {
        if (!execOptions) {
            execOptions = this.getDefaultExecOptions();
        }

        var projectFile = path.join(path.dirname(inputFilename), "prog.dpr");

        saveDummyProjectFile(projectFile);

        options.pop();
        options.push('-B');
        options.push(projectFile);

        return this.exec(compiler, options, execOptions).then(function (result) {
            result.inputFilename = inputFilename;
            result.stdout = utils.parseOutput(result.stdout, inputFilename);
            result.stderr = utils.parseOutput(result.stderr, inputFilename);
            return result;
        });
    };

    compiler.execBinary = function (executable, result, maxSize) {
        executable = path.join(path.dirname(executable), "prog");

        originalExecBinary(executable, result, maxSize);
    };

    return compiler.initialise();
}

module.exports = compileFPC;
<|endoftext|>


<commit_before>var _ = require("lodash")
var path = require("path")

// Load configuration file
function loadFile(dir, filename) {
  if (filename == null) return {}
  filename = path.join(dir, filename)
  try {
    return require(filename)
  } catch(e) {
    return {}
  }
}

module.exports = Config
function Config(options) {
  this.options = options
  this._config = null
}

Config.prototype.getConfig = function () {
  if (!this._config) {
    this._config = _.extend({},
      loadFile(this.options.dir, "default"),
      loadFile(this.options.dir, process.env.NODE_ENV),
      loadFile(this.options.dir, "local")
    )
  }
  return this._config
}

Config.prototype.apply = function(compiler) {
  // Build the configuration object
  var options = this.options
  var config = this.getConfig()

  // Setup a resolver to faux-resolve a request for "config"
  compiler.resolvers.normal.plugin("module", function(request, next) {
    if (request.request !== "config") {
      // This plugin only resolves for the explicit module "config"
      return next()
    }

    return next(null, {
      // No actual source is needed here
      path: path.join(options.dir, "default.js"),
      resolved: true
    })
  })

  // Setup a module-factory to direct the flow to the loader (
  // which outputs the configuration JSON)
  compiler.plugin("normal-module-factory", function(nmf) {
    nmf.plugin("after-resolve", function(data, next) {
      if (data.rawRequest !== "config") {
        // This plugin only resolves for the explicit module "config"
        return next(null, data)
      }

      // console.log(data)
      // NOTE: Parameters are passed via query string to the loader
      //       at `this.query`
      data.loaders = [
        path.join(__dirname, "./config-loader.js") + "?" +
        JSON.stringify(config)
      ]

      return next(null, data)
    })
  })
}
<commit_msg>Use merge instead of extend when merging configurations.<commit_after>var _ = require("lodash")
var path = require("path")

// Load configuration file
function loadFile(dir, filename) {
  if (filename == null) return {}
  filename = path.join(dir, filename)
  try {
    return require(filename)
  } catch(e) {
    return {}
  }
}

module.exports = Config
function Config(options) {
  this.options = options
  this._config = null
}

Config.prototype.getConfig = function () {
  if (!this._config) {
    this._config = _.merge({},
      loadFile(this.options.dir, "default"),
      loadFile(this.options.dir, process.env.NODE_ENV),
      loadFile(this.options.dir, "local")
    )
  }
  return this._config
}

Config.prototype.apply = function(compiler) {
  // Build the configuration object
  var options = this.options
  var config = this.getConfig()

  // Setup a resolver to faux-resolve a request for "config"
  compiler.resolvers.normal.plugin("module", function(request, next) {
    if (request.request !== "config") {
      // This plugin only resolves for the explicit module "config"
      return next()
    }

    return next(null, {
      // No actual source is needed here
      path: path.join(options.dir, "default.js"),
      resolved: true
    })
  })

  // Setup a module-factory to direct the flow to the loader (
  // which outputs the configuration JSON)
  compiler.plugin("normal-module-factory", function(nmf) {
    nmf.plugin("after-resolve", function(data, next) {
      if (data.rawRequest !== "config") {
        // This plugin only resolves for the explicit module "config"
        return next(null, data)
      }

      // console.log(data)
      // NOTE: Parameters are passed via query string to the loader
      //       at `this.query`
      data.loaders = [
        path.join(__dirname, "./config-loader.js") + "?" +
        JSON.stringify(config)
      ]

      return next(null, data)
    })
  })
}
<|endoftext|>