<commit_before>var { Octokit } = require('@octokit/rest'),
    { throttling } = require("@octokit/plugin-throttling"),
    MyOctokit = Octokit.plugin(throttling),
    config = require('./config-loader'),
    Promise = require('bluebird'),
    _ = require('underscore'),
    debug = require('./debug')('pulldasher:github'),
    utils = require('./utils'),
    Pull = require('../models/pull'),
    Issue = require('../models/issue'),
    Comment = require('../models/comment'),
    Review = require('../models/review'),
    Label = require('../models/label'),
    Status = require('../models/status'),
    Signature = require('../models/signature'),
    getLogin  = require('./get-user-login'),
    rateLimit = require('./rate-limit.js');

const github = new MyOctokit({
   auth: config.github.token,
   throttle: {
      onRateLimit: (retryAfter, options) => {
        github.log.warn(
          `Request quota exhausted for request ${options.method} ${options.url}`
        );

        // Retry twice after hitting a rate limit error, then give up
        if (options.request.retryCount <= 2) {
          github.log.debug(`Retrying after ${retryAfter} seconds!`);
          return true;
        }
      },
      onAbuseLimit: (retryAfter, options) => {
        // does not retry, only logs a warning
        github.log.warn(
          `Abuse detected for request ${options.method} ${options.url}`
        );
      },
    }
});

const githubRest = github.rest;

module.exports = {
   github: githubRest,

   /**
    * Returns a promise which resolves to a GitHub API response to
    * a query for a particular Pull Request.
    */
   getPull: function(repo, number) {
      debug("Getting pull %s", number);
      return githubRest.pulls.get(params({ pull_number: number }, repo))
       .then(res => res.data);
   },

   /**
    * Get all *open* pull requests for a repo.
    *
    * Returns a promise which resolves to an array of all open pull requests
    */
   getOpenPulls: function(repo) {
      debug("Getting open pulls in repo %s", repo);
      return github.paginate(githubRest.pulls.list, params({state: 'open'}, repo));
   },

   /**
    * Get *all* pull requests for a repo.
    *
    * Returns a promise which resolves to an array of all pull requests
    */
   getAllPulls: function(repo) {
      debug("Getting all pulls in repo %s", repo);
      return github.paginate(githubRest.pulls.list, params({ state: 'all'}, repo));
   },

   /**
    * Get an issue for a repo.
    *
    * Returns a promise which resolves to a github issue
    */
   getIssue: function(repo, number) {
      const searchParams = params({ issue_number: number }, repo);
      debug("Getting issue %s in repo %s", number, repo);
      return github.paginate(githubRest.issues.get, searchParams).then(addRepo(searchParams));
   },

   /**
    * Get all open issues for a repo.
    *
    * Returns a promise which resolves to an array of all open issues
    */
   getOpenIssues: function(repo) {
      const searchParams = params({state: 'open'}, repo);
      debug("Getting open issues");
      return github.paginate(githubRest.issues.listForRepo, searchParams).then(filterOutPulls).then(addRepo(searchParams));
   },

   /**
    * Get *all* issues for a repo.
    *
    * Returns a promise which resolves to an array of all issues
    */
   getAllIssues: function(repo) {
      const searchParams = params({state: 'all'}, repo);
      debug("Getting all issues");
      return github(githubRest.issues.listForRepo, searchParams).then(filterOutPulls).then(addRepo(searchParams));
   },

   /**
    * Takes a promise that resolves to a GitHub pull request API response,
    * parses it, and returns a promise that resolves to a Pull objects.
    */
   parse: function(githubPull) {
      debug("Getting all information for pull %s in repo %s", githubPull.number,
         githubPull.base.repo.full_name);
      // We've occasionally noticed a null pull body, so lets fix it upfront
      // before errors happen.
      githubPull.body = githubPull.body || '';

      var repo = githubPull.base.repo.full_name;

      var reviewComments = getPullReviewComments(repo, githubPull.number);
      var comments = getIssueComments(repo, githubPull.number);
      var headCommit = getCommit(repo, githubPull.head.sha);
      var commitStatuses = getCommitStatuses(repo, githubPull.head.sha);
      var events = getIssueEvents(repo, githubPull.number);
      // Only so we have the canonical list of labels.
      var ghIssue = module.exports.getIssue(repo, githubPull.number);
      var reviews = getReviews(repo, githubPull.number);

      // Returned to the map function. Each element of githubPulls maps to
      // a promise that resolves to a Pull.
      return Promise.all([reviewComments,
                          comments,
                          headCommit,
                          commitStatuses,
                          events,
                          ghIssue,
                          reviews])
       .then(function(results) {
         var reviewComments = results[0],
             comments       = results[1],
             headCommit     = results[2],
             commitStatuses = results[3],
             events         = results[4],
             ghIssue        = results[5],
             reviews        = results[6];

         // Array of Signature objects.
         var commentSignatures = comments.reduce(function(sigs, comment) {
            var commentSigs = Signature.parseComment(
             comment, repo, githubPull.number);

            return sigs.concat(commentSigs);
         }, []);

         var signatures = reviews.reduce(function(sigs, review) {
            var reviewSigs = Signature.parseReview(
             review, repo, githubPull.number);

            return sigs.concat(reviewSigs);
         }, commentSignatures);

         // Signoffs from before the most recent commit are no longer active.
         var headCommitDate = new Date(headCommit.commit.committer.date);
         signatures.forEach(function(signature) {
            if ((signature.data.type === 'CR' ||
             signature.data.type === 'QA') &&
             new Date(signature.data.created_at) < headCommitDate) {
               signature.data.active = false;
            }
         });

         // Array of Comment objects.
         comments = comments.map(function(commentData) {
            commentData.number = githubPull.number;
            commentData.repo = repo;
            commentData.type = 'issue';

            return new Comment(commentData);
         });

         // Array of Comment objects.
         comments = comments.concat(reviewComments.map(function(commentData) {
            commentData.number = githubPull.number;
            commentData.repo = repo;
            commentData.type = 'review';

            return new Comment(commentData);
         }));

         reviews = reviews.map(function(reviewData) {
            reviewData.number = githubPull.number;
            reviewData.repo = repo;

            return new Review(reviewData);
         });

         let statuses = commitStatuses.map(function(commitStatus) {
            return new Status({
               repo:          repo,
               sha:           githubPull.head.sha,
               state:         commitStatus.state,
               description:   commitStatus.description,
               target_url:    commitStatus.target_url,
               context:       commitStatus.context,
            });
         });

         // Array of Label objects.
         const labels = getLabelsFromEvents(events, ghIssue);

         const pull = Pull.fromGithubApi(githubPull, signatures, comments, reviews, statuses, labels);
         return pull.syncToIssue();
      });
   },

   /**
    * Takes a GitHub issue API response
    * parses it, and returns a promise that resolves to an Issue object.
    */
   parseIssue: function(ghIssue) {
      debug("Getting all information for issue %s in repo %s", ghIssue.number,
         ghIssue.repo);
      return getIssueEvents(ghIssue.repo, ghIssue.number)
      .then(function(events) {
         // Array of Label objects.
         // Note: using the repo name from the config for now until we support
         // multiple repos. The ghIssue object doesn't contain the repo name.
         var labels = getLabelsFromEvents(events, ghIssue);

         return Issue.getFromGH(ghIssue, labels);
      });
   },
};

/**
 * Get array of Label objects from complete list of a Issue's events.
 *
 * Note: ghIssue at this point has always come from one of the
 * get*Issues() commands and thus has been augmented with the
 * issue.repo property.
 */
function getLabelsFromEvents(events, ghIssue) {
   debug("Extracting label assignments from %s issue events for #%s",
    events.length, ghIssue.number);

   // Narrow list to relevant labeled/unlabeled events.
   events = _.filter(events, function(event) {
      return event.event === 'labeled' || event.event === 'unlabeled';
   });

   debug("Found %s label events for #%s", events.length, ghIssue.number);

   // Build simple Event objects with all the info we care about.
   events = events.map(function(event) {
      return {
         type: event.event,
         name: event.label.name,
         user: getLogin(event.actor),
         created_at: utils.fromDateString(event.created_at)
      };
   });

   // Group label events by label name.
   var labels = _.groupBy(events, 'name');

   // Get a list of the most recent events for each label.
   labels = _.map(labels, function(events) {
      events = _.sortBy(events, 'created_at');
      return _.last(events);
   });

   labels = _.filter(labels, function(event) {
      return event.type === 'labeled';
   });

   debug("Found %s unique labels for #%s", labels.length, ghIssue.number);

   // If these are available, use them as the canonical source, only augmented
   // by the data from events. If a label is renamed, the events will retain
   // the old name but the list of labels on the issue itself will be correct.
   // So, if a label is renamed, we'll lose the labeler and the date.
   if (ghIssue.labels && ghIssue.labels.length) {
      debug("Using %s labels from the github issue", ghIssue.labels.length);
      // Includes labeller and a time from the events api
      var eventLabels = _.indexBy(labels, 'name');

      return ghIssue.labels.map(function(label) {
         var eventLabel = eventLabels[label.name];
         return new Label(
            {name: label.name},
            ghIssue.number,
            ghIssue.repo,
            eventLabel && eventLabel.user,
            eventLabel && eventLabel.created_at
         );
      });
   }

   // Construct Label objects.
   return labels.map(function(label) {
      return new Label(
         {name: label.name},
         ghIssue.number,
         ghIssue.repo,
         label.user,
         label.created_at
      );
   });
}

