Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unixStylePath option #65

Merged
merged 6 commits into from
Feb 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/api/inline-fixture-files.defineiffcreatoroptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ The options for [defineIFFCreator()](./inline-fixture-files.defineiffcreator.md)
export interface DefineIFFCreatorOptions
```

## Properties

| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [unixStylePath?](./inline-fixture-files.defineiffcreatoroptions.unixstylepath.md) | | boolean \| undefined | _(Optional)_ Use unix-style path separator (<code>/</code>) for paths on windows. |

## Methods

| Method | Description |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [@mizdra/inline-fixture-files](./inline-fixture-files.md) &gt; [DefineIFFCreatorOptions](./inline-fixture-files.defineiffcreatoroptions.md) &gt; [unixStylePath](./inline-fixture-files.defineiffcreatoroptions.unixstylepath.md)

## DefineIFFCreatorOptions.unixStylePath property

Use unix-style path separator (`/`<!-- -->) for paths on windows.

**Signature:**

```typescript
unixStylePath?: boolean | undefined;
```
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"eslint": "^9.14.0",
"eslint-plugin-tsdoc": "^0.3.0",
"npm-run-all": "^4.1.5",
"prettier": "^3.3.3",
"prettier": "^3.5.1",
"ts-expect": "^1.3.0",
"typescript": "^5.2.2",
"vitest": "^2.1.4"
Expand Down
88 changes: 55 additions & 33 deletions src/get-paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { utimes, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { expectType } from 'ts-expect';
import { describe, expect, test } from 'vitest';
import { getPaths, getSelfAndUpperPaths } from './get-paths.js';
import { getPaths, getSelfAndUpperPaths, slash } from './get-paths.js';
import { fixtureDir } from './test/util.js';

test('getSelfAndUpperPaths', () => {
Expand All @@ -17,6 +17,7 @@ describe('getPaths', () => {
'b.txt': 'b',
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
Expand All @@ -43,6 +44,7 @@ describe('getPaths', () => {
},
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
Expand Down Expand Up @@ -74,6 +76,7 @@ describe('getPaths', () => {
},
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'a': join(fixtureDir, 'a'),
Expand All @@ -100,29 +103,29 @@ describe('getPaths', () => {
});

test('throw error when item name starts with separator', () => {
expect(() => getPaths({ '/a.txt': 'a' }, fixtureDir)).toThrowErrorMatchingInlineSnapshot(
expect(() => getPaths({ '/a.txt': 'a' }, fixtureDir, false)).toThrowErrorMatchingInlineSnapshot(
`[Error: Item name must not start with separator: /a.txt]`,
);
expect(() => getPaths({ '/a': {} }, fixtureDir)).toThrowErrorMatchingInlineSnapshot(
expect(() => getPaths({ '/a': {} }, fixtureDir, false)).toThrowErrorMatchingInlineSnapshot(
`[Error: Item name must not start with separator: /a]`,
);
// NOTE: Use of Windows path separator is an undefined behavior.
expect(() => getPaths({ '\\a.txt': 'a' }, fixtureDir)).not.toThrow();
expect(() => getPaths({ '\\a.txt': 'a' }, fixtureDir, false)).not.toThrow();
});

test('throw error when item name ends with separator', () => {
expect(() => getPaths({ 'a.txt/': 'a' }, fixtureDir)).toThrowErrorMatchingInlineSnapshot(
expect(() => getPaths({ 'a.txt/': 'a' }, fixtureDir, false)).toThrowErrorMatchingInlineSnapshot(
`[Error: Item name must not end with separator: a.txt/]`,
);
expect(() => getPaths({ 'a/': {} }, fixtureDir)).toThrowErrorMatchingInlineSnapshot(
expect(() => getPaths({ 'a/': {} }, fixtureDir, false)).toThrowErrorMatchingInlineSnapshot(
`[Error: Item name must not end with separator: a/]`,
);
// NOTE: Use of Windows path separator is an undefined behavior.
expect(() => getPaths({ 'a.txt\\': 'a' }, fixtureDir)).not.toThrow();
expect(() => getPaths({ 'a.txt\\': 'a' }, fixtureDir, false)).not.toThrow();
});

test('throw error when item name contains consecutive separators', () => {
expect(() => getPaths({ 'a//a.txt': 'a--a' }, fixtureDir)).toThrowErrorMatchingInlineSnapshot(
expect(() => getPaths({ 'a//a.txt': 'a--a' }, fixtureDir, false)).toThrowErrorMatchingInlineSnapshot(
`[Error: Item name must not contain consecutive separators: a//a.txt]`,
);
});
Expand All @@ -143,6 +146,7 @@ describe('getPaths', () => {
},
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
Expand Down Expand Up @@ -185,6 +189,7 @@ describe('getPaths', () => {
},
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'utime.txt': join(fixtureDir, 'utime.txt'),
Expand All @@ -196,30 +201,47 @@ describe('getPaths', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
paths['a.txt'];
});
});

