common.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const Pattern = require('hexo-util').Pattern;
  3. const moment = require('moment-timezone');
  4. const minimatch = require('minimatch');
  5. const _ = require('lodash');
  6. const DURATION_MINUTE = 1000 * 60;
  7. function isTmpFile(path) {
  8. const last = path[path.length - 1];
  9. return last === '%' || last === '~';
  10. }
  11. function isHiddenFile(path) {
  12. return /(^|\/)[_\.]/.test(path); // eslint-disable-line no-useless-escape
  13. }
  14. exports.ignoreTmpAndHiddenFile = new Pattern(path => {
  15. if (isTmpFile(path) || isHiddenFile(path)) return false;
  16. return true;
  17. });
  18. exports.isTmpFile = isTmpFile;
  19. exports.isHiddenFile = isHiddenFile;
  20. exports.toDate = date => {
  21. if (!date || moment.isMoment(date)) return date;
  22. if (!(date instanceof Date)) {
  23. date = new Date(date);
  24. }
  25. if (isNaN(date.getTime())) return;
  26. return date;
  27. };
  28. exports.timezone = (date, timezone) => {
  29. if (moment.isMoment(date)) date = date.toDate();
  30. const offset = date.getTimezoneOffset();
  31. const ms = date.getTime();
  32. const target = moment.tz.zone(timezone).utcOffset(ms);
  33. const diff = (offset - target) * DURATION_MINUTE;
  34. return new Date(ms - diff);
  35. };
  36. exports.isMatch = (path, patterns) => {
  37. if (!patterns) return false;
  38. if (!Array.isArray(patterns)) patterns = [patterns];
  39. patterns = _.compact(patterns);
  40. if (!patterns.length) return false;
  41. for (let i = 0, len = patterns.length; i < len; i++) {
  42. if (minimatch(path, patterns[i])) return true;
  43. }
  44. return false;
  45. };