/**
 * Return the default api params merged with the overrides
 */
function params(apiParams, fullRepoName) {
   const [owner, repo] = parseRepo(fullRepoName);

   return _.extend({
      owner,
      repo,
   }, apiParams);
}

/**
 * Returns a function that uses the search parameters to add the "repo"
 * property to all the results. When we ask for a list of open issues from the
 * API for a particular repo, those results don't have references to the repo
 * we asked about, so we have to inject them to normalize the structure of the
 * object.
 */
function addRepo({owner, repo}) {
   function addRepositoryField(ghIssue) {
      ghIssue.repo = owner + "/" + repo;
   }
   return function(results) {
      if (Array.isArray(results)) {
         results.forEach(addRepositoryField);
      } else {
         addRepositoryField(results);
      }
      return results;
   };
}

/**
 * Splits the repo into the owner and repo name.
 */
function parseRepo(repo) {
   return repo.split("/");
}

/**
 * Return a promise for all issue events for the given issue / pull
 */
function getIssueEvents(repo, number) {
   debug("Getting events for issue #%s", number);
   return github.paginate(githubRest.issues.listEventsForRepo, params({ issue_number: number }, repo))
}

function getIssueComments(repo, number) {
   debug("Getting comments for issue #%s", number);
   return github.paginate(githubRest.issues.listComments, (params({ issue_number: number }, repo)));
}

function getReviews(repo, number) {
   debug("Getting reviews for pull #%s", number);
   return rateLimit(github.pullRequests.listReviews)(params({ number }, repo))
                       .then(paginate);
}

function getPullReviewComments(repo, number) {
   debug("Getting pull review comments for pull #%s", number);
   return github.paginate(githubRest.pulls.listReviewComments,params({ pull_number: number }, repo))
}

function getCommit(repo, sha) {
   return githubRest.repos.getCommit(params({ ref: sha }, repo)).then(res => res.data);
}

function getCommitStatuses(repo, ref) {
   debug("Getting commit status for %s", ref);
   return githubRest.repos.getCombinedStatusForRef(params({ ref }, repo))
      .then(res => res.data.statuses)
      .then(statuses => statuses || [])
}

/**
 * Remove all entries that have the pull_request key set to something truthy
 */
function filterOutPulls(issues) {
   debug("Filtering out pulls from list of %s issues", issues.length);
   issues = _.filter(issues,
                     issue => !issue.pull_request || !issue.pull_request.url);
   debug("Filtered down to %s issues", issues.length);
   return issues;
}
<commit_msg>Increase retry limit<commit_after>var { Octokit } = require('@octokit/rest'),
    { throttling } = require("@octokit/plugin-throttling"),
    MyOctokit = Octokit.plugin(throttling),
    config = require('./config-loader'),
    Promise = require('bluebird'),
    _ = require('underscore'),
    debug = require('./debug')('pulldasher:github'),
    utils = require('./utils'),
    Pull = require('../models/pull'),
    Issue = require('../models/issue'),
    Comment = require('../models/comment'),
    Review = require('../models/review'),
    Label = require('../models/label'),
    Status = require('../models/status'),
    Signature = require('../models/signature'),
    getLogin  = require('./get-user-login'),
    rateLimit = require('./rate-limit.js');

const github = new MyOctokit({
   auth: config.github.token,
   throttle: {
      onRateLimit: (retryAfter, options) => {
        github.log.warn(
          `Request quota exhausted for request ${options.method} ${options.url}`
        );

        // Retry five times after hitting a rate limit error, then give up
        if (options.request.retryCount <= 5) {
          github.log.debug(`Retrying after ${retryAfter} seconds!`);
          return true;
        }
      },
      onAbuseLimit: (retryAfter, options) => {
        // does not retry, only logs a warning
        github.log.warn(
          `Abuse detected for request ${options.method} ${options.url}`
        );
      },
    }
});

const githubRest = github.rest;

module.exports = {
   github: githubRest,

   /**
    * Returns a promise which resolves to a GitHub API response to
    * a query for a particular Pull Request.
    */
   getPull: function(repo, number) {
      debug("Getting pull %s", number);
      return githubRest.pulls.get(params({ pull_number: number }, repo))
       .then(res => res.data);
   },

   /**
    * Get all *open* pull requests for a repo.
    *
    * Returns a promise which resolves to an array of all open pull requests
    */
   getOpenPulls: function(repo) {
      debug("Getting open pulls in repo %s", repo);
      return github.paginate(githubRest.pulls.list, params({state: 'open'}, repo));
   },

   /**
    * Get *all* pull requests for a repo.
    *
    * Returns a promise which resolves to an array of all pull requests
    */
   getAllPulls: function(repo) {
      debug("Getting all pulls in repo %s", repo);
      return github.paginate(githubRest.pulls.list, params({ state: 'all'}, repo));
   },

   /**
    * Get an issue for a repo.
    *
    * Returns a promise which resolves to a github issue
    */
   getIssue: function(repo, number) {
      const searchParams = params({ issue_number: number }, repo);
      debug("Getting issue %s in repo %s", number, repo);
      return github.paginate(githubRest.issues.get, searchParams).then(addRepo(searchParams));
   },

   /**
    * Get all open issues for a repo.
    *
    * Returns a promise which resolves to an array of all open issues
    */
   getOpenIssues: function(repo) {
      const searchParams = params({state: 'open'}, repo);
      debug("Getting open issues");
      return github.paginate(githubRest.issues.listForRepo, searchParams).then(filterOutPulls).then(addRepo(searchParams));
   },

   /**
    * Get *all* issues for a repo.
    *
    * Returns a promise which resolves to an array of all issues
    */
   getAllIssues: function(repo) {
      const searchParams = params({state: 'all'}, repo);
      debug("Getting all issues");
      return github(githubRest.issues.listForRepo, searchParams).then(filterOutPulls).then(addRepo(searchParams));
   },

   /**
    * Takes a promise that resolves to a GitHub pull request API response,
    * parses it, and returns a promise that resolves to a Pull objects.
    */
   parse: function(githubPull) {
      debug("Getting all information for pull %s in repo %s", githubPull.number,
         githubPull.base.repo.full_name);
      // We've occasionally noticed a null pull body, so lets fix it upfront
      // before errors happen.
      githubPull.body = githubPull.body || '';

      var repo = githubPull.base.repo.full_name;

      var reviewComments = getPullReviewComments(repo, githubPull.number);
      var comments = getIssueComments(repo, githubPull.number);
      var headCommit = getCommit(repo, githubPull.head.sha);
      var commitStatuses = getCommitStatuses(repo, githubPull.head.sha);
      var events = getIssueEvents(repo, githubPull.number);
      // Only so we have the canonical list of labels.
      var ghIssue = module.exports.getIssue(repo, githubPull.number);
      var reviews = getReviews(repo, githubPull.number);

      // Returned to the map function. Each element of githubPulls maps to
      // a promise that resolves to a Pull.
      return Promise.all([reviewComments,
                          comments,
                          headCommit,
                          commitStatuses,
                          events,
                          ghIssue,
                          reviews])
       .then(function(results) {
         var reviewComments = results[0],
             comments       = results[1],
             headCommit     = results[2],
             commitStatuses = results[3],
             events         = results[4],
             ghIssue        = results[5],
             reviews        = results[6];

         // Array of Signature objects.
         var commentSignatures = comments.reduce(function(sigs, comment) {
            var commentSigs = Signature.parseComment(
             comment, repo, githubPull.number);

            return sigs.concat(commentSigs);
         }, []);

         var signatures = reviews.reduce(function(sigs, review) {
            var reviewSigs = Signature.parseReview(
             review, repo, githubPull.number);

            return sigs.concat(reviewSigs);
         }, commentSignatures);

         // Signoffs from before the most recent commit are no longer active.
         var headCommitDate = new Date(headCommit.commit.committer.date);
         signatures.forEach(function(signature) {
            if ((signature.data.type === 'CR' ||
             signature.data.type === 'QA') &&
             new Date(signature.data.created_at) < headCommitDate) {
               signature.data.active = false;
            }
         });

         // Array of Comment objects.
         comments = comments.map(function(commentData) {
            commentData.number = githubPull.number;
            commentData.repo = repo;
            commentData.type = 'issue';

            return new Comment(commentData);
         });

         // Array of Comment objects.
         comments = comments.concat(reviewComments.map(function(commentData) {
            commentData.number = githubPull.number;
            commentData.repo = repo;
            commentData.type = 'review';

            return new Comment(commentData);
         }));

         reviews = reviews.map(function(reviewData) {
            reviewData.number = githubPull.number;
            reviewData.repo = repo;

            return new Review(reviewData);
         });

         let statuses = commitStatuses.map(function(commitStatus) {
            return new Status({
               repo:          repo,
               sha:           githubPull.head.sha,
               state:         commitStatus.state,
               description:   commitStatus.description,
               target_url:    commitStatus.target_url,
               context:       commitStatus.context,
            });
         });

         // Array of Label objects.
         const labels = getLabelsFromEvents(events, ghIssue);

         const pull = Pull.fromGithubApi(githubPull, signatures, comments, reviews, statuses, labels);
         return pull.syncToIssue();
      });
   },

   /**
    * Takes a GitHub issue API response
    * parses it, and returns a promise that resolves to an Issue object.
    */
   parseIssue: function(ghIssue) {
      debug("Getting all information for issue %s in repo %s", ghIssue.number,
         ghIssue.repo);
      return getIssueEvents(ghIssue.repo, ghIssue.number)
      .then(function(events) {
         // Array of Label objects.
         // Note: using the repo name from the config for now until we support
         // multiple repos. The ghIssue object doesn't contain the repo name.
         var labels = getLabelsFromEvents(events, ghIssue);

         return Issue.getFromGH(ghIssue, labels);
      });
   },
};

