<commit_before>'use strict';

const chalk = require('chalk');
const Command = require('cmnd').Command;
const fs = require('fs');
const path = require('path');

const LocalGateway = require('../local_gateway.js');
const FunctionParser = require('faaslang').FunctionParser;
const config = require('../config.js');

function parseFileFromArg(arg) {
  if (arg.indexOf('file:') === 0) {
    let filename = arg.slice('file:'.length);
    let file;
    try {
      file = fs.readFileSync(filename);
      file = JSON.stringify({_base64: file.toString('base64')});
    } catch (e) {
      return new Error(`Can not read file: "${filename}"`);
    }
    return file;
  }
  return arg;
}

const lib = require('lib');

class __nomethod__Command extends Command {

  constructor() {

    super('*');

  }

  help() {

    return {
      description: 'Runs a StdLib function, i.e. "lib user.service[@ver]" (remote) or "lib ." (local)',
      args: [
        'all arguments converted to parameters'
      ],
      flags: {
        b: 'Execute as a Background Function',
        d: 'Specify debug mode (prints Gateway logs locally, response logs remotely)',
        t: 'Specify a Library Token to use manually',
        x: 'Unauthenticated - Execute without a token (overrides active token and -t flag)'
      },
      vflags: {
        '*': 'all verbose flags converted to named keyword parameters'
      }
    };

  }

  run(params, callback) {

    let debug = !!params.flags.d;
    let isLocal = false;
    let gateway;

    if (params.name.indexOf('.') === -1) {
      if (params.name.indexOf('/') > -1) {
        let names = params.name.split('/');
        if (names[1].indexOf('@') > -1) {
          names[1] = names[1].split('@');
          if (names[1].length > 1) {
            names[1][1] = names[1][1] && `[@${names[1][1]}]`;
          }
          names[1] = names[1].slice(0, 2).join('');
        }
        return callback(new Error(`Deprecated service path usage, please try \`lib ${names.join('.')}\` instead`));
      }
      return callback(new Error(`Command "${params.name}" does not exist.`));
    } else if (params.name[0] === '.') {
      isLocal = true;
      let pkg;
      let env;
      try {
        pkg = require(path.join(process.cwd(), 'package.json'));
      } catch (e) {
        if (!config.workspace()) {
          return callback(new Error([
            'You have not set up a StdLib workspace yet.',
            '\nTry running `lib init` in a directory that you would like to use as a workspace.'
          ].join('')));
        } else if (!config.location(2)) {
          return callback(
            new Error(
              [
                'There was an error parsing "package.json" from this directory.',
                '\nIt could be malformed, but it\'s more likely you\'re running',
                ' this command from the wrong directory.',
                '\n\nYour StdLib workspace is located in:',
                '\n  ' + config.workspace(),
                '\nAnd you\'re currently in:',
                '\n  ' + process.cwd(),
                '\n\nStdLib services are normally two levels down from your workspace directory.',
                '\n  (i.e. workspace/username/servicename)'
              ].join('')
            )
          );
        } else if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
          return callback(new Error(
            [
              'There was no "package.json" found in this directory, you may have deleted it.',
              '\nTry creating a new service (using `lib create`) from your StdLib workspace directory:',
              '\n  ' + config.workspace()
            ].join(''))
          );
        } else {
          return callback(new Error('Invalid "package.json" in this directory, your JSON syntax is likely malformed.'));
        }
      }
      try {
        env = require(path.join(process.cwd(), 'env.json'));
      } catch (e) {
        if (!config.workspace()) {
          return callback(new Error([
            'You have not set up a StdLib workspace yet.',
            '\nTry running `lib init` in a directory that you would like to use as a workspace.'
          ].join('')));
        } else if (!config.location(2)) {
          return callback(
            new Error(
              [
                'There was an error parsing "env.json" from this directory.',
                '\nIt could be malformed, but it\'s more likely you\'re running',
                ' this command from the wrong directory.',
                '\n\nYour StdLib workspace is located in:',
                '\n  ' + config.workspace(),
                '\nAnd you\'re currently in:',
                '\n  ' + process.cwd(),
                '\n\nStdLib services are normally two levels down from your workspace directory.',
                '\n  (i.e. workspace/username/servicename)'
              ].join('')
            )
          );
        } else if (!fs.existsSync(path.join(process.cwd(), 'env.json'))) {
          return callback(new Error(
            [
              'There was no "env.json" found in this directory, you may have deleted it.',
              '\nTry creating a new service (using `lib create`) from your StdLib workspace directory:',
              '\n  ' + config.workspace()
            ].join(''))
          );
        } else {
          return callback(new Error('Invalid "env.json" in this directory, your JSON syntax is likely malformed.'));
        }
      }
      if (pkg.stdlib.build === 'faaslang') {
        gateway = new LocalGateway({debug: debug});
        let fp = new FunctionParser();
        try {
          gateway.service(pkg.stdlib.name);
          gateway.environment(env.local || {});
          gateway.define(fp.load(process.cwd(), 'functions'));
        } catch (e) {
          return callback(e);
        }
        gateway.listen();
        params.name = `${pkg.stdlib.name.replace(/\//gi, '.')}[@local]${params.name.length > 1 ? params.name : ''}`;
      }
    }

