<commit_before>var path = require('path');
var tools = require('../../api/tools');
var cliConfig = require('../../cli-config');
var userConfigModule = require('../../user/user-config');
var mkdirp = require('mkdirp');

var blueprintMetadataModule = {
    getBlueprints : function (blueprintType, blueprintName, vFlags, projectRootPath) {

        //1. Figure out the name and destination for the component to generate
        var nameMetadata = blueprintMetadataModule.extractNameData(blueprintName, blueprintType);

        //2. Get all files that are required fo this component + their metadata
        var blueprintTemplates = blueprintMetadataModule.getBlueprintFiles(blueprintType, nameMetadata, vFlags, projectRootPath);

        return blueprintTemplates;

    },

    logUserTemplateUsed : function (vFlags) {
        var userTemplate = tools.getvFlagPayload(tools.getvFlag(vFlags, '--template'));
        if (userTemplate) {
            if (userConfigModule.getUserTemplateFilesMap(userTemplate)) {
                tools.logInfo("Using template '" + userTemplate + "' from 'angular-cli-tools/config.json'");
            } else {
                tools.throwError("Template '" + userTemplate + "' not found in 'angular-cli-tools/config.json'");
            }
        }
    },

    getBlueprintFiles : function (blueprintType, nameMetadata, vFlags, projectRootPath) {

        projectRootPath = projectRootPath || tools.getProjectRootFolder();
        var userTemplate = tools.getvFlagPayload(tools.getvFlag(vFlags, '--template'));
        var cliConfigBlueprintFiles = cliConfig.templates.map[blueprintType];
        var cliConfigGeneratedFileNames = cliConfig.templates.names;
        var userBlueprintFiles = userConfigModule.getUserTemplateFilesMap(userTemplate, projectRootPath);
        var styleType = blueprintMetadataModule.determineStyleType(vFlags);
        var blueprintFiles = [];

        //default to angular-cli-tools list of files for a specific component
        var blueprintFileList = cliConfigBlueprintFiles;

        // if a user has provided a template and type to be generated is a complex one [component,route] use
        // the list of files in the user's template
        if (userTemplate && ['component', 'route'].indexOf(blueprintType) >= 0) {
            blueprintFileList = userBlueprintFiles;
        }

        // override the CLI blueprint files with files specified by user
        for (var blueprintFileType in blueprintFileList) {

            //ignore the description property if present as it is used for describing what the template does and serves no other purpose
            if (blueprintFileType != 'description') {

                var fileMetadata = null;

                //1. Try getting the file from templateMap in user's config.json file

                if (userBlueprintFiles && userBlueprintFiles[blueprintFileType]) {
                    fileMetadata = userConfigModule.getAbsolutePathToUserBlueprintFile(userBlueprintFiles[blueprintFileType], projectRootPath);
                }

                //1b. Style file is different in that it can have a different extension (css|scss|less?) so we need to pull the right template
                // if --css flag present default to component.css
                // if --scss flag present default to component.scss
                // if --less flag present default to component.less
                var templateFileName = cliConfigBlueprintFiles[blueprintFileType];
                if (blueprintFileType === 'style') {
                    templateFileName = blueprintMetadataModule.determineStyleFile(templateFileName, styleType);
                }

                //2. Try getting the file from local user templates in [project-root]/angular-cli-tools/templates/[file-name]
                if (!fileMetadata) {
                    fileMetadata = blueprintMetadataModule.getAbsolutePathToLocalBlueprintFile(templateFileName, projectRootPath);
                }

                //3. Lastly, if above fails get the default file from angular-cli-tools/bin/cli/templates (global installation)
                if (!fileMetadata) {
                    fileMetadata = blueprintMetadataModule.getAbsolutePathToCliBlueprintFile(templateFileName);
                }

                //4 Prune files that are in the templateMap (config) but template file can't be found anywhere in the project
                if (blueprintMetadataModule.isValidFile(fileMetadata)) {

                    fileMetadata.type = blueprintType;
                    fileMetadata.fileType = blueprintFileType;
                    fileMetadata.fileName = nameMetadata.name + cliConfigGeneratedFileNames[blueprintFileType];
                    fileMetadata.destinationDirectory = nameMetadata.destinationDirectory;

                    //get replacements for template placeholders

                    var templateData = tools.getTemplateReplacements(nameMetadata.name);
                    fileMetadata.variables = templateData.templateVariables;
                    fileMetadata.userDefinedValues = templateData.userDefinedValues;

                    //store name formats for displaying usage info after generation
                    fileMetadata.componentName = {
                        original : nameMetadata.name,
                        camelCase : tools.camelCase(nameMetadata.name),
                        pascalCase : tools.pascalCase(nameMetadata.name)
                    };

                    // style file is a little bit different in that it could have different
                    // file type ending .css / .scss so we check for it

                    if (blueprintFileType === 'style') {
                        fileMetadata.fileName += styleType;
                    }

                    //let component.ts file know which style file it is using
                    if (blueprintFileType === 'component') {
                        fileMetadata.variables.push('$styleFileType$');
                        fileMetadata.userDefinedValues.push(styleType);
                    }

                    blueprintFiles.push(fileMetadata);
                }
            }

        }
        return blueprintFiles;
    },
    //the user can add files to a template but they may not physically exist so remove them from the metadata if they were not found
    isValidFile : function (fileMetaData) {
        var fileLocation = fileMetaData.location.split(tools.getOSDirCharacter());
        return fileLocation[fileLocation.length - 1] != 'undefined';
    },

    determineStyleType : function (vFlags) {
        var styleType = 'scss'; //default
        styleType = tools.isvFlagPresent(vFlags, '--css') ? 'css' : styleType;
        styleType = tools.isvFlagPresent(vFlags, '--less') ? 'less' : styleType;
        return styleType;
    },

    determineStyleFile : function (templateFileName, styleExtension) {
        var fileParts = templateFileName.split('.');
        fileParts[fileParts.length - 1] = styleExtension;
        return fileParts.join('.');
    },

    /*
     * Name can be blank, regular name, or name with a relative path
     */
    extractNameData : function (blueprintName, blueprintType) {
        var nameData = {};
        if (blueprintName == './' || blueprintName == '.' || blueprintName == undefined || blueprintName == '') {
            nameData.name = tools.getCurrentDirectoryName();
            nameData.destinationDirectory = './';
        } else {

            //strip last char if '/' or '\'
            var nameEndsWithSlash = false;
            if (tools.pathEndsWithSlash(blueprintName)) {
                blueprintName = blueprintName.substring(0, blueprintName.length - 1);
                nameEndsWithSlash = true;
            }

            //split name on '/' or '\'
            var pathParts = blueprintName.split(/[\\/]+/);

            //add '.' if doesn't exist to make it a relative path
            if (pathParts[0] != '.') {
                pathParts.unshift('.');
            }

            //if last char '/' or '\' then component name is last folder name otherwise use last part of the path as name
            var componentName = nameEndsWithSlash ? pathParts[pathParts.length - 1] : pathParts.pop();

            nameData.name = componentName;
            nameData.destinationDirectory = pathParts.join('/') + '/';
        }

        if (['component', 'route'].indexOf(blueprintType) >= 0) {
            nameData.destinationDirectory += nameData.name + '/';
        }

        return nameData;
    },

    getAbsolutePathToLocalBlueprintFile : function (templateFileName, projectRootPath) {
        projectRootPath = projectRootPath || tools.getProjectRootFolder();
        var localTemplateLocation = path.resolve(projectRootPath, cliConfig.user.templates.location + templateFileName);

        var fileMetadata = {
            location : localTemplateLocation,
            label : tools.getRelativePathFromProjectRoot(localTemplateLocation, projectRootPath, '[project-root]/'),
            origin : 'local'
        };
        if (!tools.fileExists(localTemplateLocation)) {
            fileMetadata = null;
        }
        return fileMetadata;

    },

    getAbsolutePathToCliBlueprintFile : function (filePath) {
        return {
            location : cliConfig.appRoot + cliConfig.templates.root + filePath,
            label : '',
            origin : 'default'
        };

    }

};

module.exports = blueprintMetadataModule;

<commit_msg>adding 'flat' and custom file names<commit_after>var path = require('path');
var tools = require('../../api/tools');
var cliConfig = require('../../cli-config');
var userConfigModule = require('../../user/user-config');
var mkdirp = require('mkdirp');
var merge = require('merge');