/**
 * Get array of Label objects from complete list of a Issue's events.
 *
 * Note: ghIssue at this point has always come from one of the
 * get*Issues() commands and thus has been augmented with the
 * issue.repo property.
 */
function getLabelsFromEvents(events, ghIssue) {
   debug("Extracting label assignments from %s issue events for #%s",
    events.length, ghIssue.number);

   // Narrow list to relevant labeled/unlabeled events.
   events = _.filter(events, function(event) {
      return event.event === 'labeled' || event.event === 'unlabeled';
   });

   debug("Found %s label events for #%s", events.length, ghIssue.number);

   // Build simple Event objects with all the info we care about.
   events = events.map(function(event) {
      return {
         type: event.event,
         name: event.label.name,
         user: getLogin(event.actor),
         created_at: utils.fromDateString(event.created_at)
      };
   });

   // Group label events by label name.
   var labels = _.groupBy(events, 'name');

   // Get a list of the most recent events for each label.
   labels = _.map(labels, function(events) {
      events = _.sortBy(events, 'created_at');
      return _.last(events);
   });

   labels = _.filter(labels, function(event) {
      return event.type === 'labeled';
   });

   debug("Found %s unique labels for #%s", labels.length, ghIssue.number);

   // If these are available, use them as the canonical source, only augmented
   // by the data from events. If a label is renamed, the events will retain
   // the old name but the list of labels on the issue itself will be correct.
   // So, if a label is renamed, we'll lose the labeler and the date.
   if (ghIssue.labels && ghIssue.labels.length) {
      debug("Using %s labels from the github issue", ghIssue.labels.length);
      // Includes labeller and a time from the events api
      var eventLabels = _.indexBy(labels, 'name');

      return ghIssue.labels.map(function(label) {
         var eventLabel = eventLabels[label.name];
         return new Label(
            {name: label.name},
            ghIssue.number,
            ghIssue.repo,
            eventLabel && eventLabel.user,
            eventLabel && eventLabel.created_at
         );
      });
   }

   // Construct Label objects.
   return labels.map(function(label) {
      return new Label(
         {name: label.name},
         ghIssue.number,
         ghIssue.repo,
         label.user,
         label.created_at
      );
   });
}

/**
 * Return the default api params merged with the overrides
 */
function params(apiParams, fullRepoName) {
   const [owner, repo] = parseRepo(fullRepoName);

   return _.extend({
      owner,
      repo,
   }, apiParams);
}

/**
 * Returns a function that uses the search parameters to add the "repo"
 * property to all the results. When we ask for a list of open issues from the
 * API for a particular repo, those results don't have references to the repo
 * we asked about, so we have to inject them to normalize the structure of the
 * object.
 */
function addRepo({owner, repo}) {
   function addRepositoryField(ghIssue) {
      ghIssue.repo = owner + "/" + repo;
   }
   return function(results) {
      if (Array.isArray(results)) {
         results.forEach(addRepositoryField);
      } else {
         addRepositoryField(results);
      }
      return results;
   };
}

/**
 * Splits the repo into the owner and repo name.
 */
function parseRepo(repo) {
   return repo.split("/");
}

/**
 * Return a promise for all issue events for the given issue / pull
 */
function getIssueEvents(repo, number) {
   debug("Getting events for issue #%s", number);
   return github.paginate(githubRest.issues.listEventsForRepo, params({ issue_number: number }, repo))
}

function getIssueComments(repo, number) {
   debug("Getting comments for issue #%s", number);
   return github.paginate(githubRest.issues.listComments, (params({ issue_number: number }, repo)));
}

function getReviews(repo, number) {
   debug("Getting reviews for pull #%s", number);
   return rateLimit(github.pullRequests.listReviews)(params({ number }, repo))
                       .then(paginate);
}

function getPullReviewComments(repo, number) {
   debug("Getting pull review comments for pull #%s", number);
   return github.paginate(githubRest.pulls.listReviewComments,params({ pull_number: number }, repo))
}

function getCommit(repo, sha) {
   return githubRest.repos.getCommit(params({ ref: sha }, repo)).then(res => res.data);
}

function getCommitStatuses(repo, ref) {
   debug("Getting commit status for %s", ref);
   return githubRest.repos.getCombinedStatusForRef(params({ ref }, repo))
      .then(res => res.data.statuses)
      .then(statuses => statuses || [])
}

/**
 * Remove all entries that have the pull_request key set to something truthy
 */
function filterOutPulls(issues) {
   debug("Filtering out pulls from list of %s issues", issues.length);
   issues = _.filter(issues,
                     issue => !issue.pull_request || !issue.pull_request.url);
   debug("Filtered down to %s issues", issues.length);
   return issues;
}
<|endoftext|>


<commit_before>module.exports = (GULP, PLUGINS, NODE_MODULES, PATHS, REVISION) => {
    return function (callback)
    {
        var resources = GULP.src([
            PATHS.src + '/resources/**',
            '!**/sprite/**',
            '!**/svg-sprite/**',
            '!**/*.scss',
            '!**/*.md',
            '!**/*.twig',
        ], {
            nodir: true
        })
        .pipe(GULP.dest(PATHS.dest + '/resources'));

        var bower_components = GULP.src([
            './bower_components/jquery/**',
            './bower_components/svg-sprite-injector/**'
        ], {
            nodir: true,
            base: '.'
        })
        .pipe(PLUGINS.flatten({
            subPath: 1
        }))
        .pipe(GULP.dest(PATHS.dest + '/resources/base/javascripts/lib'));

        return NODE_MODULES.merge(resources, bower_components);
    }
}<commit_msg>Sync bower component javascripts<commit_after>module.exports = (GULP, PLUGINS, NODE_MODULES, PATHS, REVISION) => {
    return function (callback)
    {
        var resources = GULP.src([
            PATHS.src + '/resources/**',
            '!**/sprite/**',
            '!**/svg-sprite/**',
            '!**/*.scss',
            '!**/*.md',
            '!**/*.twig',
        ], {
            nodir: true
        })
        .pipe(GULP.dest(PATHS.dest + '/resources'));

        var package_objects = GULP.src([
            PATHS.packages + '/totem.object.*/**'
        ], {
            nodir: true
        })
        .pipe(GULP.dest(PATHS.dest + '/resources/objects'));

        var package_components = GULP.src([
            PATHS.packages + '/totem.component.*/**',
        ], {
            nodir: true
        })
        .pipe(GULP.dest(PATHS.dest + '/resources/components'));

        var bower_components = GULP.src([
            './bower_components/jquery/**',
            './bower_components/svg-sprite-injector/**'
        ], {
            nodir: true,
            base: '.'
        })
        .pipe(PLUGINS.flatten({
            subPath: 1
        }))
        .pipe(GULP.dest(PATHS.dest + '/resources/base/javascripts/lib'));

        return NODE_MODULES.merge(resources, package_objects, package_components, bower_components);
    }
}<|endoftext|>


<commit_before>/* globals module */
function solve() {
    return function (selector, items) {

    };
}