    let args = params.args.slice().map(parseFileFromArg);
    let kwargs = Object.keys(params.vflags).reduce((kwargs, key) => {
      kwargs[key] = parseFileFromArg(params.vflags[key].join(' '));<commit_msg>Makes legacy a special case in local testing<commit_after>'use strict';

const chalk = require('chalk');
const Command = require('cmnd').Command;
const fs = require('fs');
const path = require('path');

const LocalGateway = require('../local_gateway.js');
const FunctionParser = require('faaslang').FunctionParser;
const config = require('../config.js');

function parseFileFromArg(arg) {
  if (arg.indexOf('file:') === 0) {
    let filename = arg.slice('file:'.length);
    let file;
    try {
      file = fs.readFileSync(filename);
      file = JSON.stringify({_base64: file.toString('base64')});
    } catch (e) {
      return new Error(`Can not read file: "${filename}"`);
    }
    return file;
  }
  return arg;
}

const lib = require('lib');

class __nomethod__Command extends Command {

  constructor() {

    super('*');

  }

  help() {

    return {
      description: 'Runs a StdLib function, i.e. "lib user.service[@ver]" (remote) or "lib ." (local)',
      args: [
        'all arguments converted to parameters'
      ],
      flags: {
        b: 'Execute as a Background Function',
        d: 'Specify debug mode (prints Gateway logs locally, response logs remotely)',
        t: 'Specify a Library Token to use manually',
        x: 'Unauthenticated - Execute without a token (overrides active token and -t flag)'
      },
      vflags: {
        '*': 'all verbose flags converted to named keyword parameters'
      }
    };

  }

  run(params, callback) {

    let debug = !!params.flags.d;
    let isLocal = false;
    let gateway;

    if (params.name.indexOf('.') === -1) {
      if (params.name.indexOf('/') > -1) {
        let names = params.name.split('/');
        if (names[1].indexOf('@') > -1) {
          names[1] = names[1].split('@');
          if (names[1].length > 1) {
            names[1][1] = names[1][1] && `[@${names[1][1]}]`;
          }
          names[1] = names[1].slice(0, 2).join('');
        }
        return callback(new Error(`Deprecated service path usage, please try \`lib ${names.join('.')}\` instead`));
      }
      return callback(new Error(`Command "${params.name}" does not exist.`));
    } else if (params.name[0] === '.') {
      isLocal = true;
      let pkg;
      let env;
      try {
        pkg = require(path.join(process.cwd(), 'package.json'));
      } catch (e) {
        if (!config.workspace()) {
          return callback(new Error([
            'You have not set up a StdLib workspace yet.',
            '\nTry running `lib init` in a directory that you would like to use as a workspace.'
          ].join('')));
        } else if (!config.location(2)) {
          return callback(
            new Error(
              [
                'There was an error parsing "package.json" from this directory.',
                '\nIt could be malformed, but it\'s more likely you\'re running',
                ' this command from the wrong directory.',
                '\n\nYour StdLib workspace is located in:',
                '\n  ' + config.workspace(),
                '\nAnd you\'re currently in:',
                '\n  ' + process.cwd(),
                '\n\nStdLib services are normally two levels down from your workspace directory.',
                '\n  (i.e. workspace/username/servicename)'
              ].join('')
            )
          );
        } else if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
          return callback(new Error(
            [
              'There was no "package.json" found in this directory, you may have deleted it.',
              '\nTry creating a new service (using `lib create`) from your StdLib workspace directory:',
              '\n  ' + config.workspace()
            ].join(''))
          );
        } else {
          return callback(new Error('Invalid "package.json" in this directory, your JSON syntax is likely malformed.'));
        }
      }
      try {
        env = require(path.join(process.cwd(), 'env.json'));
      } catch (e) {
        if (!config.workspace()) {
          return callback(new Error([
            'You have not set up a StdLib workspace yet.',
            '\nTry running `lib init` in a directory that you would like to use as a workspace.'
          ].join('')));
        } else if (!config.location(2)) {
          return callback(
            new Error(
              [
                'There was an error parsing "env.json" from this directory.',
                '\nIt could be malformed, but it\'s more likely you\'re running',
                ' this command from the wrong directory.',
                '\n\nYour StdLib workspace is located in:',
                '\n  ' + config.workspace(),
                '\nAnd you\'re currently in:',
                '\n  ' + process.cwd(),
                '\n\nStdLib services are normally two levels down from your workspace directory.',
                '\n  (i.e. workspace/username/servicename)'
              ].join('')
            )
          );
        } else if (!fs.existsSync(path.join(process.cwd(), 'env.json'))) {
          return callback(new Error(
            [
              'There was no "env.json" found in this directory, you may have deleted it.',
              '\nTry creating a new service (using `lib create`) from your StdLib workspace directory:',
              '\n  ' + config.workspace()
            ].join(''))
          );
        } else {
          return callback(new Error('Invalid "env.json" in this directory, your JSON syntax is likely malformed.'));
        }
      }
      if (pkg.stdlib.build !== 'legacy') {
        gateway = new LocalGateway({debug: debug});
        let fp = new FunctionParser();
        try {
          gateway.service(pkg.stdlib.name);
          gateway.environment(env.local || {});
          gateway.define(fp.load(process.cwd(), 'functions'));
        } catch (e) {
          return callback(e);
        }
        gateway.listen();
        params.name = `${pkg.stdlib.name.replace(/\//gi, '.')}[@local]${params.name.length > 1 ? params.name : ''}`;
      }
    }

    let args = params.args.slice().map(parseFileFromArg);
    let kwargs = Object.keys(params.vflags).reduce((kwargs, key) => {
      kwargs[key] = parseFileFromArg(params.vflags[key].join(' '));
{'fraction_non_alphanumeric': 0.1479932437866967, 'fraction_numerical': 0.004343279980696534, 'mean_word_length': 1.9380907372400755, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 13, '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': '6316552', 'n_tokens_mistral': 3550, 'n_tokens_neox': 3470, 'n_words': 1045}