var blueprintMetadataModule = {
    getBlueprints : function (blueprintType, blueprintName, vFlags, projectRootPath) {

        //1. Figure out the name and destination for the component to generate
        var nameMetadata = blueprintMetadataModule.extractNameData(blueprintName, blueprintType, vFlags);

        //2. Get all files that are required fo this component + their metadata
        var blueprintTemplates = blueprintMetadataModule.getBlueprintFiles(blueprintType, nameMetadata, vFlags, projectRootPath);

        return blueprintTemplates;

    },

    logUserTemplateUsed : function (vFlags) {
        var userTemplate = tools.getvFlagPayload(tools.getvFlag(vFlags, '--template'));
        if (userTemplate) {
            if (userConfigModule.getUserTemplateFilesMap(userTemplate)) {
                tools.logInfo("Using template '" + userTemplate + "' from 'angular-cli-tools/config.json'");
            } else {
                tools.throwError("Template '" + userTemplate + "' not found in 'angular-cli-tools/config.json'");
            }
        }
    },

    getBlueprintFiles : function (blueprintType, nameMetadata, vFlags, projectRootPath) {

        projectRootPath = projectRootPath || tools.getProjectRootFolder();
        var userTemplate = tools.getvFlagPayload(tools.getvFlag(vFlags, '--template'));
        var userBlueprintFiles = userConfigModule.getUserTemplateFilesMap(userTemplate, projectRootPath);
        var cliConfigGeneratedFileNames = merge({}, cliConfig.templates.names, userConfigModule.getProperty('fileNames.' + userTemplate, projectRootPath));
        var cliConfigBlueprintFiles = cliConfig.templates.map[blueprintType];
        var styleType = blueprintMetadataModule.determineStyleType(vFlags);
        var blueprintFiles = [];

        //default to angular-cli-tools list of files for a specific component
        var blueprintFileList = cliConfigBlueprintFiles;

        // if a user has provided a template and type to be generated is a complex one [component,route] use
        // the list of files in the user's template
        if (userTemplate && ['component', 'route'].indexOf(blueprintType) >= 0) {
            blueprintFileList = userBlueprintFiles;
        }

        // override the CLI blueprint files with files specified by user
        for (var blueprintFileType in blueprintFileList) {

            //ignore the description property if present as it is used for describing what the template does and serves no other purpose
            if (blueprintFileType != 'description') {

                var fileMetadata = null;

                //1. Try getting the file from templateMap in user's config.json file

                if (userBlueprintFiles && userBlueprintFiles[blueprintFileType]) {
                    fileMetadata = userConfigModule.getAbsolutePathToUserBlueprintFile(userBlueprintFiles[blueprintFileType], projectRootPath);
                }

                //1b. Style file is different in that it can have a different extension (css|scss|less?) so we need to pull the right template
                // if --css flag present default to component.css
                // if --scss flag present default to component.scss
                // if --less flag present default to component.less
                var templateFileName = cliConfigBlueprintFiles[blueprintFileType];
                if (blueprintFileType === 'style') {
                    templateFileName = blueprintMetadataModule.determineStyleFile(templateFileName, styleType);
                }

                //2. Try getting the file from local user templates in [project-root]/angular-cli-tools/templates/[file-name]
                if (!fileMetadata) {
                    fileMetadata = blueprintMetadataModule.getAbsolutePathToLocalBlueprintFile(templateFileName, projectRootPath);
                }

                //3. Lastly, if above fails get the default file from angular-cli-tools/bin/cli/templates (global installation)
                if (!fileMetadata) {
                    fileMetadata = blueprintMetadataModule.getAbsolutePathToCliBlueprintFile(templateFileName);
                }

                //4 Prune files that are in the templateMap (config) but template file can't be found anywhere in the project
                if (blueprintMetadataModule.isValidFile(fileMetadata)) {

                    fileMetadata.type = blueprintType;
                    fileMetadata.fileType = blueprintFileType;
                    fileMetadata.fileName = nameMetadata.name + cliConfigGeneratedFileNames[blueprintFileType];
                    fileMetadata.destinationDirectory = nameMetadata.destinationDirectory;

                    //get replacements for template placeholders

                    var templateData = tools.getTemplateReplacements(nameMetadata.name);
                    fileMetadata.variables = templateData.templateVariables;
                    fileMetadata.userDefinedValues = templateData.userDefinedValues;

                    //store name formats for displaying usage info after generation
                    fileMetadata.componentName = {
                        original : nameMetadata.name,
                        camelCase : tools.camelCase(nameMetadata.name),
                        pascalCase : tools.pascalCase(nameMetadata.name)
                    };

                    // style file is a little bit different in that it could have different
                    // file type ending .css / .scss so we check for it

                    if (blueprintFileType === 'style') {
                        fileMetadata.fileName += styleType;
                    }

                    //let component.ts file know which style file it is using
                    if (blueprintFileType === 'component') {
                        fileMetadata.variables.push('$styleFileType$');
                        fileMetadata.userDefinedValues.push(styleType);
                    }

                    blueprintFiles.push(fileMetadata);
                }
            }

        }
        return blueprintFiles;
    },
    //the user can add files to a template but they may not physically exist so remove them from the metadata if they were not found
    isValidFile : function (fileMetaData) {
        var fileLocation = fileMetaData.location.split(tools.getOSDirCharacter());
        return fileLocation[fileLocation.length - 1] != 'undefined';
    },

    determineStyleType : function (vFlags) {
        var styleType = 'scss'; //default
        styleType = tools.isvFlagPresent(vFlags, '--css') ? 'css' : styleType;
        styleType = tools.isvFlagPresent(vFlags, '--less') ? 'less' : styleType;
        return styleType;
    },

    determineStyleFile : function (templateFileName, styleExtension) {
        var fileParts = templateFileName.split('.');
        fileParts[fileParts.length - 1] = styleExtension;
        return fileParts.join('.');
    },

    /*
     * Name can be blank, regular name, or name with a relative path
     */
    extractNameData : function (blueprintName, blueprintType, vFlags) {
        var isFlat = tools.isvFlagPresent(vFlags, '--flat')

        var nameData = {};
        if (blueprintName == './' || blueprintName == '.' || blueprintName == undefined || blueprintName == '') {
            nameData.name = tools.getCurrentDirectoryName();
            nameData.destinationDirectory = './';
        } else {

            //strip last char if '/' or '\'
            var nameEndsWithSlash = false;
            if (tools.pathEndsWithSlash(blueprintName)) {
                blueprintName = blueprintName.substring(0, blueprintName.length - 1);
                nameEndsWithSlash = true;
            }

            //split name on '/' or '\'
            var pathParts = blueprintName.split(/[\\/]+/);

            //add '.' if doesn't exist to make it a relative path
            if (pathParts[0] != '.') {
                pathParts.unshift('.');
            }

            //if last char '/' or '\' then component name is last folder name otherwise use last part of the path as name
            var componentName = nameEndsWithSlash ? pathParts[pathParts.length - 1] : pathParts.pop();

            nameData.name = componentName;
            nameData.destinationDirectory = pathParts.join('/') + '/';
        }

        if (['component', 'route'].indexOf(blueprintType) >= 0 && !isFlat) {
            nameData.destinationDirectory += nameData.name + '/';
        }

        return nameData;
    },

    getAbsolutePathToLocalBlueprintFile : function (templateFileName, projectRootPath) {
        projectRootPath = projectRootPath || tools.getProjectRootFolder();
        var localTemplateLocation = path.resolve(projectRootPath, cliConfig.user.templates.location + templateFileName);

        var fileMetadata = {
            location : localTemplateLocation,
            label : tools.getRelativePathFromProjectRoot(localTemplateLocation, projectRootPath, '[project-root]/'),
            origin : 'local'
        };
        if (!tools.fileExists(localTemplateLocation)) {
            fileMetadata = null;
        }
        return fileMetadata;

    },

    getAbsolutePathToCliBlueprintFile : function (filePath) {
        return {
            location : cliConfig.appRoot + cliConfig.templates.root + filePath,
            label : '',
            origin : 'default'
        };

    }

};

module.exports = blueprintMetadataModule;

<|endoftext|>


<commit_before>/** @babel */

import {GitRepositoryAsync} from 'atom'
import path from 'path'
import fs from 'fs-plus'
import {Point} from 'atom'
import GitService from '../lib/git-service'
import GitStore from '../lib/git-store'
import CommitBoxViewModel from '../lib/commit-box-view-model'
import {SummaryPreferredLength} from '../lib/commit-box-view-model'
import {copyRepository} from './helpers'
import {beforeEach, it} from './async-spec-helpers'

function stageFile (repoPath, filePath) {
  return GitRepositoryAsync.Git.Repository
    .open(repoPath)
    .then(repo => repo.openIndex())
    .then(index => {
      index.addByPath(filePath)
      return index.write()
    })
}