module.exports = solve;<commit_msg>js ui dom<commit_after>/* globals module */
function solve() {
    return function (selector, items) {
        var container = selector,
            fragment,
            length, i,

            imageList,
            imageListText,
            imageListInput,

            imageContainerTemplate,
            imageContainerText,
            imageContainerImage,
            allImageContainers,

            imagePreviewContainer,
            imagePreviewText,
            imagePreviewImage;

        if (typeof container === 'string') {
            container = document.querySelector(container);
        } else if (container instanceof HTMLElement) {

        } else {
            throw new Error();
        }

        // imageContainerTemplate
        imageContainerTemplate = document.createElement('li');
        imageContainerTemplate.className += 'image-container';
        imageContainerTemplate.style.padding = '10px';

        imageContainerText = document.createElement('strong');
        imageContainerText.style.display = 'block';
        imageContainerText.style.textAlign = 'center';

        imageContainerImage = document.createElement('img');
        imageContainerImage.style.width = '200px';

        imageContainerTemplate.appendChild(imageContainerText);
        imageContainerTemplate.appendChild(imageContainerImage);

        // ImageList
        imageListText = document.createElement('p');
        imageListText.innerHTML = 'Filter';
        imageListText.style.display = 'block';
        imageListText.style.textAlign = 'center';

        imageListInput = document.createElement('input');
        imageListInput.clasName = 'filte-images';

        imageList = document.createElement('ul');
        imageList.className = 'image-list';
        imageList.style.listStyle = 'none';
        imageList.style.float = 'right';
        imageList.style.clear = 'right';
        imageList.style.height = '400px';
        imageList.style.overflowY = 'scroll';

        imageList.appendChild(imageListText);
        imageList.appendChild(imageListInput);
        container.appendChild(imageList);

        imageList.addEventListener('click', onImageListClick);
        imageList.addEventListener('mouseover', onMoustEnterChangeBackgroundColor, true);
        imageList.addEventListener('mouseout', onMouseOutRevertBackgroundColor, true);
        // imageListInput.addEventListener('input', filterImageContainers);

        // Populate the List
        length = items.length;
        fragment = document.createDocumentFragment();
        for (i = 0; i < length; i += 1) {
            imageContainerText.innerHTML = items[i].title;
            imageContainerImage.src = items[i].url;

            fragment.appendChild(imageContainerTemplate.cloneNode(true));
        }
        imageList.appendChild(fragment);
        allImageContainers = document.getElementsByClassName('image-container');

        // Create ImagePreview
        imagePreviewContainer = document.createElement('div');
        imagePreviewContainer.style.float = 'left';
        imagePreviewContainer.style.width = '400px';

        imagePreviewText = document.createElement('h1');
        imagePreviewText.style.textAlign = 'center';

        imagePreviewImage = document.createElement('img');
        imagePreviewImage.style.width = '400px';

        imagePreviewContainer.appendChild(imagePreviewText);
        imagePreviewContainer.appendChild(imagePreviewImage);

        container.appendChild(imagePreviewContainer);
        container.style.width = '960px';

        // Set initial Value to ImagePreview
        imagePreviewText.innerHTML = allImageContainers[0].querySelector('strong').innerHTML;
        imagePreviewImage.src = allImageContainers[0].querySelector('img').src;

        // EVENTS
        function onImageListClick(event) {
            var clicked = event.target,
                parent;

            parent = findParentImageContainer(clicked);
            if (!parent) {
                return;
            }

            imagePreviewText.innerHTML = parent.querySelector('strong').innerHTML;
            imagePreviewImage.src = parent.querySelector('img').src;
        }

        function onMouseOutRevertBackgroundColor(event) {
            var clicked = event.target,
                parent;

            parent = findParentImageContainer(clicked);
            if (!parent) {
                return;
            }

            parent.style.backgroundColor = '';
        }

        function onMoustEnterChangeBackgroundColor(event) {
            var clicked = event.target,
                parent;

            parent = findParentImageContainer(clicked);
            if (!parent) {
                return;
            }

            parent.style.backgroundColor = '#E6E6E6';
        }

        function findParentImageContainer(target) {
            var parent = target;
            while (parent && parent.className.indexOf('image-container') < 0) {
                parent = parent.parentNode;
            }
            return parent;
        }
    };
}

module.exports = solve;<|endoftext|>


<commit_before>/**
  Frontend-starter

  @author Bartosz Sak, Archas

  https://github.com/implico/frontend-starter

  The MIT License (MIT)

  *******************
  Configuration file

*/

module.exports = function(dirs) {

  var config = {

    styles: {

      common: {
        sourceMaps: true,
        sourceMapsRoot: '/src/styles/',

        autoprefixer: {
          browsers: ['> 1%', 'last 3 versions', 'IE 8']
        },

        sass: {
        }
      },

      dev: {

        sass: {
          outputStyle: 'expanded'
        }
      },

      prod: {

        sourceMaps: false,

        sass: {
          outputStyle: 'compressed'
        }
      }
    },

    sprites: {

      items: [
        //you can add more items (dirs), simply add an element
        {
          imgSource: dirs.src.img + 'sprites/',
          imgDest: dirs.dist.img,
          //additional options passed to the plugin
          options: {
            imgName: 'sprites.png',
            imgPath: '../img/sprites.png',
            cssName: '_sprites.scss',
          }
        }
      ]
    },

    js: {
      common: {
        sourceMaps: true,
        sourceMapsRoot: '/src/',
        minify: false,
        concatVendorApp: true,    //if true, app.js and vendor.js are merged into app.js
        vendorFilter: ['**/*.js'],

        mainBowerFiles: {
          paths: {
            bowerDirectory: dirs.vendor,
            bowerrc: dirs.app + '.bowerrc',
            bowerJson: dirs.app + 'bower.json'
          },
          overrides: {}
        },

        //add script filenames/globs (relative to the appropriate dirs) to be loaded first
        priority: {
          vendor: {
            beforeBower: [],  //before bower components load
            afterBower: [],   //before dirs.src.js.vendor load (you usually need this one)
          },
          app: [] //ex: ['core.js']
        },

        jsHint: {
          enable: true,
          options: {},
          reporter: 'default'
        }
      },

      dev: {
      },

      prod: {
        sourceMaps: false,
        minify: true,

        jsHint: {
          enable: false
        }
      }
    },

    views: {

      common: {
        useSwig: true,
        swig: {
          defaults: { cache: false },
          setup: function(swig) {
            swig.setDefaults({
              //set base dir
              loader: swig.loaders.fs(dirs.src.views.layouts)
            });
          },
          //variable context (data) passed to all templates
          data: {}
        }
      },

      dev: {
        swig: {

        }
      },

      prod: {
        swig: {

        }
      }
    },

    images: {
      imagemin: {
        optimizationLevel: 0,
        progressive: true,
        interlaced: true
      }
    },

    browserSync: {
      common: {
        enable: true,  //for prod, applies prod:preview

        options: {
          //tip: set to [project-name].localhost and uncomment the "open: external" option
          host: 'localhost',
          //open: 'external',
          port: 80,
          reloadOnRestart: true,
          server: {
            baseDir: dirs.dist.main
          }
        }
      },

      dev: {

      },

      prod: {
      }
    },

    clean: {
      //set to true for default config dir value, false to block deletion
      //or pass any glob pattern as an array (e.g. "styles: [dirs.dist.styles + 'style.css']" to delete only this one file)
      dist: false,       //only true/false; if true, whole dist dir is deleted
      styles: true,
      sprites: true,    //only true/false; set to false to block deletion of any generated by spritesmith SASS file in the src directory
      fonts: true,
      js: true,
      img: true,
      views: true,
      custom: true      //only true/false; set to false to block deletion of any custom dir
    }
  }

  //custom config file
  try {
    require(dirs.app + dirs.user.configFile)(config, dirs);
  }
  catch (ex) {
    console.log('Frontend-starter warning: no custom config definitions file present (' + dirs.user.configFile + ').');
    //process.exit(1);
  }

  return config;
}
<commit_msg>jshint disabled by default<commit_after>/**
  Frontend-starter

  @author Bartosz Sak, Archas

  https://github.com/implico/frontend-starter

  The MIT License (MIT)

  *******************
  Configuration file

*/

module.exports = function(dirs) {

  var config = {

    styles: {

      common: {
        sourceMaps: true,
        sourceMapsRoot: '/src/styles/',

        autoprefixer: {
          browsers: ['> 1%', 'last 3 versions', 'IE 8']
        },

        sass: {
        }
      },

      dev: {

        sass: {
          outputStyle: 'expanded'
        }
      },

      prod: {

        sourceMaps: false,

        sass: {
          outputStyle: 'compressed'
        }
      }
    },

    sprites: {

      items: [
        //you can add more items (dirs), simply add an element
        {
          imgSource: dirs.src.img + 'sprites/',
          imgDest: dirs.dist.img,
          //additional options passed to the plugin
          options: {
            imgName: 'sprites.png',
            imgPath: '../img/sprites.png',
            cssName: '_sprites.scss',
          }
        }
      ]
    },

    js: {
      common: {
        sourceMaps: true,
        sourceMapsRoot: '/src/',
        minify: false,
        concatVendorApp: true,    //if true, app.js and vendor.js are merged into app.js
        vendorFilter: ['**/*.js'],

        mainBowerFiles: {
          paths: {
            bowerDirectory: dirs.vendor,
            bowerrc: dirs.app + '.bowerrc',
            bowerJson: dirs.app + 'bower.json'
          },
          overrides: {}
        },

        //add script filenames/globs (relative to the appropriate dirs) to be loaded first
        priority: {
          vendor: {
            beforeBower: [],  //before bower components load
            afterBower: [],   //before dirs.src.js.vendor load (you usually need this one)
          },
          app: [] //ex: ['core.js']
        },

        jsHint: {
          enable: false,
          options: {},
          reporter: 'default'
        }
      },

      dev: {
      },

      prod: {
        sourceMaps: false,
        minify: true,

        jsHint: {
          enable: false
        }
      }
    },

    views: {

      common: {
        useSwig: true,
        swig: {
          defaults: { cache: false },
          setup: function(swig) {
            swig.setDefaults({
              //set base dir
              loader: swig.loaders.fs(dirs.src.views.layouts)
            });
          },
          //variable context (data) passed to all templates
          data: {}
        }
      },

      dev: {
        swig: {

        }
      },

      prod: {
        swig: {

        }
      }
    },

    images: {
      imagemin: {
        optimizationLevel: 0,
        progressive: true,
        interlaced: true
      }
    },

    browserSync: {
      common: {
        enable: true,  //for prod, applies prod:preview

        options: {
          //tip: set to [project-name].localhost and uncomment the "open: external" option
          host: 'localhost',
          //open: 'external',
          port: 80,
          reloadOnRestart: true,
          server: {
            baseDir: dirs.dist.main
          }
        }
      },

      dev: {

      },

      prod: {
      }
    },

    clean: {
      //set to true for default config dir value, false to block deletion
      //or pass any glob pattern as an array (e.g. "styles: [dirs.dist.styles + 'style.css']" to delete only this one file)
      dist: false,       //only true/false; if true, whole dist dir is deleted
      styles: true,
      sprites: true,    //only true/false; set to false to block deletion of any generated by spritesmith SASS file in the src directory
      fonts: true,
      js: true,
      img: true,
      views: true,
      custom: true      //only true/false; set to false to block deletion of any custom dir
    }
  }

  //custom config file
  try {
    require(dirs.app + dirs.user.configFile)(config, dirs);
  }
  catch (ex) {
    console.log('Frontend-starter warning: no custom config definitions file present (' + dirs.user.configFile + ').');
    //process.exit(1);
  }

  return config;
}
<|endoftext|>


