Skip to content
Draft
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ Diff to Html generates pretty HTML diffs from unified and git diff output in you

## Setup

The installed CLI requires Node.js 12 or later. Use a maintained version of Node.js when possible.

```sh
npm install -g diff2html-cli
```
Expand Down Expand Up @@ -96,6 +98,12 @@ Usage: diff2html [ flags and/or options ] -- [git diff passthrough flags and opt
| -v | --version | Show version number | | |
| -h | --help | Show help | | |

On Linux outside Podman containers, `-u pbcopy` requires `getconf` on `PATH` when Node.js is not x64.

In Podman containers on WSL2, browser preview and clipboard integration use the container's Linux helpers. If the
container has no desktop or clipboard access, use `-o stdout` to print the rendered diff or `-u print` to print the
Diffy link.

### Exit Status Codes

- :tada: 0: Success
Expand Down Expand Up @@ -176,6 +184,9 @@ your changes following the guidelines described in `CONTRIBUTING.md`. I will try

## Developing

Use a modern Node.js version from CI and Yarn Classic (1.x) for development. The Node.js 12 minimum applies to the
installed CLI, not the development tools.

Make some changes, `yarn build` and then `./bin/diff2html` 😉

## License
Expand Down
5 changes: 3 additions & 2 deletions bin/diff2html.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env node

// eslint-disable-next-line import/no-unresolved
import { main } from '../lib/main.js';
// The build creates lib/main.js after lint runs.
// eslint-disable-next-line @typescript-eslint/no-var-requires, node/no-missing-require
const { main } = require('../lib/main.js');
main();
15 changes: 1 addition & 14 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
import type { JestConfigWithTsJest } from 'ts-jest';

const jestConfig: JestConfigWithTsJest = {
preset: 'ts-jest/presets/default-esm',
preset: 'ts-jest',
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
moduleFileExtensions: ['js', 'json', 'jsx', 'node', 'ts', 'tsx'],
transform: {
// '^.+\\.tsx?$' to process ts with `ts-jest`
// '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
// '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
'^.+\\.m?[tj]sx?$': [
'ts-jest',
{
useESM: true,
},
],
},
extensionsToTreatAsEsm: ['.ts'],
verbose: true,
testEnvironment: 'node',
coverageDirectory: './coverage',
Expand Down
28 changes: 12 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"url": "https://github.com/rtfpessoa/diff2html-cli/issues"
},
"engines": {
"node": ">=16"
"node": ">=12"
},
"preferGlobal": true,
"scripts": {
Expand All @@ -51,22 +51,19 @@
"gen:toc-base": "markdown-toc --maxdepth 3 --bullets='-' -i",
"gen:toc": "yarn run gen:toc-base README.md",
"test": "is-ci 'test:coverage' 'test:watch'",
"test:coverage": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage",
"test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --watch",
"test:debug": "node --experimental-vm-modules --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --watch",
"test:coverage": "jest --coverage",
"test:watch": "jest --watch",
"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --watch",
"coverage:open": "yarn run test:coverage && open ./coverage/index.html",
"validate": "yarn run format:check && yarn run lint:check && yarn run build && yarn run test:coverage",
"fix": "yarn run format:fix && yarn run lint:fix",
"preversion": "yarn run validate",
"version": "git add -A package.json",
"prepare": "husky install"
},
"type": "module",
"bin": {
"diff2html": "./bin/diff2html.js"
},
"main": "./lib/diff2html.js",
"types": "./lib/diff2html.d.ts",
"lint-staged": {
"**/*.+(js|jsx|ts|tsx|json)": [
"prettier --write",
Expand All @@ -80,22 +77,21 @@
]
},
"dependencies": {
"clipboardy": "^4.0.0",
"diff2html": "^3.4.47",
"node-fetch": "^3.3.2",
"open": "^10.0.3",
"yargs": "^17.6.0"
"clipboardy": "2.3.0",
"diff2html": "3.5.0",
"node-fetch": "2.7.0",
"open": "8.4.2",
"yargs": "17.7.3"
},
"devDependencies": {
"@babel/core": "^7.23.7",
"@babel/preset-env": "^7.23.8",
"@babel/preset-typescript": "^7.23.3",
"@jest/globals": "^29.7.0",
"@types/hogan.js": "^3.0.5",
"@types/jest": "^29.5.11",
"@types/node": "20.11.0",
"@types/node-fetch": "^2.6.10",
"@types/request": "2.48.12",
"@types/node": "12.20.55",
"@types/node-fetch": "2.6.13",
"@types/yargs": "17.0.35",
"@typescript-eslint/eslint-plugin": "6.18.1",
"@typescript-eslint/parser": "6.18.1",
"babel-jest": "^29.7.0",
Expand Down
99 changes: 99 additions & 0 deletions src/__tests__/cli-podman-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import childProcess from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { jest } from '@jest/globals';

import { put } from '../http-utils';

jest.mock('child_process');
jest.mock('clipboardy', () => {
throw new Error('Podman should not load the clipboard adapter');
});
jest.mock('../http-utils', () => ({ put: jest.fn() }));
jest.mock('../logger', () => ({ print: jest.fn() }));
jest.mock('../utils', () => ({ writeFile: jest.fn() }));

const originalPlatform = process.platform;
const originalArch = process.arch;
const spawn = jest.mocked(childProcess.spawn);
const spawnSync = jest.mocked(childProcess.spawnSync);
const bundledOpener = require.resolve('open/xdg-open');
const url = 'https://diffy.org/diff/test';
const xselArgs = ['--clipboard', '--input'];

beforeEach(() => {
Object.defineProperty(process, 'platform', { value: 'linux' });
Object.defineProperty(process, 'arch', { value: 'x64' });
jest.spyOn(os, 'release').mockReturnValue('5.15.153.1-microsoft-standard-WSL2');
const { existsSync, statSync, readFileSync } = fs;
const { access } = fs.promises;
jest.spyOn(fs, 'existsSync').mockImplementation(file => file === '/run/.containerenv' || existsSync(file));
jest.spyOn(fs, 'accessSync').mockReturnValue(undefined);
jest.spyOn(fs, 'statSync').mockImplementation((file, options) => {
if (file === '/.dockerenv') throw new Error('No Docker marker');
return statSync(file, options);
});
jest.spyOn(fs, 'readFileSync').mockImplementation((file, options) => {
return file === '/proc/self/cgroup' ? '0::/libpod-fixture' : readFileSync(file, options);
});
jest.spyOn(fs.promises, 'access').mockImplementation((file, mode) => {
return file === '/etc/wsl.conf' ? Promise.reject(new Error('No WSL config')) : access(file, mode);
});

jest.mocked(put).mockResolvedValue({ id: 'test' });
});

afterEach(() => {
Object.defineProperty(process, 'platform', { value: originalPlatform });
Object.defineProperty(process, 'arch', { value: originalArch });
jest.restoreAllMocks();
jest.resetAllMocks();
});

test('uses the executable bundled opener and system xsel in Podman on WSL2', async () => {
spawn.mockReturnValue({ unref: jest.fn() } as unknown as childProcess.ChildProcess);
spawnSync.mockReturnValue({ pid: 1, output: [], status: 0, signal: null, stdout: '', stderr: '' });

const cli = await import('../cli');
const filePath = path.resolve(os.tmpdir(), 'diff.html');
cli.preview('output', 'html');
await cli.postToDiffy('input', 'browser');
await cli.postToDiffy('input', 'pbcopy');

expect(fs.accessSync).toHaveBeenCalledWith(bundledOpener, fs.constants.X_OK);
expect(spawn.mock.calls.map(([command, args]) => [command, args])).toEqual([
[bundledOpener, [filePath]],
[bundledOpener, [url]],
]);
expect(spawnSync).toHaveBeenCalledTimes(1);
expect(spawnSync).toHaveBeenCalledWith('xsel', xselArgs, expect.objectContaining({ input: url }));
});

test('uses system xdg-open when the bundled opener is not executable in Podman on WSL2', async () => {
spawn.mockReturnValue({ unref: jest.fn() } as unknown as childProcess.ChildProcess);
jest.mocked(fs.accessSync).mockImplementation(() => {
throw Object.assign(new Error('Bundled opener is not executable'), { code: 'EACCES' });
});

const cli = await import('../cli');
const filePath = path.resolve(os.tmpdir(), 'diff.html');
cli.preview('output', 'html');

expect(fs.accessSync).toHaveBeenCalledWith(bundledOpener, fs.constants.X_OK);
expect(spawn).toHaveBeenCalledTimes(1);
expect(spawn).toHaveBeenCalledWith('xdg-open', [filePath], { detached: true, stdio: 'ignore' });
});

test('tries bundled xsel without falling back to Windows if the Linux clipboard fails', async () => {
spawnSync.mockReturnValue({ pid: 1, output: [], status: 1, signal: null, stdout: '', stderr: '' });

const cli = await import('../cli');
await expect(cli.postToDiffy('input', 'pbcopy')).rejects.toThrow('xsel failed (exit 1)');
const bundledXsel = path.resolve(path.dirname(require.resolve('clipboardy')), 'fallbacks', 'linux', 'xsel');
expect(spawnSync.mock.calls.map(([command, args]) => [command, args])).toEqual([
['xsel', xselArgs],
[bundledXsel, xselArgs],
]);
expect(spawn).not.toHaveBeenCalled();
});
9 changes: 9 additions & 0 deletions src/__tests__/cli-startup-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { jest } from '@jest/globals';

jest.mock('clipboardy', () => {
throw new Error('Clipboard adapter could not initialize');
});

test('loads the CLI when the clipboard adapter cannot initialize', async () => {
await expect(import('../cli')).resolves.toHaveProperty('getInput');
});
121 changes: 90 additions & 31 deletions src/__tests__/cli-tests.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,39 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { jest } from '@jest/globals';

let cli: typeof import('../cli');

const readFileSpy: jest.Mock<() => string> = jest.fn();
const readStdinSpy: jest.Mock<() => Promise<string>> = jest.fn();
const writeFileSpy: jest.Mock<(filePath: string, content: string) => void> = jest.fn();
const executeSpy: jest.Mock<(executable: string, args: string[]) => string> = jest.fn();
jest.unstable_mockModule('../utils', async () => ({
readFile: readFileSpy,
readStdin: readStdinSpy,
execute: executeSpy,
writeFile: writeFileSpy,
}));

const putSpy: jest.Mock<(url: string, payload: object) => Promise<unknown>> = jest.fn();
jest.unstable_mockModule('../http-utils', async () => ({
put: putSpy,
}));

beforeEach(async () => {
cli = await import('../cli');
import { writeSync } from 'clipboardy';
import open from 'open';

import * as cli from '../cli';
import { parseArgv } from '../configuration';
import { put } from '../http-utils';
import * as utils from '../utils';
import { setup } from '../yargs';

jest.mock('child_process');
jest.mock('clipboardy', () => ({ writeSync: jest.fn() }));
jest.mock('open', () => jest.fn());
jest.mock('../utils');
jest.mock('../http-utils', () => ({ put: jest.fn() }));
jest.mock('../logger', () => ({ print: jest.fn() }));

const readFileSpy = jest.mocked(utils.readFile);
const readStdinSpy = jest.mocked(utils.readStdin);
const writeFileSpy = jest.mocked(utils.writeFile);
const executeSpy = jest.mocked(utils.execute);
const putSpy = jest.mocked(put);

beforeEach(() => {
const { existsSync } = fs;
jest.spyOn(fs, 'existsSync').mockImplementation(file => file !== '/run/.containerenv' && existsSync(file));
});

afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
jest.resetAllMocks();
});

process.argv = ['node', 'diff2html.js', '-i', 'stdin', '--', 'test'];

describe('cli', () => {
describe('getInput', () => {
test('should readFile when inputType is `file`', async () => {
Expand Down Expand Up @@ -114,24 +120,77 @@ describe('cli', () => {
});
});

describe('preview', () => {
test('should call `utils.writeFile`', async () => {
writeFileSpy.mockReturnValue();
describe('getOutput', () => {
test('should fail with exit code 4 if the template does not exist', async () => {
const argv = process.argv;
const exitCode = process.exitCode;
const template = path.join(__filename, 'missing-template.html');
try {
process.argv = ['node', 'diff2html.js', '--hwt', template];
const [options, config] = parseArgv(await setup());

expect(() => cli.getOutput(options, config, 'input')).toThrow(`Template ('${template}') not found!`);
expect(process.exitCode).toBe(4);
} finally {
process.argv = argv;
process.exitCode = exitCode;
}
});
});

cli.preview('a', 'b');
describe('preview', () => {
test('should write the preview file and pass its path to the opener', () => {
cli.preview('output', 'html');

const filePath = path.resolve(os.tmpdir(), 'diff.html');
expect(writeFileSpy).toHaveBeenCalledTimes(1);
expect(writeFileSpy).toHaveBeenCalledWith(filePath, 'output');
expect(open).toHaveBeenCalledWith(filePath, { wait: false });
});
});

describe('postToDiffy', () => {
test('should call `http.put`', async () => {
putSpy.mockReturnValue(Promise.resolve({ id: 'foo' }));
const diffUrl = 'https://diffy.org/diff/foo';

await cli.postToDiffy('a', 'print');
test('should request a link without opening it or copying it in print mode', async () => {
putSpy.mockResolvedValue({ id: 'foo' });

await expect(cli.postToDiffy('a', 'print')).resolves.toBe(diffUrl);

expect(putSpy).toHaveBeenCalledTimes(1);
expect(putSpy).toHaveBeenCalledWith('https://diffy.org/api/diff/', { diff: 'a' });
expect(open).not.toHaveBeenCalled();
expect(writeSync).not.toHaveBeenCalled();
});

test('should pass the generated link to the opener in browser mode', async () => {
putSpy.mockResolvedValue({ id: 'foo' });

await cli.postToDiffy('a', 'browser');

expect(open).toHaveBeenCalledWith(diffUrl, { wait: false });
expect(writeSync).not.toHaveBeenCalled();
});

test('should pass the generated link to the clipboard adapter in pbcopy mode', async () => {
putSpy.mockResolvedValue({ id: 'foo' });

await cli.postToDiffy('a', 'pbcopy');

expect(writeSync).toHaveBeenCalledWith(diffUrl);
expect(open).not.toHaveBeenCalled();
});

test('should report an API error response', async () => {
putSpy.mockResolvedValue({ error: 'Upload failed' });

await expect(cli.postToDiffy('a', 'print')).rejects.toThrow('Upload failed');
});

test('should reject a response without an id or an API error', async () => {
putSpy.mockResolvedValue({});

await expect(cli.postToDiffy('a', 'print')).rejects.toThrow("Could not find 'id'");
});
});
});
Loading