Pārlūkot izejas kodu

transplant path-utils

Yuki Takei 7 gadi atpakaļ
vecāks
revīzija
d58ad9b64e

+ 1 - 0
packages/growi-commons/src/index.js

@@ -1,3 +1,4 @@
 module.exports = {
   BasicInterceptor: require('./util/basic-interceptor'),
+  pathUtils: require('./util/path-utils'),
 };

+ 24 - 0
packages/growi-commons/src/test/util/path-utils.test.js

@@ -0,0 +1,24 @@
+require('module-alias/register');
+
+const pathUtils = require('@src/util/path-utils');
+
+
+describe('page-utils', () => {
+  describe('.normalizePath', () => {
+    test('should rurn root path with empty string', () => {
+      expect(pathUtils.normalizePath('')).toBe('/');
+    });
+
+    test('should add heading slash', () => {
+      expect(pathUtils.normalizePath('hoge/fuga')).toBe('/hoge/fuga');
+    });
+
+    test('should remove trailing slash', () => {
+      expect(pathUtils.normalizePath('/hoge/fuga/')).toBe('/hoge/fuga');
+    });
+
+    test('should remove unnecessary slashes', () => {
+      expect(pathUtils.normalizePath('//hoge/fuga//')).toBe('/hoge/fuga');
+    });
+  });
+});

+ 83 - 0
packages/growi-commons/src/util/path-utils.js

@@ -0,0 +1,83 @@
+
+function encodePagePath(path) {
+  const paths = path.split('/');
+  paths.forEach((item, index) => {
+    paths[index] = encodeURIComponent(item);
+  });
+  return paths.join('/');
+}
+
+function encodePagesPath(pages) {
+  pages.forEach((page) => {
+    if (!page.path) {
+      return;
+    }
+    page.path = encodePagePath(page.path);
+  });
+  return pages;
+}
+
+function matchSlashes(path) {
+  // https://regex101.com/r/Z21fEd/5
+  return path.match(/^((\/+)?(.+?))(\/+)?$/);
+}
+
+function hasHeadingSlash(path) {
+  const match = matchSlashes(path);
+  return (match[2] != null);
+}
+
+function hasTrailingSlash(path) {
+  const match = matchSlashes(path);
+  return (match[4] != null);
+}
+
+function addHeadingSlash(path) {
+  if (path === '/') {
+    return path;
+  }
+
+  if (!hasHeadingSlash(path)) {
+    return `/${path}`;
+  }
+  return path;
+}
+
+function addTrailingSlash(path) {
+  if (path === '/') {
+    return path;
+  }
+
+  if (!hasTrailingSlash(path)) {
+    return `${path}/`;
+  }
+  return path;
+}
+
+function removeTrailingSlash(path) {
+  if (path === '/') {
+    return path;
+  }
+
+  const match = matchSlashes(path);
+  return match[1];
+}
+
+function normalizePath(path) {
+  const match = matchSlashes(path);
+  if (match == null) {
+    return '/';
+  }
+  return `/${match[3]}`;
+}
+
+module.exports = {
+  encodePagePath,
+  encodePagesPath,
+  hasHeadingSlash,
+  hasTrailingSlash,
+  addHeadingSlash,
+  addTrailingSlash,
+  removeTrailingSlash,
+  normalizePath,
+};