<commit_before>new RestService();<commit_msg>making sure the test passes<commit_after>new RestService({
	baseUrl: '',
	operations: {}
});<|endoftext|>


<commit_before>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    return (a > b ? -1 : (a < b ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'http://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      });

      releaseTitle.innerHTML = version + ' for ' + info.servers[selectedServer];

      var d = new Date(release.date);
      dateSpan.innerHTML = d.getDate() + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer === 'ibm-was' || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<commit_msg>fix(release-date): correct the ee download release dates<commit_after>'use strict';
/*jshint browser: true*/

/*global require: false*/
var utils = require('./utils');

var months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

var attr = utils.attr;
var query = utils.query;
var mkEl = utils.mkEl;
var keys = utils.keys;
var tmpl = utils.tmpl;

function mkListItems(target, texts, clickCb, that) {
  var items = [];
  that = that || {};

  texts.forEach(function (text, i) {
    var el = mkEl('li');
    el.innerHTML = '' + text + '';

    el.addEventListener('click', function (evt) {
      evt.preventDefault();
      items.forEach(function (e) {
        var cl = e.classList;
        if (e === el) {
          if (!cl.contains('active')) {
            cl.add('active');
          }
        }
        else {
          cl.remove('active');
        }
      });

      clickCb.call(that, i, el);
    });

    target.appendChild(el);

    items.push(el);
  });

  return items;
}

function camDownloadsWidget(info, holder) {
  var majorList = query('ul.major', holder);
  var patchList = query('ul.patch', holder);
  var serverList = query('ul.server', holder);
  var infoDiv = query('.selected-server', holder);
  var standaloneDiv = query('.standalone', infoDiv);

  var releaseTitle = query('.info h3', holder);
  var notesA = query('a.notes', holder);
  var dateSpan = query('span.date', holder);
  var zipA = query('a.zip', holder);
  var targzA = query('a.tar-gz', holder);
  var warA = query('a.war', holder);

  var branches = keys(info.branches).sort(function (a, b) {
    return (a > b ? -1 : (a < b ? 1 : 0));
  });

  function getReleaseInfo(branch, version) {
    return info.branches[branch].find(function (release) {
      return release.number === version;
    });
  }

  function getBranchVersions(branch) {
    return info.branches[branch].map(function (release) {
      return release.number;
    }).filter(function (item) { return !!item; });
  }

  function getServers(release) {
    var servers = keys(info.servers);
    if (release.excludeServers) {
      servers = servers.filter(function (name) {
        return release.excludeServers.indexOf(name) < 0;
      });
    }
    return servers;
  }

  var dlBasePath = 'http://camunda.org/enterprise-release/camunda-bpm/';
  function mkServerClickHandler(servers, version, branch) {
    return function (s) {
      var selectedServer = servers[s];
      var release = getReleaseInfo(branch, version);
      infoDiv.classList.add('accessible');

      var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{server}-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      });

      releaseTitle.innerHTML = version + ' for ' + info.servers[selectedServer];

      var parts = release.date.split('.').map(function (part) {
        return parseInt(part, 10);
      });
      dateSpan.innerHTML = parts[2] + ' ' + months[parts[1]] + ' ' + parts[0];

      attr(notesA, 'href', release.note);

      attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
        version:  version,
        branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
        server:   selectedServer
      }) + '.war');

      attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

      attr(zipA, 'href', dlBasePath + dl + '.zip');

      if (selectedServer === 'ibm-was' || selectedServer === 'oracle-wls') {
        dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        });

        attr(targzA, 'href', dlBasePath + dl + '.tar.gz');

        attr(zipA, 'href', dlBasePath + dl + '.zip');

        attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', {
          version:  version,
          branch:   (version.indexOf('alpha') > -1) ? 'nightly' : branch,
          vendor:   selectedServer.split('-')[0],
          server:   selectedServer.split('-')[1]
        }) + '.war');
      }

      if (release.excludeFormats && release.excludeFormats.indexOf('war') > -1) {
        standaloneDiv.style.display = 'none';
      }
      else {
        standaloneDiv.style.display = 'block';
      }
    };
  }

  function mkVersionClickHandler(branchName) {
    var patchReleases = getBranchVersions(branchName);

    return function selectVersion(r) {
      serverList.innerHTML = '';

      infoDiv.classList.remove('accessible');

      var selectedVersion = patchReleases[r];

      var releaseInfo = getReleaseInfo(branchName, selectedVersion);

      var releaseServers = getServers(releaseInfo);

      return mkListItems(serverList, releaseServers.map(function (name) {
        return info.servers[name];
      }), mkServerClickHandler(releaseServers, selectedVersion, branchName));
    };
  }

  function selectBranch(b) {
    patchList.innerHTML = '';

    serverList.innerHTML = '';

    infoDiv.classList.remove('accessible');

    var branchName = branches[b];

    var patchReleases = getBranchVersions(branchName);

    return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName));
  }

  var branchEls = mkListItems(majorList, branches, selectBranch);

  if (info.selected) {
    var b = branches.indexOf(info.selected.branch);

    var versionEls = selectBranch(b);

    branchEls[b].classList.add('active');

    var patchReleases = getBranchVersions(branches[b]);

    var v = patchReleases.indexOf(info.selected.version);

    var serverEls = mkVersionClickHandler(branches[b])(v);

    versionEls[v].classList.add('active');

    var servers = getServers(patchReleases[v]);

    var s = servers.indexOf(info.selected.server);

    serverEls[s].classList.add('active');

    mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s);
  }
}

var camDownloadsEl = query('.cam-downloads');
if (window.camDownloads && camDownloadsEl) {
  camDownloadsWidget(window.camDownloads, camDownloadsEl);
}
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = function (_options) {
  checkJava();

  var options = formatOptions(_options);
  var parserDir = getParserDir(options);
  var mode = getMode(options);
  var ANTLR4 = getClasses(options);

  return _through2.default.obj(function (file, encoding, callback) {
    var _this = this;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, 'Streams not supported (yet)!'));
    } else if (file.isBuffer()) {
      var inputFile = file.history[0];

      switch (_path2.default.extname(inputFile)) {
        case '.g4':
          var args = ['org.antlr.v4.Tool', '-Dlanguage=JavaScript', '-o', parserDir];
          if (mode === 'visitor' || mode === 'both') {
            args.push('-visitor');
          }
          if (mode !== 'listener' && mode !== 'both') {
            args.push('-no-listener');
          }
          args.push(inputFile);
          return (0, _childProcessData2.default)((0, _child_process.spawn)('java', args)).then(function () {
            callback(null, file);
          }, function (err) {
            _this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
            callback(null, file);
          });

        default:
          if (ANTLR4.isProperlySetup()) {
            var data = file.contents.toString('utf8');
            var chars = new _antlr.InputStream(data, true);
            var lexer = new ANTLR4.Lexer(chars);
            var tokens = new _antlr.CommonTokenStream(lexer);
            var parser = new ANTLR4.Parser(tokens);
            parser.buildParseTrees = true;
            var tree = parser[ANTLR4.rule]();

            switch (mode) {
              case 'tree':
                console.log(tree.toStringTree(parser.ruleNames));
                break;

              case 'listener':
                new Promise(function (resolve, reject) {
                  var walker = new _tree.ParseTreeWalker();
                  var listener = new ANTLR4.Listener(resolve, reject);
                  walker.walk(listener, tree);
                }).then(function () {
                  _this.emit('finish');
                }, function (err) {
                  _this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
                });
                return;

              case 'visitor':
                try {
                  var visitor = new ANTLR4.Visitor();

                  Promise.resolve(visitor.visit(tree)).then(function () {
                    _this.emit('finish');
                  });

                  return; // Don't use callback but rely on above Promise
                  // to emit eventually the proper 'finish' event
                } catch (err) {
                  this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
                }
                break;
            }
          }

          return callback(null, file);
      }
    }
  });
};

var _gulpUtil = require('gulp-util');

var _through = require('through2');

var _through2 = _interopRequireDefault(_through);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _child_process = require('child_process');

var _childProcessData = require('child-process-data');

var _childProcessData2 = _interopRequireDefault(_childProcessData);

var _antlr = require('antlr4');

var _tree = require('antlr4/tree');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PLUGIN_NAME = 'gulp-antlr4';

function checkJava() {
  var CLASSPATH = process.env.CLASSPATH;

  if (!CLASSPATH) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Environment variable CLASSPATH is not defined;\nJava is not installed or is improperly set'));
  }

  // Not matching '~' as it is not understood by Java anyway
  var matchJar = CLASSPATH.match(/.*:((\d|\w|\/|-|_|\.)+antlr-\d+\.\d+-complete\.jar):.*/);

  if (matchJar === null) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Cannot find ANTLR4 .jar file;\nIt should appear in your CLASSPATH'));
  }
}