describe('CommitBoxViewModel', () => {
  let viewModel
  let gitStore
  let gitService
  let repoPath

  beforeEach(async () => {
    repoPath = copyRepository()

    gitService = new GitService(GitRepositoryAsync.open(repoPath))
    gitStore = new GitStore(gitService)
    await gitStore.loadFromGit()

    viewModel = new CommitBoxViewModel(gitStore)
  })

  describe('::getBranchName', () => {
    it('returns the current branch', () => {
      expect(viewModel.getBranchName()).toBe('master')
    })
  })

  describe('::commit', () => {
    it('commits the staged changes', async () => {
      const newFileName = 'new-file.txt'
      const newFile = path.join(repoPath, newFileName)
      fs.writeFileSync(newFile, 'my fav file')

      let statuses = await gitService.getStatuses()
      expect(statuses[newFileName]).not.toBeUndefined()

      await stageFile(repoPath, newFileName)
      await viewModel.commit('hey there')

      statuses = await gitService.getStatuses()
      expect(statuses[newFileName]).toBeUndefined()
    })
  })

  describe('.calculateRemainingCharacters', () => {
    const summary = 'hey kids!'
    const description = 'Version control is good and good for you!'
    const msg = `${summary}\n\n${description}`

    describe('when the summary is being edited', () => {
      it('counts down from 50', () => {
        const remaining = viewModel.calculateRemainingCharacters(msg, new Point(0, 0))
        expect(remaining).toBe(SummaryPreferredLength - summary.length)
      })
    })

    describe('when the description is being edited', () => {
      it('is infinite', () => {
        const msg = 'hey kids!\n\nVersion control is good and good for you!'
        const remaining = viewModel.calculateRemainingCharacters(msg, new Point(3, 0))
        expect(isFinite(remaining)).toBe(false)
      })
    })
  })
})
<commit_msg>Test it.<commit_after>/** @babel */

import {GitRepositoryAsync} from 'atom'
import path from 'path'
import fs from 'fs-plus'
import {Point} from 'atom'
import GitService from '../lib/git-service'
import GitStore from '../lib/git-store'
import CommitBoxViewModel from '../lib/commit-box-view-model'
import {SummaryPreferredLength} from '../lib/commit-box-view-model'
import {copyRepository} from './helpers'
import {beforeEach, it} from './async-spec-helpers'

function stageFile (repoPath, filePath) {
  return GitRepositoryAsync.Git.Repository
    .open(repoPath)
    .then(repo => repo.openIndex())
    .then(index => {
      index.addByPath(filePath)
      return index.write()
    })
}

describe('CommitBoxViewModel', () => {
  let viewModel
  let gitStore
  let gitService
  let repoPath

  beforeEach(async () => {
    repoPath = copyRepository()

    gitService = new GitService(GitRepositoryAsync.open(repoPath))
    gitStore = new GitStore(gitService)
    await gitStore.loadFromGit()

    viewModel = new CommitBoxViewModel(gitStore)
  })

  describe('::getBranchName', () => {
    it('returns the current branch', () => {
      expect(viewModel.getBranchName()).toBe('master')
    })
  })

  describe('::commit', () => {
    const newFileName = 'new-file.txt'

    beforeEach(async () => {
      const newFile = path.join(repoPath, newFileName)
      fs.writeFileSync(newFile, 'my fav file')

      let statuses = await gitService.getStatuses()
      expect(statuses[newFileName]).not.toBeUndefined()
    })

    it('commits the staged changes', async () => {
      await stageFile(repoPath, newFileName)

      await viewModel.commit('hey there')

      const statuses = await gitService.getStatuses()
      expect(statuses[newFileName]).toBeUndefined()
    })

    it("throws an error if there's no commit message", async () => {
      let error = null
      try {
        await viewModel.commit('')
      } catch (e) {
        error = e
      }

      expect(error.name).toBe(CommitBoxViewModel.NoMessageErrorName())
    })

    it('throws an error if there are no staged changes', async () => {
      let error = null
      try {
        await viewModel.commit('hey there')
      } catch (e) {
        error = e
      }

      expect(error.name).toBe(CommitBoxViewModel.NoStagedFilesErrorName())
    })
  })

  describe('.calculateRemainingCharacters', () => {
    const summary = 'hey kids!'
    const description = 'Version control is good and good for you!'
    const msg = `${summary}\n\n${description}`

    describe('when the summary is being edited', () => {
      it('counts down from 50', () => {
        const remaining = viewModel.calculateRemainingCharacters(msg, new Point(0, 0))
        expect(remaining).toBe(SummaryPreferredLength - summary.length)
      })
    })

    describe('when the description is being edited', () => {
      it('is infinite', () => {
        const msg = 'hey kids!\n\nVersion control is good and good for you!'
        const remaining = viewModel.calculateRemainingCharacters(msg, new Point(3, 0))
        expect(isFinite(remaining)).toBe(false)
      })
    })
  })
})
<|endoftext|>


<commit_before>export default {
  name: 'entity-labels',
  configure(config) {
    config.addLabel('book', 'Book')
    config.addLabel('journal-article', 'Journal Article')

    // book labels
    config.addLabel('authors', 'Authors')
    config.addLabel('editors', 'Editors')
    config.addLabel('chapterTitle', 'Chapter Title')
    config.addLabel('articleTitle', 'Article Title')
    config.addLabel('source', 'Source')
    config.addLabel('edition', 'Edition')
    config.addLabel('publisherLoc', 'Publisher Location')
    config.addLabel('publisherName', 'Publisher Name')
    config.addLabel('year', 'Year')
    config.addLabel('month', 'Month')
    config.addLabel('day', 'Day')
    config.addLabel('fpage', 'First Page')
    config.addLabel('lpage', 'Last Page')
    config.addLabel('pageRange', 'Page Range')
    config.addLabel('elocationId', 'E-Location ID')
    config.addLabel('doi', 'DOI')
    config.addLabel('isbn', 'ISBN')
    config.addLabel('pmid', 'PubMed ID')
    // person labels
    config.addLabel('orcid', 'ORCID')
    config.addLabel('givenNames', 'Given names')
    config.addLabel('surname', 'Surname')
    config.addLabel('prefix', 'Prefix')
    config.addLabel('suffix', 'Suffix')
    config.addLabel('affiliations', 'Affiliations')
    // organisation labels
    config.addLabel('name', 'Name')

    config.addLabel('edit-book', 'Edit Book')
    config.addLabel('add-book', 'Add Book')
    config.addLabel('edit-journal-article', 'Edit Journal Article')
    config.addLabel('add-journal-article', 'Add Journal Article')
    config.addLabel('add-person', 'Add Person')
    config.addLabel('edit-person', 'Edit Person')
    config.addLabel('add-organisation', 'Add Organisation')
    config.addLabel('edit-organisation', 'Edit Organisation')

    config.addLabel('edit-authors', 'Edit Authors')
    config.addLabel('edit-editors', 'Edit Editors')
    config.addLabel('edit-references', 'Edit References')
    config.addLabel('edit-affiliations', 'Edit Affiliations')

    config.addLabel('create-book', 'Create Book')
    config.addLabel('create-journal-article', 'Create Journal Article')
    config.addLabel('create-person', 'Create Person')
    config.addLabel('create-organisation', 'Create Organisation')
  }
}
<commit_msg>Missing labels.<commit_after>export default {
  name: 'entity-labels',
  configure(config) {
    config.addLabel('book', 'Book')
    config.addLabel('journal-article', 'Journal Article')

    // book labels
    config.addLabel('authors', 'Authors')
    config.addLabel('editors', 'Editors')
    config.addLabel('chapterTitle', 'Chapter Title')
    config.addLabel('articleTitle', 'Article Title')
    config.addLabel('source', 'Source')
    config.addLabel('edition', 'Edition')
    config.addLabel('publisherLoc', 'Publisher Location')
    config.addLabel('publisherName', 'Publisher Name')
    config.addLabel('year', 'Year')
    config.addLabel('month', 'Month')
    config.addLabel('day', 'Day')
    config.addLabel('fpage', 'First Page')
    config.addLabel('lpage', 'Last Page')
    config.addLabel('pageRange', 'Page Range')
    config.addLabel('elocationId', 'E-Location ID')
    config.addLabel('doi', 'DOI')
    config.addLabel('isbn', 'ISBN')
    config.addLabel('pmid', 'PubMed ID')
    // person labels
    config.addLabel('orcid', 'ORCID')
    config.addLabel('givenNames', 'Given names')
    config.addLabel('surname', 'Surname')
    config.addLabel('prefix', 'Prefix')
    config.addLabel('suffix', 'Suffix')
    config.addLabel('affiliations', 'Affiliations')
    // organisation labels
    config.addLabel('name', 'Name')
    config.addLabel('division1', 'Division 1 (Department)')
    config.addLabel('division2', 'Division 2')
    config.addLabel('division3', 'Division 2')
    config.addLabel('street', 'Address Line 1 (Street)')
    config.addLabel('addressComplements', 'Address Line 2 (Complements)')
    config.addLabel('city', 'City')
    config.addLabel('state', 'State')
    config.addLabel('postalCode', 'Postal Code')
    config.addLabel('country', 'Country')
    config.addLabel('phone', 'Phone')
    config.addLabel('fax', 'Fax')
    config.addLabel('email', 'Email')
    config.addLabel('uri', 'Website')

    config.addLabel('edit-book', 'Edit Book')
    config.addLabel('add-book', 'Add Book')
    config.addLabel('edit-journal-article', 'Edit Journal Article')
    config.addLabel('add-journal-article', 'Add Journal Article')
    config.addLabel('add-person', 'Add Person')
    config.addLabel('edit-person', 'Edit Person')
    config.addLabel('add-organisation', 'Add Organisation')
    config.addLabel('edit-organisation', 'Edit Organisation')

    config.addLabel('edit-authors', 'Edit Authors')
    config.addLabel('edit-editors', 'Edit Editors')
    config.addLabel('edit-references', 'Edit References')
    config.addLabel('edit-affiliations', 'Edit Affiliations')

    config.addLabel('create-book', 'Create Book')
    config.addLabel('create-journal-article', 'Create Journal Article')
    config.addLabel('create-person', 'Create Person')
    config.addLabel('create-organisation', 'Create Organisation')
  }
}
<|endoftext|>