test('allow function and null as items', () => {
const paths = getPaths(
{
'a.txt': null,
// eslint-disable-next-line @typescript-eslint/naming-convention
'b.txt': () => {},
// eslint-disable-next-line @typescript-eslint/naming-convention
'c.txt': async () => {},
},
fixtureDir,
);
expect(paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
'b.txt': join(fixtureDir, 'b.txt'),
'c.txt': join(fixtureDir, 'c.txt'),
test('allow function and null as items', () => {
const paths = getPaths(
{
'a.txt': null,
// eslint-disable-next-line @typescript-eslint/naming-convention
'b.txt': () => {},
// eslint-disable-next-line @typescript-eslint/naming-convention
'c.txt': async () => {},
},
fixtureDir,
false,
);
expect(paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
'b.txt': join(fixtureDir, 'b.txt'),
'c.txt': join(fixtureDir, 'c.txt'),
});
expectType<{
'a.txt': string;
'b.txt': string;
'c.txt': string;
}>(paths);
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
paths['d.txt'];
});
test.runIf(process.platform === 'win32')('convert windows path separator to unix path separator', () => {
const paths = getPaths(
{
'a.txt': 'a',
'b': {
'a.txt': 'b-a',
},
},
fixtureDir,
true,
);
expect(paths).toStrictEqual({
'a.txt': slash(join(fixtureDir, 'a.txt')),
'b': slash(join(fixtureDir, 'b')),
'b/a.txt': slash(join(fixtureDir, 'b/a.txt')),
});
});
expectType<{
'a.txt': string;
'b.txt': string;
'c.txt': string;
}>(paths);
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
paths['d.txt'];
});
23 changes: 18 additions & 5 deletions src/get-paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ export function getSelfAndUpperPaths(path: string): string[] {
return [path, ...getSelfAndUpperPaths(parent)];
}

