forked from rtfpessoa/diff2html-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
170 lines (137 loc) · 5.44 KB
/
Copy pathcli.ts
File metadata and controls
170 lines (137 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import fs from 'fs';
import os from 'os';
import path from 'path';
import * as clipboardy from 'clipboardy';
import open = require('open');
import { parse, html, Diff2HtmlConfig } from 'diff2html';
import * as http from './http-utils';
import * as log from './logger';
import { Configuration, InputType, DiffyType } from './types';
import * as utils from './utils';
const defaultArgs = ['-M', '-C', 'HEAD'];
function generateGitDiffArgs(gitArgsArr: string[], ignore: string[]): string[] {
const gitDiffArgs: string[] = ['diff'];
if (!gitArgsArr.includes('--no-color')) gitDiffArgs.push('--no-color');
if (gitArgsArr.length === 0) Array.prototype.push.apply(gitDiffArgs, defaultArgs);
Array.prototype.push.apply(gitDiffArgs, gitArgsArr);
if (ignore.length > 0) {
if (!gitArgsArr.includes('--')) gitDiffArgs.push('--');
Array.prototype.push.apply(
gitDiffArgs,
ignore.map(path => `:(exclude)${path}`),
);
}
return gitDiffArgs;
}
function runGitDiff(gitArgsArr: string[], ignore: string[]): string {
const gitDiffArgs = generateGitDiffArgs(gitArgsArr, ignore);
return utils.execute('git', gitDiffArgs);
}
function prepareHTML(diffHTMLContent: string, config: Configuration): string {
const template = utils.readFile(config.htmlWrapperTemplate);
const diff2htmlPath = path.join(path.dirname(require.resolve('diff2html')), '..');
const cssFilePath = path.resolve(diff2htmlPath, 'bundles', 'css', 'diff2html.min.css');
const cssContent = utils.readFile(cssFilePath);
const jsUiFilePath = path.resolve(diff2htmlPath, 'bundles', 'js', 'diff2html-ui-slim.min.js');
const jsUiContent = utils.readFile(jsUiFilePath);
const pageTitle = config.pageTitle;
const pageHeader = config.pageHeader;
/* HACK:
* Replace needs to receive a function as the second argument to perform an exact replacement.
* This will avoid the replacements from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter
*/
return [
{ searchValue: '<!--diff2html-title-->', replaceValue: pageTitle },
{ searchValue: '<!--diff2html-css-->', replaceValue: `<style>\n${cssContent}\n</style>` },
{ searchValue: '<!--diff2html-js-ui-->', replaceValue: `<script>\n${jsUiContent}\n</script>` },
{
searchValue: '//diff2html-fileListToggle',
replaceValue: `diff2htmlUi.fileListToggle(${config.showFilesOpen});`,
},
{
searchValue: '//diff2html-fileContentToggle',
replaceValue: config.fileContentToggle ? `diff2htmlUi.fileContentToggle();` : '',
},
{
searchValue: '//diff2html-synchronisedScroll',
replaceValue: config.synchronisedScroll ? `diff2htmlUi.synchronisedScroll();` : '',
},
{
searchValue: '//diff2html-highlightCode',
replaceValue: config.highlightCode ? `diff2htmlUi.highlightCode();` : '',
},
{ searchValue: '<!--diff2html-header-->', replaceValue: pageHeader },
{ searchValue: '<!--diff2html-diff-->', replaceValue: diffHTMLContent },
].reduce(
(previousValue, replacement) =>
utils.replaceExactly(previousValue, replacement.searchValue, replacement.replaceValue),
template,
);
}
/**
* Get unified diff input from type
* @param inputType - a string `file`, `stdin`, or `command`
* @param inputArgs - a string array
* @param ignore - a string array
*/
export async function getInput(inputType: InputType, inputArgs: string[], ignore: string[]): Promise<string> {
switch (inputType) {
case 'file':
return utils.readFile(inputArgs[0]);
case 'stdin':
return utils.readStdin();
case 'command':
return runGitDiff(inputArgs, ignore);
}
}
export function getOutput(options: Diff2HtmlConfig, config: Configuration, input: string): string {
if (config.htmlWrapperTemplate && !fs.existsSync(config.htmlWrapperTemplate)) {
process.exitCode = 4;
throw new Error(`Template ('${config.htmlWrapperTemplate}') not found!`);
}
const diffJson = parse(input, options);
switch (config.formatType) {
case 'html': {
const htmlContent = html(diffJson, { ...options });
return prepareHTML(htmlContent, config);
}
case 'json': {
return JSON.stringify(diffJson);
}
}
}
export function preview(content: string, format: string): void {
const filename = `diff.${format}`;
const filePath: string = path.resolve(os.tmpdir(), filename);
utils.writeFile(filePath, content);
open(filePath, { wait: false });
}
type CreateDiffResponse = { id: string };
type ApiError = { error: string };
function isCreateDiffResponse(obj: unknown): obj is CreateDiffResponse {
return (obj as CreateDiffResponse).id !== undefined;
}
function isApiError(obj: unknown): obj is ApiError {
return (obj as ApiError).error !== undefined;
}
export async function postToDiffy(diff: string, diffyOutput: DiffyType): Promise<string> {
const response = await http.put('https://diffy.org/api/diff/', { diff: diff });
if (!isCreateDiffResponse(response)) {
if (isApiError(response)) {
throw new Error(response.error);
} else {
throw new Error(
`Could not find 'id' of created diff in the response json.\nBody:\n\n${JSON.stringify(response, null, 2)}`,
);
}
}
const url = `https://diffy.org/diff/${response.id}`;
log.print('Link powered by https://diffy.org');
log.print(url);
if (diffyOutput === 'browser') {
open(url);
} else if (diffyOutput === 'pbcopy') {
clipboardy.writeSync(url);
}
return url;
}