<commit_before>CloudPebble.GitHub = (function() {
    var github_template = null;

    var create_repo = function(new_repo) {
        var prompt = $('#github-new-repo-prompt').modal();
        var repo_name = new_repo.match(/^(?:https?:\/\/|git@|git:\/\/)?(?:www\.)?github\.com[\/:]([\w.-]+)\/([\w.-]+?)(?:\.git|\/|$)/)[2];
        prompt.find('#github-new-repo').val(repo_name);
        prompt.find('.alert').removeClass('alert-error').addClass('alert-warning').text(gettext("That repo does not exist. Would you like to create it?"));
    };

    var show_github_pane = function() {
        if(!USER_SETTINGS.github) return;
        CloudPebble.Sidebar.SuspendActive();
        if(CloudPebble.Sidebar.Restore("github")) {
            return;
        }
        var pane = github_template.clone();
        var show_alert = function(type, message) {
            pane.find('.alert').removeClass('hide alert-error alert-warning alert-info alert-success').addClass('alert-' + type).text(message);
        };
        var clear_alert = function() {
            pane.find('.alert').addClass('hide');
        };
        var disable_all = function() {
            pane.find('input, button').attr('disabled', 'disabled');
        };
        var enable_all = function() {
            pane.find('input, button').removeAttr('disabled');
        };
        var disable_needy = function() {
            pane.find('.github-actions').find('input, button').attr('disabled', 'disabled');
        };
        var enable_needy = function() {
            pane.find('.github-actions').find('input, button').removeAttr('disabled');
        };

        pane.find('#github-repo-form').submit(function(e) {
            e.preventDefault();
            clear_alert();
            var new_repo = pane.find('#github-repo').val();
            var repo_branch = pane.find('#github-branch').val();
            var auto_pull = pane.find('#github-repo-hook').val() == '1';
            var auto_build = pane.find('#github-repo-build').val() == '1';

            if(repo_branch == null || repo_branch.length == 0) {
                repo_branch = "master";
            }

            if((new_repo === CloudPebble.ProjectInfo.github.repo || !new_repo && !CloudPebble.ProjectInfo.github.repo) &&
                (repo_branch === CloudPebble.ProjectInfo.github.branch || !repo_branch && !CloudPebble.ProjectInfo.github.branch) &&
                auto_pull === CloudPebble.ProjectInfo.github.auto_pull && auto_build === CloudPebble.ProjectInfo.github.auto_build) {
                show_alert('success', "Updated repo (nothing changed).");
                return;
            }
            disable_all();
            Ajax.Ajax('/ide/project/' + PROJECT_ID + '/github/repo', {repo: new_repo, auto_pull: auto_pull ? '1' : '0', auto_build: auto_build ? '1' : '0', branch: repo_branch}).then(function(data) {
                enable_all();
                if(data.updated) {
                    show_alert('success', gettext("Updated repo."));
                    CloudPebble.ProjectInfo.github.repo = new_repo;
                    CloudPebble.ProjectInfo.github.branch = repo_branch;
                    CloudPebble.ProjectInfo.github.auto_pull = auto_pull;
                    CloudPebble.ProjectInfo.github.auto_build = auto_build;
                    return;
                }
                if(!data.exists) {
                    disable_needy();
                    create_repo(new_repo);
                    return;
                }
                if(!data.access) {
                    throw gettext("You don't have access to that repository.")
                }
            }).catch(function(error) {
                disable_needy();
                show_alert('error', error);
            });
        });

        pane.find('#github-repo').on('input', function() {
            var new_repo = $(this).val();
            if(new_repo !== CloudPebble.ProjectInfo.github.repo || !new_repo) {
                disable_needy();
            } else {
                disable_needy();
            }
        });
        if(CloudPebble.ProjectInfo.github.repo) {
            pane.find('#github-repo').val(CloudPebble.ProjectInfo.github.repo);
            enable_needy();
        }
        if(CloudPebble.ProjectInfo.github.branch) {
            pane.find('#github-branch').val(CloudPebble.ProjectInfo.github.branch);
        }
        pane.find('#github-repo-hook').val(CloudPebble.ProjectInfo.github.auto_pull ? '1' : '0');
        pane.find('#github-repo-build').val(CloudPebble.ProjectInfo.github.auto_build ? '1' : '0');

        var prompt = $('#github-new-repo-prompt');
        prompt.find('form').submit(function(e) {
            e.preventDefault();
            var new_repo = $('#github-new-repo').val();
            if(new_repo.replace(/\s/g, '') === '') {
                prompt.find('.alert').removeClass('alert-warning').addClass('alert-error').text(gettext("You must provide a repo URL."));
            }
            var description = $('#github-repo-description').val();
            prompt.find('input, button').prop('disabled', true);
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/repo/create', {repo: new_repo, description: description}).then(function(data) {
                pane.find('#github-repo').val(data.repo);
                CloudPebble.ProjectInfo.github.repo = new_repo;
                pane.find('#github-branch').val(data.branch);
                CloudPebble.ProjectInfo.github.branch = data.branch;
                prompt.modal('hide');
                enable_all();
            }).catch(function(error) {
                prompt.find('.alert').removeClass('alert-warning').addClass('alert-error').text(error);
            }).finally(function() {
                prompt.find('input, button').prop('disabled', false);
            });
        });
        pane.find('#github-push-btn').click(function() {
            $('#github-commit-prompt').modal().find('.alert, .progress').addClass('hide');
            $('#github-commit-prompt').find('input[type=text], textarea').val('');
            $('#github-commit-prompt').focus();
        });

        pane.find('#github-pull-btn').click(function() {
            var prompt = $('#github-pull-prompt').modal();
            prompt.find(".running").addClass('hide');
            prompt.find(".close, .dire-warning, .modal-footer").removeClass("hide");
        });

        var poll_commit_status = function(task_id) {
            return Ajax.Get('/ide/task/' + task_id).then(function(data) {
                var state = data.state;
                if(state.status == 'SUCCESS' || state.status == 'FAILURE') {
                    $('#github-commit-prompt').find('.progress').addClass('hide');
                    $('#github-commit-prompt').modal('hide');
                    if(state.status == 'SUCCESS') {
                        if(state.result)
                            show_alert('success', "Made new commit.");
                        else
                            show_alert('success', "Nothing to commit.");
                    } else {
                        show_alert('error', 'Error: ' + state.result);
                    }
                } else {
                    return Promise.delay(1000).then(function() {
                        return poll_commit_status(task_id);
                    });
                }
            });
        };

        var poll_pull_status = function(task_id) {
            return Ajax.Get('/ide/task/' + task_id).then(function(data) {
                var state = data.state;
                if(state.status == 'SUCCESS' || state.status == 'FAILURE') {
                    var prompt = $('#github-pull-prompt').modal('hide');
                    if(state.status == 'SUCCESS') {
                        if(state.result) {
                            show_alert('success', gettext("Pulled successfully."));
                            alert(gettext("Pull completed successfully."));
                            // *NASTY HACK: Make sure it doesn't think we have unsaved files, thereby
                            // preventing page reload.
                            CloudPebble.Editor.GetUnsavedFiles = function() { return 0; };
                            window.location.reload(true);
                        } else {
                            show_alert('success', gettext("Pull completed: Nothing to pull."));
                        }
                    } else {
                        show_alert('error', interpolate(gettext('Error: %s'), [state.result]));
                    }
                } else {
                    return Promise.delay(1000).then(function() {
                        return poll_pull_status(task_id);
                    });
                }
            });
        };

        $('#github-commit-prompt form').submit(function(e) {
            e.preventDefault();
            var commit_summary = $('#github-commit-summary').val();
            var commit_description = $('#github-commit-description').val();
            if(commit_summary.replace(/\s/g, '') === '') {
                $('#github-commit-prompt form').find('.alert').addClass('alert-error').removeClass('hide').text(gettext("You must provide a commit summary."));
                return;
            }
            var commit_message = commit_summary;
            if(commit_description !== '') {
                commit_message += "\n\n" + commit_description.replace("\r\n", "\n");
            }
            disable_all();
            $('#github-commit-prompt').find('input, textarea, button').attr('disabled', 'disabled');
            $('#github-commit-prompt').find('.progress').removeClass('hide');
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/commit', {commit_message: commit_message}).then(function(data) {
                return poll_commit_status(data.task_id);
            }).catch(function(error) {
                $('#github-commit-prompt form').find('.alert').addClass('alert-error').removeClass('hide').text(error);
            }).finally(function() {
                enable_all();
                $('#github-commit-prompt').find('input, textarea, button').removeAttr('disabled');
            });
            ga('send', 'event', 'github', 'push');
        });

        $('#github-pull-prompt-confirm').click(function() {
            disable_all();
            var prompt = $('#github-pull-prompt');
            prompt.find(".close, .dire-warning, .modal-footer").addClass("hide");
            prompt.find(".running").removeClass('hide');
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/pull').then(function(data) {
                return poll_pull_status(data.task_id);
            }).catch(function(error) {
                show_alert('error', interpolate(gettext("Pull failed: %s"), [error]));
            }).finally(function() {
                enable_all();
            });
            ga('send', 'event', 'github', 'pull');
        });

        CloudPebble.Sidebar.SetActivePane(pane, 'github');
    };

    return {
        Init: function() {
            github_template = $('#github-template').remove().removeClass('hide');
            if(!USER_SETTINGS.github) {
                $('#sidebar-pane-github').addClass('disabled');
                CloudPebble.Sidebar.SetPopover('github', '', gettext('GitHub integration can be enabled in your user settings by linking a GitHub account.'))
            }
        },
        Show: function() {
            show_github_pane();
        }
    };
})();
<commit_msg>Fixed logic errors in github.js<commit_after>CloudPebble.GitHub = (function() {
    var github_template = null;

    var create_repo = function(new_repo) {
        var prompt = $('#github-new-repo-prompt').modal();
        var repo_name = new_repo.match(/^(?:https?:\/\/|git@|git:\/\/)?(?:www\.)?github\.com[\/:]([\w.-]+)\/([\w.-]+?)(?:\.git|\/|$)/)[2];
        prompt.find('#github-new-repo').val(repo_name);
        prompt.find('.alert').removeClass('alert-error').addClass('alert-warning').text(gettext("That repo does not exist. Would you like to create it?"));
    };

    var show_github_pane = function() {
        if(!USER_SETTINGS.github) return;
        CloudPebble.Sidebar.SuspendActive();
        if(CloudPebble.Sidebar.Restore("github")) {
            return;
        }
        var pane = github_template.clone();
        var show_alert = function(type, message) {
            pane.find('.alert').removeClass('hide alert-error alert-warning alert-info alert-success').addClass('alert-' + type).text(message);
        };
        var clear_alert = function() {
            pane.find('.alert').addClass('hide');
        };
        var disable_all = function() {
            pane.find('input, button').attr('disabled', 'disabled');
        };
        var enable_all = function() {
            pane.find('input, button').removeAttr('disabled');
        };
        var disable_needy = function() {
            pane.find('.github-actions').find('input, button').attr('disabled', 'disabled');
        };
        var enable_needy = function() {
            pane.find('.github-actions').find('input, button').removeAttr('disabled');
        };

        pane.find('#github-repo-form').submit(function(e) {
            e.preventDefault();
            clear_alert();
            var new_repo = pane.find('#github-repo').val();
            var repo_branch = pane.find('#github-branch').val();
            var auto_pull = pane.find('#github-repo-hook').val() == '1';
            var auto_build = pane.find('#github-repo-build').val() == '1';

            if(repo_branch == null || repo_branch.length == 0) {
                repo_branch = "master";
            }

            if((new_repo === CloudPebble.ProjectInfo.github.repo || !new_repo && !CloudPebble.ProjectInfo.github.repo) &&
                (repo_branch === CloudPebble.ProjectInfo.github.branch || !repo_branch && !CloudPebble.ProjectInfo.github.branch) &&
                auto_pull === CloudPebble.ProjectInfo.github.auto_pull && auto_build === CloudPebble.ProjectInfo.github.auto_build) {
                show_alert('success', "Updated repo (nothing changed).");
                return;
            }
            disable_all();
            var data = {
                repo: new_repo,
                auto_pull: auto_pull ? '1' : '0',
                auto_build: auto_build ? '1' : '0',
                branch: repo_branch
            };
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/repo', data).then(function(data) {
                enable_all();
                if(data.updated) {
                    show_alert('success', gettext("Updated repo."));
                    CloudPebble.ProjectInfo.github.repo = new_repo;
                    CloudPebble.ProjectInfo.github.branch = repo_branch;
                    CloudPebble.ProjectInfo.github.auto_pull = auto_pull;
                    CloudPebble.ProjectInfo.github.auto_build = auto_build;
                    return;
                }
                if(!data.exists) {
                    disable_needy();
                    create_repo(new_repo);
                    return;
                }
                if(!data.access) {
                    throw new Error(gettext("You don't have access to that repository."));
                }
            }).catch(function(error) {
                enable_all();
                disable_needy();
                show_alert('error', error.message);
            });
        });

        pane.find('#github-repo').on('input', function() {
            var new_repo = $(this).val();
            if(new_repo !== CloudPebble.ProjectInfo.github.repo || !new_repo) {
                disable_needy();
            } else {
                disable_needy();
            }
        });
        if(CloudPebble.ProjectInfo.github.repo) {
            pane.find('#github-repo').val(CloudPebble.ProjectInfo.github.repo);
            enable_needy();
        }
        if(CloudPebble.ProjectInfo.github.branch) {
            pane.find('#github-branch').val(CloudPebble.ProjectInfo.github.branch);
        }
        pane.find('#github-repo-hook').val(CloudPebble.ProjectInfo.github.auto_pull ? '1' : '0');
        pane.find('#github-repo-build').val(CloudPebble.ProjectInfo.github.auto_build ? '1' : '0');

        var prompt = $('#github-new-repo-prompt');
        prompt.find('form').submit(function(e) {
            e.preventDefault();
            var new_repo = $('#github-new-repo').val();
            if(new_repo.replace(/\s/g, '') === '') {
                prompt.find('.alert').removeClass('alert-warning').addClass('alert-error').text(gettext("You must provide a repo URL."));
            }
            var description = $('#github-repo-description').val();
            prompt.find('input, button').prop('disabled', true);
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/repo/create', {repo: new_repo, description: description}).then(function(data) {
                pane.find('#github-repo').val(data.repo);
                CloudPebble.ProjectInfo.github.repo = new_repo;
                pane.find('#github-branch').val(data.branch);
                CloudPebble.ProjectInfo.github.branch = data.branch;
                prompt.modal('hide');
                enable_all();
            }).catch(function(error) {
                prompt.find('.alert').removeClass('alert-warning').addClass('alert-error').text(error);
            }).finally(function() {
                prompt.find('input, button').prop('disabled', false);
            });
        });
        pane.find('#github-push-btn').click(function() {
            $('#github-commit-prompt').modal().find('.alert, .progress').addClass('hide');
            $('#github-commit-prompt').find('input[type=text], textarea').val('');
            $('#github-commit-prompt').focus();
        });

        pane.find('#github-pull-btn').click(function() {
            var prompt = $('#github-pull-prompt').modal();
            prompt.find(".running").addClass('hide');
            prompt.find(".close, .dire-warning, .modal-footer").removeClass("hide");
        });

        var poll_commit_status = function(task_id) {
            return Ajax.Get('/ide/task/' + task_id).then(function(data) {
                var state = data.state;
                if(state.status == 'SUCCESS' || state.status == 'FAILURE') {
                    $('#github-commit-prompt').find('.progress').addClass('hide');
                    $('#github-commit-prompt').modal('hide');
                    if(state.status == 'SUCCESS') {
                        if(state.result)
                            show_alert('success', "Made new commit.");
                        else
                            show_alert('success', "Nothing to commit.");
                    } else {
                        show_alert('error', 'Error: ' + state.result);
                    }
                } else {
                    return Promise.delay(1000).then(function() {
                        return poll_commit_status(task_id);
                    });
                }
            });
        };

        var poll_pull_status = function(task_id) {
            return Ajax.Get('/ide/task/' + task_id).then(function(data) {
                var state = data.state;
                if(state.status == 'SUCCESS' || state.status == 'FAILURE') {
                    if(state.status == 'SUCCESS') {
                        if(state.result) {
                            show_alert('success', gettext("Pulled successfully."));
                            alert(gettext("Pull completed successfully."));
                            // *NASTY HACK: Make sure it doesn't think we have unsaved files, thereby
                            // preventing page reload.
                            CloudPebble.Editor.GetUnsavedFiles = function() { return 0; };
                            window.location.reload(true);
                        } else {
                            show_alert('success', gettext("Pull completed: Nothing to pull."));
                        }
                    } else {
                        show_alert('error', interpolate(gettext('Error: %s'), [state.result]));
                    }
                } else {
                    return Promise.delay(1000).then(function() {
                        return poll_pull_status(task_id);
                    });
                }
            });
        };

        $('#github-commit-prompt form').submit(function(e) {
            e.preventDefault();
            var commit_summary = $('#github-commit-summary').val();
            var commit_description = $('#github-commit-description').val();
            if(commit_summary.replace(/\s/g, '') === '') {
                $('#github-commit-prompt form').find('.alert').addClass('alert-error').removeClass('hide').text(gettext("You must provide a commit summary."));
                return;
            }
            var commit_message = commit_summary;
            if(commit_description !== '') {
                commit_message += "\n\n" + commit_description.replace("\r\n", "\n");
            }
            disable_all();
            $('#github-commit-prompt').find('input, textarea, button').attr('disabled', 'disabled');
            $('#github-commit-prompt').find('.progress').removeClass('hide');
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/commit', {commit_message: commit_message}).then(function(data) {
                return poll_commit_status(data.task_id);
            }).catch(function(error) {
                $('#github-commit-prompt form').find('.alert').addClass('alert-error').removeClass('hide').text(error);
            }).finally(function() {
                enable_all();
                $('#github-commit-prompt').find('input, textarea, button').removeAttr('disabled');
            });
            ga('send', 'event', 'github', 'push');
        });

        $('#github-pull-prompt-confirm').click(function() {
            disable_all();
            var prompt = $('#github-pull-prompt');
            prompt.find(".close, .dire-warning, .modal-footer").addClass("hide");
            prompt.find(".running").removeClass('hide');
            Ajax.Post('/ide/project/' + PROJECT_ID + '/github/pull').then(function(data) {
                return poll_pull_status(data.task_id);
            }).catch(function(error) {
                show_alert('error', interpolate(gettext("Pull failed: %s"), [error]));
            }).finally(function() {
                enable_all();
                prompt.modal('hide');
            });
            ga('send', 'event', 'github', 'pull');
        });

        CloudPebble.Sidebar.SetActivePane(pane, 'github');
    };

    return {
        Init: function() {
            github_template = $('#github-template').remove().removeClass('hide');
            if(!USER_SETTINGS.github) {
                $('#sidebar-pane-github').addClass('disabled');
                CloudPebble.Sidebar.SetPopover('github', '', gettext('GitHub integration can be enabled in your user settings by linking a GitHub account.'))
            }
        },
        Show: function() {
            show_github_pane();
        }
    };
})();
<|endoftext|>