export function getPaths<T extends Directory>(directory: T, rootDir: string, prefix = ''): FlattenDirectory<T> {
export function getPaths<T extends Directory>(
directory: T,
rootDir: string,
unixStylePath: boolean,
prefix = '',
): FlattenDirectory<T> {
let paths: Record<string, string> = {};
for (const [name, item] of Object.entries(directory)) {
// TODO: Extract to `validateDirectory` function
Expand All @@ -56,25 +61,33 @@ export function getPaths<T extends Directory>(directory: T, rootDir: string, pre
// NOTE: Use `Object.defineProperty(obj, prop, { value })` instead of `obj[prop] = value` to allow `paths['__proto__']`.
// ref: https://2ality.com/2015/09/proto-es6.html#defining-__proto__
Object.defineProperty(paths, joinForPosix(prefix, n), {
value: join(rootDir, prefix, n),
value: unixStylePath ? slash(join(rootDir, prefix, n)) : join(rootDir, prefix, n),
enumerable: true,
writable: true,
configurable: true,
});
}

if (isDirectory(item)) {
const newPaths = getPaths(item, rootDir, joinForPosix(prefix, name));
const newPaths = getPaths(item, rootDir, unixStylePath, joinForPosix(prefix, name));
paths = { ...paths, ...newPaths };
}
}
return paths as unknown as FlattenDirectory<T>;
}

export function changeRootDirOfPaths<T extends FlattenDirectory<Directory>>(paths: T, newRootDir: string): T {
export function changeRootDirOfPaths<T extends FlattenDirectory<Directory>>(
paths: T,
newRootDir: string,
unixStylePath: boolean,
): T {
const newPaths: Record<string, string> = {};
for (const key of Object.keys(paths)) {
newPaths[key] = join(newRootDir, key);
newPaths[key] = unixStylePath ? slash(join(newRootDir, key)) : join(newRootDir, key);
}
return newPaths as unknown as T;
}

export function slash(path: string): string {
return path.replace(/\\/gu, '/');
}
57 changes: 51 additions & 6 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { expectType } from 'ts-expect';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { slash } from './get-paths.js';
import { defineIFFCreator } from './index.js';
import { exists, fixtureDir } from './test/util.js';

Expand Down Expand Up @@ -188,12 +189,56 @@ describe('CreateIFFResult', () => {
const iff = await createIFF({});
expect(iff.rootDir).toBe(join(fixtureDir, 'a'));
});
test('join', async () => {
const iff = await createIFF({ 'a.txt': 'a' });
expect(iff.join('a.txt')).toBe(join(fixtureDir, 'a.txt'));
expect(iff.join('/a.txt')).toBe(join(fixtureDir, 'a.txt'));
expect(iff.join('nonexistent-file.txt')).toBe(join(fixtureDir, 'nonexistent-file.txt'));
expect(iff.join('')).toBe(fixtureDir);
describe('paths', () => {
test('basic', async () => {
const iff = await createIFF({
'a.txt': 'a',
'b': {
'a.txt': 'b-a',
},
});
expect(iff.paths).toStrictEqual({
'a.txt': join(fixtureDir, 'a.txt'),
'b': join(fixtureDir, 'b'),
'b/a.txt': join(fixtureDir, 'b/a.txt'),
});
expectType<{
'a.txt': string;
'b': string;
'b/a.txt': string;
}>(iff.paths);
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
iff.paths['b/b.txt'];
});
test.runIf(process.platform === 'win32')('unixStylePath', async () => {
const createIFF = defineIFFCreator({ generateRootDir: () => fixtureDir, unixStylePath: true });
const iff = await createIFF({
'a.txt': 'a',
'b': {
'a.txt': 'b-a',
},
});
expect(iff.paths).toStrictEqual({
'a.txt': slash(join(fixtureDir, 'a.txt')),
'b': slash(join(fixtureDir, 'b')),
'b/a.txt': slash(join(fixtureDir, 'b/a.txt')),
});
});
});
describe('join', () => {
test('basic', async () => {
const iff = await createIFF({ 'a.txt': 'a' });
expect(iff.join('a.txt')).toBe(join(fixtureDir, 'a.txt'));
expect(iff.join('/a.txt')).toBe(join(fixtureDir, 'a.txt'));
expect(iff.join('nonexistent-file.txt')).toBe(join(fixtureDir, 'nonexistent-file.txt'));
expect(iff.join('')).toBe(fixtureDir);
});
test.runIf(process.platform === 'win32')('unixStylePath', async () => {
const createIFF = defineIFFCreator({ generateRootDir: () => fixtureDir, unixStylePath: true });
const iff = await createIFF({});
expect(iff.join('a.txt')).toBe(slash(join(fixtureDir, 'a.txt')));
});
});
test('rmFixtures', async () => {
const iff = await createIFF({
Expand Down
11 changes: 7 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { join } from 'node:path';
import type { Directory, MergeDirectory } from './create-iff-impl.js';
import { createIFFImpl } from './create-iff-impl.js';
import type { FlattenDirectory } from './get-paths.js';
import { changeRootDirOfPaths, getPaths } from './get-paths.js';
import { changeRootDirOfPaths, getPaths, slash } from './get-paths.js';

export type { Directory, DirectoryItem, FileType } from './create-iff-impl.js';
export { IFFFixtureCreationError } from './error.js';
Expand Down Expand Up @@ -40,6 +40,8 @@ export interface DefineIFFCreatorOptions {
* ```
*/
generateRootDir(): string;
/** Use unix-style path separator (`/`) for paths on windows. */
unixStylePath?: boolean | undefined;
}

/**
Expand Down Expand Up @@ -249,16 +251,17 @@ export function defineIFFCreator(defineIFFCreatorOptions: DefineIFFCreatorOption
__INTERNAL__prevIFF?: CreateIFFResult<U>,
): Promise<CreateIFFResult<MergeDirectory<U, T>>> {
const rootDir = options?.overrideRootDir ?? defineIFFCreatorOptions.generateRootDir();
const unixStylePath = defineIFFCreatorOptions.unixStylePath ?? false;
const paths = {
...changeRootDirOfPaths(__INTERNAL__prevIFF?.paths ?? ({} as FlattenDirectory<U>), rootDir),
...getPaths(directory, rootDir),
...changeRootDirOfPaths(__INTERNAL__prevIFF?.paths ?? ({} as FlattenDirectory<U>), rootDir, unixStylePath),
...getPaths(directory, rootDir, unixStylePath),
} as FlattenDirectory<MergeDirectory<U, T>>;

const iff: CreateIFFResult<MergeDirectory<U, T>> = {
rootDir,
paths,
join(...paths) {
return join(rootDir, ...paths);
return unixStylePath ? slash(join(rootDir, ...paths)) : join(rootDir, ...paths);
},
async rmRootDir() {
await rm(rootDir, { recursive: true, force: true });
Expand Down