-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuti.ts
165 lines (141 loc) · 4.8 KB
/
uti.ts
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
import { setFailed } from '@actions/core';
import { spawn } from 'child_process';
import { iswitch } from 'iswitch';
import { getChessComArchives, getChessComGames } from './api';
import { COMMIT_EMAIL, COMMIT_MSG, COMMIT_USERNAME, FILE_NAME } from './main';
import { Game, Result, Stats } from './types';
// Internal consts
export const START_TOKEN = '<!--START_SECTION:chessStats-->';
export const END_TOKEN = '<!--END_SECTION:chessStats-->';
export const INFO_LINE =
'<!-- Automatically generated with https://github.com/Balastrong/chess-stats-action -->\n';
export const getGames = async (
chessUsername: string,
amount: number
): Promise<Game[]> => {
if (!chessUsername) {
throw new Error('Username not provided!');
}
const games: Game[] = [];
const archives = await getChessComArchives(chessUsername);
for (const archive of archives) {
if (games.length < amount) {
const gamesInArchive = await getChessComGames(archive);
games.push(...gamesInArchive.reverse());
} else break;
}
return games.slice(0, amount);
};
export const commitFile = async () => {
await exec('git', ['config', '--global', 'user.email', COMMIT_EMAIL]);
await exec('git', ['config', '--global', 'user.name', COMMIT_USERNAME]);
await exec('git', ['add', FILE_NAME]);
await exec('git', ['commit', '-m', COMMIT_MSG]);
await exec('git', ['push']);
};
const exec = (cmd: string, args: string[] = []) =>
new Promise((resolve, reject) => {
const app = spawn(cmd, args, { stdio: 'pipe' });
let stdout = '';
app.stdout.on('data', data => {
stdout = data;
});
app.on('close', code => {
if (code !== 0 && !stdout.includes('nothing to commit')) {
const err = new Error(`Invalid status code: ${code}`);
return reject(err);
}
return resolve(code);
});
app.on('error', reject);
});
export const formatGamesTable = (
games: Game[],
player: string,
showDate: boolean,
showFen: boolean,
showTimeClass: boolean
): string => {
const tableHeader = `| White ⚪ | Black ⚫ | Result 🏆 |${
showDate ? ' Date 📅 |' : ''
}${showFen ? ' Position 🗺️ |' : ''}${showTimeClass ? ' Type 🕕 |' : ''}`;
const extraColumnsSize = [showDate, showFen, showTimeClass].filter(
Boolean
).length;
const tableSeparator =
'|' + Array.from({ length: 3 + extraColumnsSize }, () => ':---:|').join('');
const lowerCasePlayer = player.toLowerCase();
const gameRows = games
.map(game => {
const { white, black } = game;
const player =
white.username.toLowerCase() === lowerCasePlayer ? white : black;
const data = [
boldifyPlayer(white.username, player.username),
boldifyPlayer(black.username, player.username),
formatResult(player.result)
];
if (showDate) {
const date = new Date(game.end_time * 1000);
data.push(
`${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`
);
}
if (showFen) {
data.push(
`<a href="http://www.ee.unb.ca/cgi-bin/tervo/fen.pl?select=${game.fen}">Link</a>`
);
}
if (showTimeClass) {
const timeClass =
game.time_class.charAt(0).toUpperCase() + game.time_class.slice(1);
data.push(`${timeClass}`);
}
return `| ${data.join(' | ')} |`;
})
.join('\n');
return `${tableHeader}\n${tableSeparator}\n${gameRows}\n`;
};
export const formatStatsTable = (stats: Stats): string => {
const tableHeader = `| Type | Rapid ⏲️ | Blitz ⚡ | Bullet 🔫 |`;
const tableSeparator =
'|' + Array.from({ length: 4 }, () => ':---:|').join('');
const lastRatings = [
stats.chess_rapid?.last?.rating ?? 'No Rating',
stats.chess_blitz?.last?.rating ?? 'No Rating',
stats.chess_bullet?.last?.rating ?? 'No Rating'
];
const bestRatings = [
stats.chess_rapid?.best?.rating ?? 'No Rating',
stats.chess_blitz?.best?.rating ?? 'No Rating',
stats.chess_bullet?.best?.rating ?? 'No Rating'
];
const lastRatingRow = `| Current | ${lastRatings.join(' | ')} |`;
const bestRatingRow = `| Best | ${bestRatings.join(' | ')} |`;
return `${tableHeader}\n${tableSeparator}\n${lastRatingRow}\n${bestRatingRow}\n`;
};
export const boldifyPlayer = (test: string, player: string): string =>
test === player ? `**${test}**` : test;
const formatResult = (result: Result): string => {
const icon =
iswitch<Result, string>(
result,
['win', () => '🥇'],
[['timeout', 'checkmated', 'resigned'], () => '❌'],
[
[
'stalemate',
'insufficient',
'agreed',
'repetition',
'timevsinsufficient'
],
() => '⏸️'
]
) || '';
return `${result} ${icon}`;
};
export const setFailure = (error: string) => {
console.error(error);
setFailed(error);
};