Skip to content

Commit

Permalink
feat(internal): ensurePosix
Browse files Browse the repository at this point in the history
Signed-off-by: Lexus Drumgold <[email protected]>
  • Loading branch information
unicornware committed Dec 7, 2022
1 parent 3f2df46 commit 12e2a26
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/internal/__tests__/ensure-posix.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* @file Unit Tests - ensurePosix
* @module pathe/internal/tests/unit/ensurePosix
*/

import delimiter from '#src/lib/delimiter'
import sep from '#src/lib/sep'
import testSubject from '../ensure-posix'

describe('unit:internal/ensurePosix', () => {
let path: string

beforeEach(() => {
path = 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'
})

it('should consolidate duplicate posix path segment separators', () => {
expect(testSubject(path)).to.not.include('//')
})

it('should convert windows path delimiters', () => {
expect(testSubject(path)).to.not.include(';')
})

it('should convert windows path segment separators', () => {
expect(testSubject(path)).to.not.include('\\')
})

it('should return path that meets posix standards', () => {
// Arrange
const segments: string[] = [
`C:${sep}Windows${sep}system32`,
`C:${sep}Windows`,
`C:${sep}Program Files${sep}node${sep}`
]

// Act + Expect
expect(testSubject(path)).to.equal(segments.join(delimiter))
})
})
36 changes: 36 additions & 0 deletions src/internal/ensure-posix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* @file Internal - ensurePosix
* @module pathe/internal/ensurePosix
*/

import delimiter from '#src/lib/delimiter'
import sep from '#src/lib/sep'
import validateString from './validate-string'

/**
* Ensures `path` meets POSIX standards.
*
* This includes:
*
* - Converting Windows-style path delimiters (`;`) to POSIX (`:`)
* - Converting Windows-style path segment separators (`\`) to POSIX (`/`)
* - Consolidating duplicate path segment separators (occurs when an escaped
* Windows-style separator (`\\`) is converted to POSIX)
*
* @see https://nodejs.org/api/path.html#windows-vs-posix
* @see https://nodejs.org/api/path.html#pathdelimiter
* @see https://nodejs.org/api/path.html#pathsep
*
* @param {string} [path=''] - Path to normalize
* @return {string} `path` normalized
*/
const ensurePosix = (path: string = ''): string => {
validateString(path, 'path')

return path
.replace(/;/g, delimiter) // convert path delimiters
.replace(/\\/g, sep) // convert path segment separators
.replace(new RegExp(`(?<!^)\\${sep}+`), sep) // consolidate separators
}

export default ensurePosix

0 comments on commit 12e2a26

Please sign in to comment.