function formatOptions(options) {
  if (typeof options === 'string') {
    return { parserDir: options };
  }
  return (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? Object.assign({
    listenerDir: options.parserDir, // Default is same dir
    visitorDir: options.parserDir }, options) : {};
}

function getParserDir(options) {
  var parserDir = options.parserDir;

  if (typeof parserDir !== 'string') {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('You must provide the directory where to write or read\n     the generated lexing and parsing tools (option \'parserDir\')'));
  }

  return parserDir;
}

function getMode(options) {
  var mode = options.mode,
      listener = options.listener,
      visitor = options.visitor;

  if (typeof mode !== 'string' && mode !== undefined) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('Bad option: ' + mode));
  }

  if (listener && visitor) {
    return 'both';
  }

  if (listener) {
    return 'listener';
  }

  if (visitor) {
    return 'visitor';
  }

  return mode || 'listener';
}

function getClasses(options) {
  var grammar = options.grammar;

  if (!grammar) {
    return {
      isProperlySetup: function isProperlySetup() {
        return false;
      }
    };
  }

  return {
    rule: getRule(options),
    Lexer: getLexer(options),
    Parser: getParser(options),
    Listener: getListener(options),
    Visitor: getVisitor(options),
    isProperlySetup: function isProperlySetup() {
      return true;
    }
  };
}

function getRule(options) {
  var rule = options.rule;

  if (!rule) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, 'Undefined starting rule (option \'rule\')');
  }

  return rule;
}

function getLexer(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var lexer = grammar + 'Lexer';

  return requireAfresh(lexer, parserDir);
}

function getParser(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var parser = grammar + 'Parser';

  return requireAfresh(parser, parserDir);
}

function getListener(options) {
  var listener = options.listener,
      listenerDir = options.listenerDir;

  if (!listener) {
    return;
  }

  return requireAfresh(listener, listenerDir);
}

function getVisitor(options) {
  var visitor = options.visitor,
      visitorDir = options.visitorDir;

  if (!visitor) {
    return;
  }

  return requireAfresh(visitor, visitorDir);
}

function requireAfresh(name, dir) {
  // Convert relative to absolute path
  var base = process.cwd();
  var rel = _path2.default.relative(base, dir);
  var file = _path2.default.join(base, rel, name);

  // Don't cache parser files
  if (require.cache && require.cache[file]) {
    delete require.cache[file];
  }

  return require(file)[name];
}
module.exports = exports['default'];<commit_msg>prepublish<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.default = function (_options) {
  checkJava();

  var options = formatOptions(_options);
  var parserDir = getParserDir(options);
  var mode = getMode(options);
  var ANTLR4 = getClasses(options);

  return _through2.default.obj(function (file, encoding, callback) {
    var _this = this;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      (0, _streamToArray2.default)(file.contents).then(function (parts) {
        consumeData({
          data: _buffer.Buffer.concat(parts).toString(encoding),
          ANTLR4: ANTLR4, mode: mode,
          ctx: _this
        });
      });
    } else if (file.isBuffer()) {
      var inputFile = file.history[0];

      switch (_path2.default.extname(inputFile)) {
        case '.g4':
          var args = ['org.antlr.v4.Tool', '-Dlanguage=JavaScript', '-o', parserDir];
          if (mode === 'visitor' || mode === 'both') {
            args.push('-visitor');
          }
          if (mode !== 'listener' && mode !== 'both') {
            args.push('-no-listener');
          }
          args.push(inputFile);
          return (0, _childProcessData2.default)((0, _child_process.spawn)('java', args)).then(function () {
            callback(null, file);
          }, function (err) {
            _this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
            callback(null, file);
          });

        default:
          if (ANTLR4.isProperlySetup()) {
            consumeData({
              data: file.contents.toString('utf8'),
              ANTLR4: ANTLR4, mode: mode,
              ctx: this
            });
          }
      }
    }
  });
};

var _streamToArray = require('stream-to-array');

var _streamToArray2 = _interopRequireDefault(_streamToArray);

var _buffer = require('buffer');

var _gulpUtil = require('gulp-util');

var _through = require('through2');

var _through2 = _interopRequireDefault(_through);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _child_process = require('child_process');

var _childProcessData = require('child-process-data');

var _childProcessData2 = _interopRequireDefault(_childProcessData);

var _antlr = require('antlr4');

var _tree = require('antlr4/tree');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PLUGIN_NAME = 'gulp-antlr4';

function checkJava() {
  var CLASSPATH = process.env.CLASSPATH;

  if (!CLASSPATH) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Environment variable CLASSPATH is not defined;\nJava is not installed or is improperly set'));
  }

  // Not matching '~' as it is not understood by Java anyway
  var matchJar = CLASSPATH.match(/.*:((\d|\w|\/|-|_|\.)+antlr-\d+\.\d+-complete\.jar):.*/);

  if (matchJar === null) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Cannot find ANTLR4 .jar file;\nIt should appear in your CLASSPATH'));
  }
}

function formatOptions(options) {
  if (typeof options === 'string') {
    return { parserDir: options };
  }
  return (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? Object.assign({
    listenerDir: options.parserDir, // Default is same dir
    visitorDir: options.parserDir }, options) : {};
}

function getParserDir(options) {
  var parserDir = options.parserDir;

  if (typeof parserDir !== 'string') {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('You must provide the directory where to write or read\n     the generated lexing and parsing tools (option \'parserDir\')'));
  }

  return parserDir;
}

function getMode(options) {
  var mode = options.mode,
      listener = options.listener,
      visitor = options.visitor;

  if (typeof mode !== 'string' && mode !== undefined) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('Bad option: ' + mode));
  }

  if (listener && visitor) {
    return 'both';
  }

  if (listener) {
    return 'listener';
  }

  if (visitor) {
    return 'visitor';
  }

  return mode || 'listener';
}

function getClasses(options) {
  var grammar = options.grammar;

  if (!grammar) {
    return {
      isProperlySetup: function isProperlySetup() {
        return false;
      }
    };
  }

  return {
    rule: getRule(options),
    Lexer: getLexer(options),
    Parser: getParser(options),
    Listener: getListener(options),
    Visitor: getVisitor(options),
    isProperlySetup: function isProperlySetup() {
      return true;
    }
  };
}

function getRule(options) {
  var rule = options.rule;

  if (!rule) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, 'Undefined starting rule (option \'rule\')');
  }

  return rule;
}

function getLexer(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var lexer = grammar + 'Lexer';

  return requireAfresh(lexer, parserDir);
}

function getParser(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var parser = grammar + 'Parser';

  return requireAfresh(parser, parserDir);
}

function getListener(options) {
  var listener = options.listener,
      listenerDir = options.listenerDir;

  if (!listener) {
    return;
  }

  return requireAfresh(listener, listenerDir);
}

function getVisitor(options) {
  var visitor = options.visitor,
      visitorDir = options.visitorDir;

  if (!visitor) {
    return;
  }

  return requireAfresh(visitor, visitorDir);
}

function requireAfresh(name, dir) {
  // Convert relative to absolute path
  var base = process.cwd();
  var rel = _path2.default.relative(base, dir);
  var file = _path2.default.join(base, rel, name);

  // Don't cache parser files
  if (require.cache && require.cache[file]) {
    delete require.cache[file];
  }

  return require(file)[name];
}

function consumeData(_ref) {
  var data = _ref.data,
      ANTLR4 = _ref.ANTLR4,
      ctx = _ref.ctx,
      mode = _ref.mode;

  var chars = new _antlr.InputStream(data, true);
  var lexer = new ANTLR4.Lexer(chars);
  var tokens = new _antlr.CommonTokenStream(lexer);
  var parser = new ANTLR4.Parser(tokens);
  parser.buildParseTrees = true;
  var tree = parser[ANTLR4.rule]();

  switch (mode) {
    case 'tree':
      console.log(tree.toStringTree(parser.ruleNames));
      return;

    case 'listener':
      new Promise(function (resolve, reject) {
        var walker = new _tree.ParseTreeWalker();
        var listener = new ANTLR4.Listener(resolve, reject);
        walker.walk(listener, tree);
      }).then(function () {
        ctx.emit('finish');
      }, function (err) {
        ctx.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
      });
      return;

    case 'visitor':
      try {
        var visitor = new ANTLR4.Visitor();

        Promise.resolve(visitor.visit(tree)).then(function () {
          ctx.emit('finish');
        });

        return; // Don't use callback but rely on above Promise
        // to emit eventually the proper 'finish' event
      } catch (err) {
        ctx.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, err));
      }
      break;
  }
}
module.exports = exports['default'];<|endoftext|>


<commit_before>// MIT License
//
// Copyright (c) 2012 AdCloud GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict";

function parse_lang_range(lang_range) {
	var reg = /^([a-z]{2}|\*)(-([a-z]{2}))?(;q=[0-9.]*)?$/i;
	var match = lang_range.trim().match(reg);

	if (match) {
		var result = {};
		if (match[1]) { // language
			result.language = match[1].toLowerCase();
		}
		if (match[3]) { // locale
			result.locale = match[3].toUpperCase();
		}
		return result;
	}
	return undefined;
}

function extractFirstLang(acc_lang_header) {
	// return if input is invalid
	if (!acc_lang_header) {
		return undefined;
	}

	var split = acc_lang_header.split(",");
	if (split[0]) {
		return parse_lang_range(split[0]);
	} else {
		return undefined;
	}
}