<commit_before>// Context is phantom

var system = require('system');
var webpage = require('webpage');
var fs = require('fs');
var [
  ,
  address, // URL to evaluate
  configFilePath, // Configuration JSON file.
  outputDir // Directory to write output to.
] = system.args;
var dir = fs.workingDirectory

// Run time configurations.
var config;
try {
  config = JSON.parse(fs.read(configFilePath));
}
catch (err) {
  quitPhantom(err);
}

// Create the QtRuntimeObject with the desired configuration. This is the
// PhantomJS controller object.
var page = webpage.create(config.phantomjs);

/**
 * Logs the reason for exit; exits Phantom.
 */
function quitPhantom (reason) {
  console.log('phantom_evaluator' + (reason && (': ' + reason) || ''));
  if (stream) {
    stream.close();
  }
  phantom.exit();
}

/**
 * Escapes strings to pass to RegExp.
 *
 * @see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
 */
function escapeRegExp (str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

page.onConsoleMessage = function (msg) {
  console.log(msg);
};

// Catch script evaluation errors; quit Phantom.
page.onError = function (msg, trace) {
  console.log(JSON.stringify([
    'Error on the evaluated page',
    msg,
    trace
  ], undefined, 2));
  quitPhantom('Error on the evaluated page');
};

// Blocking resource requests by domain or type.
var blacklists = config.blacklists || {};

function rMapper (str) {
  var r = escapeRegExp(str);
  return new RegExp(r, 'i');
}

var rBlockedDomains = (blacklists.domains || []).map(rMapper);
var rBlockedTypes = (blacklists.mimetypes || []).map(rMapper);
var rBlockedHeaders = (blacklists.headers || []).map(rMapper);

page.onResourceRequested = function (requestData, request) {
  var blocked = false;
  var reason = '';
  // Block third-party resource requests from blacklisted domains.
  blocked = rBlockedDomains.some(function (reg) {
    return reg.test(requestData.url);
  });
  // Block third-party resource requests of specific Accept types.
  if (blocked) {
    reason = 'domain';
  }
  else {
    blocked = rBlockedTypes.some(function (reg) {
      // Get the Accept header value.
      var headers = requestData.headers || [];
      var accept, header;
      for (var i = 0, il = headers.length; i < il; i++) {
        header = headers[i];
        if (header.name.toLowerCase() === 'accept') {
          accept = header.value;
          break;
        }
      }
      return reg.test(accept || '');
    });
    if (blocked) {
      reason = 'type';
    }
  }
  // Block third-party resource requests by Header.
  if (!blocked) {
    blocked = rBlockedHeaders.some(function (reg) {
      return (requestData.headers || []).some(function (header) {
        return reg.test(header.name);
      });
    });
    if (blocked) {
      reason = 'header';
    }
  }

  if (blocked) {
    console.log(JSON.stringify([
      'BLOCKED (' + reason + ')',
      'Requested (' + requestData.method + ')',
      requestData.url
    ]));
    request.abort();
  }
};

page.onResourceTimeout = function (error) {
  console.log(JSON.stringify([
    'Resource timeout',
    error.errorCode, // it'll probably be 408
    error.errorString, // it'll probably be 'Network timeout on resource'
    error.url // the url whose request timed out
  ]));
};

page.onResourceError = function (error) {
  // Ignore blocked resource errors.
  if (error.errorCode !== 301) {
    console.log(JSON.stringify([
      'Resource error',
      'Error code: ' + error.errorCode,
      error.errorString,
      error.url
    ], undefined, 2));
  }
};

// This is the last chance to catch catestrophic errors.
phantom.onError = function (msg, trace) {
  console.log(JSON.stringify([
    'Error in the phantom runner',
    msg,
    trace
  ], undefined, 2));
};

// The number of items that will attempt to write data from the evaluation.
// When the evaulation starts, it will register how many items will
// report back.
var len = null;
// Open a write stream to an output file.
var date = new Date();
var timestamp = [
  date.getFullYear(),
  ('0' + (date.getMonth() + 1)).slice(-2),
  ('0' + date.getDate()).slice(-2),
  '-',
  ('0' + date.getHours()).slice(-2),
  ('0' + date.getMinutes()).slice(-2),
  ('0' + date.getSeconds()).slice(-2),
  '-',
  date.getTime()
].join('');
// Write out the results is an output directory path was provided.
var resultsFile;
if (outputDir) {
  resultsFile = [outputDir, timestamp + '-analysis.js'].join('/');
}
else {
  resultsFile = dir + '/analyses/' + timestamp + '-analysis.js';
}
var stream = fs.open(resultsFile, 'w');

// The data to be written to file.
var output = {};
var start = (new Date()).getTime();
// The callback function reachable from the page.evaluate* methods.
page.onCallback = function (action, data) {
  var name;
  switch (action) {
  // Len is the number of times we expect to log data.
  case 'setCounter':
    len = data;
    break;
  case 'writeData':
    if (len !== null) {
      --len;
    }

    // Store all the keys in the object to an output object.
    data = JSON.parse(data);
    if (typeof data === 'object') {
      for (var key in data) {
        // Tests and Success Criteria are situated under their own keys.
        if (key === 'tests' || key === 'successCriteria') {
          if (!output[key]) {
            output[key] = {};
          }
          for (name in data[key]) {
            if (data[key].hasOwnProperty(name)) {
              output[key][name] = data[key][name];
            }
          }
        }
        else {
          output[key] = data[key];
        }
      }
    }
    // All the tests have completed.
    if (len === 0 || len === null) {
      console.log('Elapsed time: ' + ((new Date()).getTime() - start) / 1000 + ' seconds');
      console.log('Cases found: ' + (output.stats && output.stats.cases || 0));

      // Time for each test.
      // console.log('Elapsed time for tests:');
      for (name in output.tests) {
        if (output.tests.hasOwnProperty(name)) {
          // console.log('elapsed time:\t' + output.tests[name].elapsedTime + '\t' + name);
        }
      }
      console.log('Results were written to ' + resultsFile);
      stream.write(JSON.stringify(output, null, '\t'));
      stream.close();

      quitPhantom('Testing complete');
    }
    break;
  case 'quit':
    quitPhantom(data);
    break;
  default:
    break;
  }
};

page.open(address);

// Decorate the page once the HTML has been loaded.
// This is where we run the tests.
page.onLoadFinished = function (status) {
  var callPhantom = window && window.callPhantom || function () {};
  if (status === 'success') {
    console.log('Page opened successfully: ' + address);
    page.injectJs(dir + '/dist/bundle.js');

    // Run the evaluation.
    //
    // The evaluation is executed in its own function scope. Closures that
    // incorporate outside scopes are not possible.
    try {
      page.evaluate(function () {
        // Tell the client that we're starting the test run.
        console.log('Beginning evaluation.');

        // Basic output structure attributes.
        var output = {
          tests: {},
          successCriteria: {},
          stats: {
            tests: 0,
            cases: 0
          }
        };
        globalQuail.run({
          // Called when an individual Case in a test is resolved.
          caseResolve: function (eventName, test, _case) {
            var name = test.get('name');

            if (!output.tests[name]) {
              output.tests[name] = {
                id: name,
                title: test.get('title'),
                description: test.get('description'),
                type: test.get('type'),
                testability: test.get('testability'),
                guidelines: test.get('guidelines') || {},
                tags: test.get('tags'),
                cases: []
              };
            }
            // Push the case into the results for this test.
            output.tests[name].cases.push({
              status: _case.get('status'),
              selector: _case.get('selector'),
              html: _case.get('html')
            });
            // Increment the cases count.
            output.stats.cases++;
          },
          // Called when all the Cases in a Test are resolved.
          testComplete: function (event, test) {
            var name = test.get('name');
            // Increment the tests count.
            output.stats.tests++;
            // Record the elapsed time for the test.
            if (output.tests[name]) {
              output.tests[name].elapsedTime = test.get('endTime') - test.get('startTime');
            }
          },
          // Called when all the Tests in a TestCollection are completed.
          testCollectionComplete: function () {
            // Push the results of the test out to the Phantom listener.
            console.log('The test collection has been evaluated.');
            callPhantom('writeData', JSON.stringify(output));
          },
          successCriteriaEvaluated: function (eventName, successCriteria) {
            var name = successCriteria.get('name');
            var status = successCriteria.get('status');
            // var totals = successCriteria.get('totals');
            var output = {
              successCriteria: {}
            };
            // Push the results of the test out to the Phantom listener.
            // If the SC was untested, report that as its status.
            if (status === 'untested' || status === 'noResults' || status === 'noTestCoverage') {
              output.successCriteria[name] = status;
            }
            // Otherwise get the cases and report them under their status.
            else {
              output.successCriteria[name] = {};
              var results = successCriteria.get('results');
              var cases, _case;
              for (var result in results) {
                if (results.hasOwnProperty(result)) {
                  output.successCriteria[name][result] = [];
                  // Go through each case for this result and get its selector and HTML.
                  cases = results[result];
                  for (var i = 0, il = cases.length; i < il; i++) {
                    _case = cases[i];
                    output.successCriteria[name][result].push({
                      selector: _case.get('selector'),
                      html: _case.get('html')
                    });
                  }
                }
              }
              // List the totals for each type of result
              output.successCriteria[name].totals = successCriteria.get('totals');
            }
            // Echo
            // console.log('Evaluated: ' + name, 'conclusion: ' + status, 'totals: ' + JSON.stringify(totals));
            // Attempt to write out the data.
            callPhantom('writeData', JSON.stringify(output));
          }
        });
      });
    }
    catch (error) {
      callPhantom('quit', error);
    }
  }
  else {
    callPhantom('quit', 'Page failed to load');
  }
};
<commit_msg>Quit when a host is not available<commit_after>// Context is phantom

var system = require('system');
var webpage = require('webpage');
var fs = require('fs');
var [
  ,
  address, // URL to evaluate
  configFilePath, // Configuration JSON file.
  outputDir // Directory to write output to.
] = system.args;
var dir = fs.workingDirectory

// Run time configurations.
var config;
try {
  config = JSON.parse(fs.read(configFilePath));
}
catch (err) {
  quitPhantom(err);
}

// Create the QtRuntimeObject with the desired configuration. This is the
// PhantomJS controller object.
var page = webpage.create(config.phantomjs);

/**
 * Logs the reason for exit; exits Phantom.
 */
function quitPhantom (reason) {
  console.log('phantom_evaluator' + (reason && (': ' + reason) || ''));
  if (stream) {
    stream.close();
  }
  phantom.exit();
}

/**
 * Escapes strings to pass to RegExp.
 *
 * @see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
 */
function escapeRegExp (str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

page.onConsoleMessage = function (msg) {
  console.log(msg);
};

// Catch script evaluation errors; quit Phantom.
page.onError = function (msg, trace) {
  console.log(JSON.stringify([
    'Error on the evaluated page',
    msg,
    trace
  ], undefined, 2));
  quitPhantom('Error on the evaluated page');
};

// Blocking resource requests by domain or type.
var blacklists = config.blacklists || {};

function rMapper (str) {
  var r = escapeRegExp(str);
  return new RegExp(r, 'i');
}

var rBlockedDomains = (blacklists.domains || []).map(rMapper);
var rBlockedTypes = (blacklists.mimetypes || []).map(rMapper);
var rBlockedHeaders = (blacklists.headers || []).map(rMapper);

page.onResourceRequested = function (requestData, request) {
  var blocked = false;
  var reason = '';
  // Block third-party resource requests from blacklisted domains.
  blocked = rBlockedDomains.some(function (reg) {
    return reg.test(requestData.url);
  });
  // Block third-party resource requests of specific Accept types.
  if (blocked) {
    reason = 'domain';
  }
  else {
    blocked = rBlockedTypes.some(function (reg) {
      // Get the Accept header value.
      var headers = requestData.headers || [];
      var accept, header;
      for (var i = 0, il = headers.length; i < il; i++) {
        header = headers[i];
        if (header.name.toLowerCase() === 'accept') {
          accept = header.value;
          break;
        }
      }
      return reg.test(accept || '');
    });
    if (blocked) {
      reason = 'type';
    }
  }
  // Block third-party resource requests by Header.
  if (!blocked) {
    blocked = rBlockedHeaders.some(function (reg) {
      return (requestData.headers || []).some(function (header) {
        return reg.test(header.name);
      });
    });
    if (blocked) {
      reason = 'header';
    }
  }

  if (blocked) {
    console.log(JSON.stringify([
      'BLOCKED (' + reason + ')',
      'Requested (' + requestData.method + ')',
      requestData.url
    ]));
    request.abort();
  }
};

page.onResourceTimeout = function (error) {
  console.log(JSON.stringify([
    'Resource timeout',
    error.errorCode, // it'll probably be 408
    error.errorString, // it'll probably be 'Network timeout on resource'
    error.url // the url whose request timed out
  ]));
};

page.onResourceError = function (err) {
  // Ignore blocked resource errors.
  if (err.errorCode !== 301) {
    console.log(JSON.stringify([
      'Resource error',
      'Error code: ' + err.errorCode,
      err.errorString,
      err.url
    ], undefined, 2));
    if (err.errorCode === 3) {
      quitPhantom(err.errorString);
    }
  }
};

// This is the last chance to catch catestrophic errors.
phantom.onError = function (msg, trace) {
  console.log(JSON.stringify([
    'Error in the phantom runner',
    msg,
    trace
  ], undefined, 2));
};

// The number of items that will attempt to write data from the evaluation.
// When the evaulation starts, it will register how many items will
// report back.
var len = null;
// Open a write stream to an output file.
var date = new Date();
var timestamp = [
  date.getFullYear(),
  ('0' + (date.getMonth() + 1)).slice(-2),
  ('0' + date.getDate()).slice(-2),
  '-',
  ('0' + date.getHours()).slice(-2),
  ('0' + date.getMinutes()).slice(-2),
  ('0' + date.getSeconds()).slice(-2),
  '-',
  date.getTime()
].join('');
// Write out the results is an output directory path was provided.
var resultsFile;
if (outputDir) {
  resultsFile = [outputDir, timestamp + '-analysis.js'].join('/');
}
else {
  resultsFile = dir + '/analyses/' + timestamp + '-analysis.js';
}
var stream = fs.open(resultsFile, 'w');

// The data to be written to file.
var output = {};
var start = (new Date()).getTime();
// The callback function reachable from the page.evaluate* methods.
page.onCallback = function (action, data) {
  var name;
  switch (action) {
  // Len is the number of times we expect to log data.
  case 'setCounter':
    len = data;
    break;
  case 'writeData':
    if (len !== null) {
      --len;
    }

    // Store all the keys in the object to an output object.
    data = JSON.parse(data);
    if (typeof data === 'object') {
      for (var key in data) {
        // Tests and Success Criteria are situated under their own keys.
        if (key === 'tests' || key === 'successCriteria') {
          if (!output[key]) {
            output[key] = {};
          }
          for (name in data[key]) {
            if (data[key].hasOwnProperty(name)) {
              output[key][name] = data[key][name];
            }
          }
        }
        else {
          output[key] = data[key];
        }
      }
    }
    // All the tests have completed.
    if (len === 0 || len === null) {
      console.log('Elapsed time: ' + ((new Date()).getTime() - start) / 1000 + ' seconds');
      console.log('Cases found: ' + (output.stats && output.stats.cases || 0));

      // Time for each test.
      // console.log('Elapsed time for tests:');
      for (name in output.tests) {
        if (output.tests.hasOwnProperty(name)) {
          // console.log('elapsed time:\t' + output.tests[name].elapsedTime + '\t' + name);
        }
      }
      console.log('Results were written to ' + resultsFile);
      stream.write(JSON.stringify(output, null, '\t'));
      stream.close();

      quitPhantom('Testing complete');
    }
    break;
  case 'quit':
    quitPhantom(data);
    break;
  default:
    break;
  }
};

page.open(address);

// Decorate the page once the HTML has been loaded.
// This is where we run the tests.
page.onLoadFinished = function (status) {
  var callPhantom = window && window.callPhantom || function () {};
  if (status === 'success') {
    console.log('Page opened successfully: ' + address);
    page.injectJs(dir + '/dist/bundle.js');

    // Run the evaluation.
    //
    // The evaluation is executed in its own function scope. Closures that
    // incorporate outside scopes are not possible.
    try {
      page.evaluate(function () {
        // Tell the client that we're starting the test run.
        console.log('Beginning evaluation.');

        // Basic output structure attributes.
        var output = {
          tests: {},
          successCriteria: {},
          stats: {
            tests: 0,
            cases: 0
          }
        };
        globalQuail.run({
          // Called when an individual Case in a test is resolved.
          caseResolve: function (eventName, test, _case) {
            var name = test.get('name');

            if (!output.tests[name]) {
              output.tests[name] = {
                id: name,
                title: test.get('title'),
                description: test.get('description'),
                type: test.get('type'),
                testability: test.get('testability'),
                guidelines: test.get('guidelines') || {},
                tags: test.get('tags'),
                cases: []
              };
            }
            // Push the case into the results for this test.
            output.tests[name].cases.push({
              status: _case.get('status'),
              selector: _case.get('selector'),
              html: _case.get('html')
            });
            // Increment the cases count.
            output.stats.cases++;
          },
          // Called when all the Cases in a Test are resolved.
          testComplete: function (event, test) {
            var name = test.get('name');
            // Increment the tests count.
            output.stats.tests++;
            // Record the elapsed time for the test.
            if (output.tests[name]) {
              output.tests[name].elapsedTime = test.get('endTime') - test.get('startTime');
            }
          },
          // Called when all the Tests in a TestCollection are completed.
          testCollectionComplete: function () {
            // Push the results of the test out to the Phantom listener.
            console.log('The test collection has been evaluated.');
            callPhantom('writeData', JSON.stringify(output));
          },
          successCriteriaEvaluated: function (eventName, successCriteria) {
            var name = successCriteria.get('name');
            var status = successCriteria.get('status');
            // var totals = successCriteria.get('totals');
            var output = {
              successCriteria: {}
            };
            // Push the results of the test out to the Phantom listener.
            // If the SC was untested, report that as its status.
            if (status === 'untested' || status === 'noResults' || status === 'noTestCoverage') {
              output.successCriteria[name] = status;
            }
            // Otherwise get the cases and report them under their status.
            else {
              output.successCriteria[name] = {};
              var results = successCriteria.get('results');
              var cases, _case;
              for (var result in results) {
                if (results.hasOwnProperty(result)) {
                  output.successCriteria[name][result] = [];
                  // Go through each case for this result and get its selector and HTML.
                  cases = results[result];
                  for (var i = 0, il = cases.length; i < il; i++) {
                    _case = cases[i];
                    output.successCriteria[name][result].push({
                      selector: _case.get('selector'),
                      html: _case.get('html')
                    });
                  }
                }
              }
              // List the totals for each type of result
              output.successCriteria[name].totals = successCriteria.get('totals');
            }
            // Echo
            // console.log('Evaluated: ' + name, 'conclusion: ' + status, 'totals: ' + JSON.stringify(totals));
            // Attempt to write out the data.
            callPhantom('writeData', JSON.stringify(output));
          }
        });
      });
    }
    catch (error) {
      callPhantom('quit', error);
    }
  }
  else {
    callPhantom('quit', 'Page failed to load');
  }
};
<|endoftext|>


<commit_before>(function($){

    $(window).bind('resize.bootstrapit', function(e) {
        var h = $(window).height() - 135;
        $('.CodeMirror').height(h)
            .find('.CodeMirror-scroll').height(h); // Weird ..
    });

    $('.cm-number')
        .live('mouseover', function() {
            if ($(this).text()[0] == '#') {
                $(this).css('background', $(this).text());
            }
        })
        .live('mouseleave', function() {
            $(this).css('background', 'transparent');
        });

    $.bootstrapit = (function() {

        this.preview = window.parent;
        this.buffers = {};

        this.createEditor = function(element) {
            return CodeMirror(element.get(0), {
                dynamic: true
            });
        };

        this.createViewport = function(filename, title) {
            $('.viewport').hide();
            var editor,
                lesspath = $('body').data('less-path'),
                viewport = $([
                '
',
                    '
',
                        '', title, ' ',
                        '', filename, '',
                    '
',
                    '
',
                '
'].join('')).appendTo('#bootstrapit-editor');

            editor = this.createEditor(
                        viewport.find('.viewport-content'));

            $(window).trigger('resize.bootstrapit');
            this.loadFile(lesspath + filename, editor);

            return {
                title: title,
                filename: filename,
                viewport: viewport,
                editor: editor,
            };
        };

        this.showViewport = function(filename) {
            $('.viewport').hide();
            return this.buffers[filename].viewport.show();
        };

        this.loadFile = function(path, editor) {
            $.get(path, function(rs, statusCode) {
                if (statusCode == 'success') {
                    editor.setValue(rs);
                    $(editor.getWrapperElement()).find('.cm-number')
                        .each(function(i, el){
                            var t = $(el).text()
                            if (t.slice(0,1) == '#' && (t.length == 4 || t.length == 7)) {
                                $(el).data('color', t).colorpicker().on('changeColor', function(ev){
                                    $(this).text(ev.color.toHex());
                                });
                            }
                        })
                }
            });
        };

        return this;
    })();

    $(function(){
        $('.bootstrapit-file').bind('click.bootstrapit', function(e){
            var a = $(this),
                filename = a.attr('href').replace('#', '');
            if (a.data('editor-viewport')) {
                $.bootstrapit.showViewport(filename);
            }
            else {
                a.data('editor-viewport',
                    $.bootstrapit.createViewport(filename, a.text()));
            }
        });
    });
})(jQuery);

<commit_msg>fix bug editor<commit_after>(function($){

    $(window).bind('resize.bootstrapit', function(e) {
        var h = $(window).height() - 135;
        $('.CodeMirror').height(h)
            .find('.CodeMirror-scroll').height(h); // Weird ..
    });

    $('.cm-number')
        .live('mouseover', function() {
            if ($(this).text()[0] == '#') {
                $(this).css('background', $(this).text());
            }
        })
        .live('mouseleave', function() {
            $(this).css('background', 'transparent');
        });

    $.bootstrapit = (function() {

        this.preview = window.parent;
        this.buffers = {};

        this.createEditor = function(element) {
            return CodeMirror(element.get(0), {
                dynamic: true
            });
        };

        this.createViewport = function(filename, title) {
            $('.viewport').hide();
            var editor,
                lesspath = $('body').data('less-path'),
                viewport = $([
                '
',
                    '
',
                        '', title, ' ',
                        '', filename, '',
                    '
',
                    '
',
                '
'].join('')).appendTo('#bootstrapit-editor');

            editor = this.createEditor(
                        viewport.find('.viewport-content'));

            $(window).trigger('resize.bootstrapit');
            this.loadFile(lesspath + filename, editor);

            this.buffers[filename] = {
                title: title,
                filename: filename,
                viewport: viewport,
                editor: editor,
            };

            return this.buffers[filename];

        };

        this.showViewport = function(filename) {
            $('.viewport').hide();
            return this.buffers[filename].viewport.show();
        };

        this.loadFile = function(path, editor) {
            $.get(path, function(rs, statusCode) {
                if (statusCode == 'success') {
                    editor.setValue(rs);
                    $(editor.getWrapperElement()).find('.cm-number')
                        .each(function(i, el){
                            var t = $(el).text()
                            if (t.slice(0,1) == '#' && (t.length == 4 || t.length == 7)) {
                                $(el).data('color', t).colorpicker().on('changeColor', function(ev){
                                    $(this).text(ev.color.toHex());
                                });
                            }
                        })
                }
            });
        };

        return this;
    })();

    $(function(){
        $('.bootstrapit-file').bind('click.bootstrapit', function(e){
            var a = $(this),
                filename = a.attr('href').replace('#', '');
            if (a.data('editor-viewport')) {
                $.bootstrapit.showViewport(filename);
            }
            else {
                a.data('editor-viewport',
                    $.bootstrapit.createViewport(filename, a.text()));
            }
        });
    });
})(jQuery);

<|endoftext|>


<commit_before>import { setText } from "../../src";

describe("setHtml", () => {
  afterEach(clearFixtures);

  it("replace element content with given string", () => {
    useFixture(`

    `);

    const subject = document.querySelector(".root");

    expect(subject.querySelector(".before")).not.toBe(null);

    setText(subject, "text content");

    expect(subject.querySelector(".before")).toBe(null);
    expect(subject.innerText).toBe("text content");
  });
});
<commit_msg>:cop:<commit_after>import { setText } from "../../src";

describe("setText", () => {
  afterEach(clearFixtures);

  it("replace element content with given string", () => {
    useFixture(`

    `);

    const subject = document.querySelector(".root");

    expect(subject.querySelector(".before")).not.toBe(null);

    setText(subject, "text content");

    expect(subject.querySelector(".before")).toBe(null);
    expect(subject.innerText).toBe("text content");
  });
});
<|endoftext|>