-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.js
109 lines (96 loc) · 2.67 KB
/
lib.js
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
import chalk from 'chalk';
const { green, red, bold } = chalk;
import { eq, gt, valid, lt } from 'semver';
import { table } from 'table';
export function diff(oldLock, newLock) {
const changes = {};
Object.entries(oldLock.dependencies).forEach(([name, { version }]) => {
changes[name] = [version, null];
});
Object.entries(newLock.dependencies).forEach(([name, { version }]) => {
if (changes[name]) {
if (eq(changes[name][0], version)) {
delete changes[name];
} else {
changes[name] = [changes[name][0], version];
}
} else {
changes[name] = [null, version];
}
});
return changes;
}
export function printJSON(changes, options) {
if (options.pretty) {
console.log(JSON.stringify(changes, null, 2));
} else {
console.log(JSON.stringify(changes));
}
}
export function printText(changes, options) {
Object.entries(changes).forEach(([name, [oldVersion, newVersion]]) => {
if (!oldVersion) {
if (options.color) {
console.log(`${name} ${green('added')}`);
} else {
console.log(`${name} added`);
}
} else if (!newVersion) {
if (options.color) {
console.log(`${name} ${red('removed')}`);
} else {
console.log(`${name} removed`);
}
} else if (!eq(oldVersion, newVersion)) {
if (options.color) {
const color = gt(oldVersion, newVersion)
? red
: green;
console.log(`${name} ${color(`${oldVersion} -> ${newVersion}`)}`);
} else {
console.log(`${name} ${oldVersion} -> ${newVersion}`);
}
}
});
}
export function printTable(changes, options) {
let data = Object.entries(changes)
.map(([name, [oldVersion, newVersion]]) => ([
name,
oldVersion,
newVersion,
]));
if (options.color) {
data = data.map(([name, oldVersion, newVersion]) => {
if (valid(oldVersion) && valid(newVersion)) {
if (lt(oldVersion, newVersion)) {
oldVersion = red(oldVersion);
newVersion = green(newVersion);
} else if (gt(oldVersion, newVersion)) {
oldVersion = green(oldVersion);
newVersion = red(newVersion);
}
}
return [name, oldVersion, newVersion];
});
}
data.unshift(['package', 'old version', 'new version']);
if (options.color) {
data[0] = data[0].map((heading) => bold(heading));
}
console.log(table(data));
}
export function print(changes, options) {
switch (options.format) {
case 'json':
printJSON(changes, options);
break;
case 'table':
printTable(changes, options);
break;
case 'text':
default:
printText(changes, options);
break;
}
}