function extractAllLangs(acc_lang_header) {
	// return if input is invalid
	if (!acc_lang_header) {
		return [];
	}

	var split = acc_lang_header.split(",");
	if (split.length > 0) {
		var result = [];
		split.forEach(function (i) {
			var extretion = parse_lang_range(i);
			if (extretion) {
				result.push(extretion);
			}
		});

		return result;
	} else {
		return undefined;
	}
}

exports.extractFirstLang = extractFirstLang;
exports.extractAllLangs = extractAllLangs;
<commit_msg>made lib code more nodejs stylish<commit_after>// MIT License
//
// Copyright (c) 2012 AdCloud GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"use strict";

function parseLangRange(lang_range) {
	var reg = /^([a-z]{2}|\*)(-([a-z]{2}))?(;q=[0-9.]*)?$/i;
	var match = lang_range.trim().match(reg);

	if (match) {
		var result = {};
		if (match[1]) { // language
			result.language = match[1].toLowerCase();
		}
		if (match[3]) { // locale
			result.locale = match[3].toUpperCase();
		}
		return result;
	}
	return undefined;
}

function extractFirstLang(accLangHeader) {
	// return if input is invalid
	if (!accLangHeader) {
		return undefined;
	}

	var split = accLangHeader.split(",");
	if (split[0]) {
		return parseLangRange(split[0]);
	} else {
		return undefined;
	}
}

function extractAllLangs(accLangHeader) {
	// return if input is invalid
	if (!accLangHeader) {
		return [];
	}

	var split = accLangHeader.split(",");
	if (split.length > 0) {
		var result = [];
		split.forEach(function (i) {
			var extretion = parseLangRange(i);
			if (extretion) {
				result.push(extretion);
			}
		});

		return result;
	} else {
		return [];
	}
}

exports.extractFirstLang = extractFirstLang;
exports.extractAllLangs = extractAllLangs;
<|endoftext|>


<commit_before>"use strict";

// Disable pending items / Fix focus for docked tree-view
atom.workspace.onDidAddPaneItem(event => {
	const {pane} = event;
	if(!atom.config.get("user.enable-pending-items"))
		pane.setPendingItem(null);
	pane.focus();
});

// Match brackets inside regular expressions and CSON strings
const BracketMatcher = loadFromCore("bracket-matcher/lib/bracket-matcher-view");
const {isScopeCommentedOrString} = BracketMatcher.prototype;
BracketMatcher.prototype.isScopeCommentedOrString = function(...args){
	if(args[0].some(scopeList => /^string\.quoted.*?\.coffee$/.test(scopeList))
	|| args[0].some(scopeList => /^string\b.*?\.regexp(?:$|\.)/.test(scopeList)
	&& args[0].some(scopeList => scopeList.split(".").includes("string"))))
		return false;
	return isScopeCommentedOrString.call(this, ...args);
};

// Increase token limit
loadGrammar("source.js").then(js => js.maxTokensPerLine = 500);

// Define custom filetypes without upsetting File Icons
loadGrammar("source.json").then(json =>
	json.fileTypes.push("css.map", "js.map", "mjs.map", "terserrc", "nycrc"));

// Fix idiotic filetype associations
const fixGrammars = {
	"source.shell": ["install"],
	"text.html.php": ["install", "profile", "module", "inc"],
};
for(const scope in fixGrammars)
	loadGrammar(scope).then(grammar => {
		grammar.fileTypes = grammar.fileTypes.filter(type => {
			return !fixGrammars[scope].includes(type);
		});
	});

// Wipe junk <template/> elements added to <body> after a notification
atom.notifications.onDidAddNotification(note => {
	for(const el of document.querySelectorAll("body > template"))
		document.body.removeChild(el);
});

// Remind grammar-selector I don't give a fuck about tree-shitter
const {getGrammars} = atom.grammars;
atom.grammars.getGrammars = function(params){
	return getGrammars.call(this, {...params, includeTreeSitter: false});
};

// Exclude subdirectories in ~/.atom/packages which *aren't* packages…
const PackageList = loadFromCore("settings-view/lib/list.js");
const {setItems} = PackageList.prototype;
PackageList.prototype.setItems = function(items){
	items = items.filter(item => "patches" !== item.name);
	return setItems.call(this, items);
};

// Force Java to be listed after JavaScript in the grammar-selector
loadGrammar("source.java").then(java => java.name = `\x7F${java.name}`);

// Force `.npmrc` files to use proper grammar instead of INI
atom.workspace.observeTextEditors(ed => {
	if(/^\.?npmrc$/i.test(ed.getFileName()))
		ed.setGrammar(atom.grammars.grammarForId("source.ini.npmrc"));
});

// Purge context-menus of commands I rarely/never use
for(const {items, selector} of atom.contextMenu.itemSets)
	for(let i = items.length - 1; i >= 0; --i){
		const {command} = items[i];
		if(/.tree-view/.test(selector) && "split-diff:enable" === command
		|| /^tree-view:(duplicate|open-selected-entry-\w+)$/.test(command)
		|| /^pane:split-\w+-and-copy-active-item$/.test(command))
			items.splice(i, 1);
	}

// Tidy config to reduce diff-noise
const stringLists = [
	"core.disabledPackages",
	"markdown-preview.grammars",
	"spell-check.grammars",
];
for(const key of stringLists){
	const currentValue = atom.config.get(key);
	const sortedValue = [...new Set(currentValue)].sort();
	if(currentValue.join("\n") !== sortedValue.join("\n"))
		atom.config.set(key, sortedValue);
}

// Delete settings which aren't meant to linger around
const ephemeralKeys = ["user:enable-pending-items"];
for(const keyPath of ephemeralKeys){
	if(undefined !== atom.config.getRawValue(keyPath))
		atom.config.unset(keyPath);
}

// Fix TypeError thrown when reloading window
for(const key of atom.blobStore.inMemoryBlobs.keys())
	if(atom.blobStore.usedKeys.has(key) && !atom.blobStore.getFromMemory(key))
		atom.blobStore.delete(key);
<commit_msg>Update built-in filetype mappings<commit_after>"use strict";

// Disable pending items / Fix focus for docked tree-view
atom.workspace.onDidAddPaneItem(event => {
	const {pane} = event;
	if(!atom.config.get("user.enable-pending-items"))
		pane.setPendingItem(null);
	pane.focus();
});

// Match brackets inside regular expressions and CSON strings
const BracketMatcher = loadFromCore("bracket-matcher/lib/bracket-matcher-view");
const {isScopeCommentedOrString} = BracketMatcher.prototype;
BracketMatcher.prototype.isScopeCommentedOrString = function(...args){
	if(args[0].some(scopeList => /^string\.quoted.*?\.coffee$/.test(scopeList))
	|| args[0].some(scopeList => /^string\b.*?\.regexp(?:$|\.)/.test(scopeList)
	&& args[0].some(scopeList => scopeList.split(".").includes("string"))))
		return false;
	return isScopeCommentedOrString.call(this, ...args);
};

// Increase token limit
loadGrammar("source.js").then(js => js.maxTokensPerLine = 500);

// Define custom filetypes without upsetting File Icons
loadGrammar("source.json").then(json =>
	json.fileTypes.push("css.map", "js.map", "mjs.map", "terserrc", "nycrc", "c8rc", "hintrc"));

// Fix idiotic and/or conflicting filetype associations
const fixGrammars = {
	"source.shell": ["install"],
	"text.html.php": ["install", "profile", "module", "inc"],
	"text.xml": ["svg"],
};
for(const scope in fixGrammars)
	loadGrammar(scope).then(grammar => {
		grammar.fileTypes = grammar.fileTypes.filter(type => {
			return !fixGrammars[scope].includes(type);
		});
	});

// Wipe junk <template/> elements added to <body> after a notification
atom.notifications.onDidAddNotification(note => {
	for(const el of document.querySelectorAll("body > template"))
		document.body.removeChild(el);
});

// Remind grammar-selector I don't give a fuck about tree-shitter
const {getGrammars} = atom.grammars;
atom.grammars.getGrammars = function(params){
	return getGrammars.call(this, {...params, includeTreeSitter: false});
};

// Exclude subdirectories in ~/.atom/packages which *aren't* packages…
const PackageList = loadFromCore("settings-view/lib/list.js");
const {setItems} = PackageList.prototype;
PackageList.prototype.setItems = function(items){
	items = items.filter(item => "patches" !== item.name);
	return setItems.call(this, items);
};

// Force Java to be listed after JavaScript in the grammar-selector
loadGrammar("source.java").then(java => java.name = `\x7F${java.name}`);

// Force `.npmrc` files to use proper grammar instead of INI
atom.workspace.observeTextEditors(ed => {
	if(/^\.?npmrc$/i.test(ed.getFileName()))
		ed.setGrammar(atom.grammars.grammarForId("source.ini.npmrc"));
});

// Purge context-menus of commands I rarely/never use
for(const {items, selector} of atom.contextMenu.itemSets)
	for(let i = items.length - 1; i >= 0; --i){
		const {command} = items[i];
		if(/.tree-view/.test(selector) && "split-diff:enable" === command
		|| /^tree-view:(duplicate|open-selected-entry-\w+)$/.test(command)
		|| /^pane:split-\w+-and-copy-active-item$/.test(command))
			items.splice(i, 1);
	}

// Tidy config to reduce diff-noise
const stringLists = [
	"core.disabledPackages",
	"markdown-preview.grammars",
	"spell-check.grammars",
];
for(const key of stringLists){
	const currentValue = atom.config.get(key);
	const sortedValue = [...new Set(currentValue)].sort();
	if(currentValue.join("\n") !== sortedValue.join("\n"))
		atom.config.set(key, sortedValue);
}

// Delete settings which aren't meant to linger around
const ephemeralKeys = ["user:enable-pending-items"];
for(const keyPath of ephemeralKeys){
	if(undefined !== atom.config.getRawValue(keyPath))
		atom.config.unset(keyPath);
}

// Fix TypeError thrown when reloading window
for(const key of atom.blobStore.inMemoryBlobs.keys())
	if(atom.blobStore.usedKeys.has(key) && !atom.blobStore.getFromMemory(key))
		atom.blobStore.delete(key);
<|endoftext|>


<commit_before>var _get=function(b,c,g){var d=!0;for(;d;)if(null===b&&(b=Function.prototype),d=Object.getOwnPropertyDescriptor(b,c),void 0===d){b=Object.getPrototypeOf(b);if(null===b)break;d=!0}else{if("value"in d)return d.value;c=d.get;return void 0===c?void 0:c.call(g)}},_createClass=function(){function b(c,b){for(var d=0;d<b.length;d++){var e=b[d];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(c,e.key,e)}}return function(c,g,d){g&&b(c.prototype,g);d&&b(c,d);
return c}}();function _inherits(b,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);b.prototype=Object.create(c&&c.prototype,{constructor:{value:b,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(b,c):b.__proto__=c)}function _classCallCheck(b,c){if(!(b instanceof c))throw new TypeError("Cannot call a class as a function");}
(function(){var b=this,c=[" ","\u3000"],g={isEmpty:function(a){a=""+a;return null===a||0>=a.length},isNotEmpty:function(a){return!isEmpty(a)},isBlank:function(a){a=""+a;var f=a.length,b=void 0,d=void 0;if(null===a||0===f)return!0;for(b=0;b<f;b++)if(d=a.charAt(b),-1==c.indexOf(d))return!1;return!0},isNotBlank:function(a){return!isBlank(a)},trim:function(a){a=""+a;return null===a?null:a.trim()},trimToNull:function(a){a=b.trim(a);return null===a||0===a.length?null:a},createPlaceholder:function(a,f){var b=
(a+",").repeat(f).split(",");b.pop();return b}},d=function(a){function f(){_classCallCheck(this,f);_get(Object.getPrototypeOf(f.prototype),"constructor",this).apply(this,arguments)}_inherits(f,a);_createClass(f,[{key:"getInputValue",value:function(){var a=_get(Object.getPrototypeOf(f.prototype),"getIdDom",this).call(this).value;return g.isBlank(a)?(console.info("not blank, errorCode [-1]"),-1):a}}]);return f}(function(){function a(f){_classCallCheck(this,a);this._id=document.getElementById(f)}_createClass(a,
[{key:"getIdDom",value:function(){return this._id}},{key:"isNotEquals",value:function(a){return this.getIdDom().innerText!==a}}]);return a}()),e=function(){function a(){_classCallCheck(this,a);this.__urls=(new Map).set("YAHOO","http://search.yahoo.co.jp/search?p=").set("GITHUB","https://github.com/search?utf8=\u2713&q=").set("STACKOVERFLOW","http://stackoverflow.com/search?q=").set("NONE","")}_createClass(a,[{key:"getUrl",value:function(a,b){return this.__urls.get(a)+b}}]);return a}(),l=function(){function a(){_classCallCheck(this,
a);this.__times=(new Map).set(1,{hour:17,minute:45}).set(2,{hour:17,minute:45}).set(3,{hour:17,minute:45}).set(4,{hour:17,minute:45}).set(5,{hour:17,minute:45}).set(6,{hour:0,minute:0}).set(7,{hour:0,minute:0})}_createClass(a,[{key:"getRemainTime",value:function(){var a=new Date,b=this.__times.get(a.getDay()),c=b.hour-a.getHours(),a=b.minute-a.getMinutes();0>a&&(c--,a+=60);return{hour:c,minute:a}}}]);return a}(),m=function(){function a(b){_classCallCheck(this,a);this.__tblName=b}_createClass(a,[{key:"createInsert",
value:function(a,b){var c=this;if(null===a||void 0===a||null===b||void 0===b)return!1;var d="",e="",g=[],k=0,h=0;a.forEach(function(a){0!==k&&(d+=",");d+=a;k++});b.forEach(function(a){a.forEach(function(a){0!==h&&(e+=",");e+=a;h++});g.push("insert into "+c.__tblName+" ("+d+") values ("+e+");");h=0;e=""});return g}}]);return a}();this.ERROR_CODE_BLANK=-1;this.StringUtils=g;this.InputDom=d;this.RequestUrls=e;this.Timer=l;this.Sql=m}).call(void 0);
<commit_msg>Update utils.min.js<commit_after>var _get=function(c,b,f){var d=!0;for(;d;)if(null===c&&(c=Function.prototype),d=Object.getOwnPropertyDescriptor(c,b),void 0===d){c=Object.getPrototypeOf(c);if(null===c)break;d=!0}else{if("value"in d)return d.value;b=d.get;return void 0===b?void 0:b.call(f)}},_createClass=function(){function c(b,c){for(var d=0;d<c.length;d++){var e=c[d];e.enumerable=e.enumerable||!1;e.configurable=!0;"value"in e&&(e.writable=!0);Object.defineProperty(b,e.key,e)}}return function(b,f,d){f&&c(b.prototype,f);d&&c(b,d);
return b}}();function _inherits(c,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);c.prototype=Object.create(b&&b.prototype,{constructor:{value:c,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(c,b):c.__proto__=b)}function _classCallCheck(c,b){if(!(c instanceof b))throw new TypeError("Cannot call a class as a function");}
(function(){var c=this,b={isEmpty:function(a){a=""+a;return null===a||0>=a.length},isNotEmpty:function(a){return!isEmpty(a)},isBlank:function(a){var g=[" ","\u3000"];a=""+a;var b=a.length,c=void 0,d=void 0;if(null===a||0===b)return!0;for(c=0;c<b;c++)if(d=a.charAt(c),-1==g.indexOf(d))return!1;return!0},isNotBlank:function(a){return!isBlank(a)},trim:function(a){a=""+a;return null===a?null:a.trim()},trimToNull:function(a){a=c.trim(a);return null===a||0===a.length?null:a},createPlaceholder:function(a,
g){var b=(a+",").repeat(g).split(",");b.pop();return b}},f=function(a){function g(){_classCallCheck(this,g);_get(Object.getPrototypeOf(g.prototype),"constructor",this).apply(this,arguments)}_inherits(g,a);_createClass(g,[{key:"getInputValue",value:function(){var a=_get(Object.getPrototypeOf(g.prototype),"getIdDom",this).call(this).value;return b.isBlank(a)?(console.info("not blank, errorCode [-1]"),-1):a}}]);return g}(function(){function a(g){_classCallCheck(this,a);this._id=document.getElementById(g)}
_createClass(a,[{key:"getIdDom",value:function(){return this._id}},{key:"isNotEquals",value:function(a){return this.getIdDom().innerText!==a}}]);return a}()),d=function(){function a(){_classCallCheck(this,a);this.__urls=(new Map).set("YAHOO","http://search.yahoo.co.jp/search?p=").set("GITHUB","https://github.com/search?utf8=\u2713&q=").set("STACKOVERFLOW","http://stackoverflow.com/search?q=").set("NONE","")}_createClass(a,[{key:"getUrl",value:function(a,b){return this.__urls.get(a)+b}}]);return a}(),
e=function(){function a(){_classCallCheck(this,a);this.__times=(new Map).set(1,{hour:17,minute:45}).set(2,{hour:17,minute:45}).set(3,{hour:17,minute:45}).set(4,{hour:17,minute:45}).set(5,{hour:17,minute:45}).set(6,{hour:0,minute:0}).set(7,{hour:0,minute:0})}_createClass(a,[{key:"getRemainTime",value:function(){var a=new Date,b=this.__times.get(a.getDay()),c=b.hour-a.getHours(),a=b.minute-a.getMinutes();0>a&&(c--,a+=60);return{hour:c,minute:a}}}]);return a}(),m=function(){function a(b){_classCallCheck(this,
a);this.__tblName=b}_createClass(a,[{key:"createInsert",value:function(a,b,c){var d=this;if(null===a||void 0===a||null===b||void 0===b)return!1;var e="",h="",f=[],l=0,k=0;a.forEach(function(a){0!==l&&(e+=",");e+=a;l++});b.forEach(function(a){a.forEach(function(a){0!==k&&(h+=",");h+=a;k++});c?f.push(h):f.push("insert into "+d.__tblName+" ("+e+") values ("+h+");");k=0;h=""});c&&function(){var a="",b=0;f.forEach(function(c){0!==b&&(a+=",");a+="("+c+")";b++});f=[];f.push("insert into "+d.__tblName+" ("+
e+") values "+a+";")}();return f}}]);return a}();this.ERROR_CODE_BLANK=-1;this.StringUtils=b;this.InputDom=f;this.RequestUrls=d;this.Timer=e;this.Sql=m}).call(void 0);
<|endoftext|>