This repository has been archived by the owner on Dec 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtldr.c
355 lines (315 loc) · 9.3 KB
/
tldr.c
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/* MIT License
* Copyright 2024 Ivan Kovmir */
/* Includes */
/* cURL must be included before libarchive in order to avoid a compiler
* warning on Windows regarding the Winsock2 library. */
#include <curl/curl.h>
#include <dirent.h>
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
/* libarchive */
#include <archive.h>
#include <archive_entry.h>
/* Constants and Macros */
#define BUF_SIZE 1024
#define D_NAME entry->d_name
#define ENABLE_WIN_VT100_OUT 7
#define NULL_TERMINATE(arr, size) (arr[(size)-1] = 0)
/* Function prototypes */
/* Print error message and terminate the execution */
static void error_terminate(const char *msg, const char *details);
/* Prints instructions on how to use the program. */
static void print_usage(void);
/* Downloads pages. */
static void fetch_pages(void);
/* Extracts pages and put them in place. */
static void extract_pages(void);
/* Creates index file of all pages. */
static void index_pages(void);
static int nftw_callback(const char *path, const struct stat *sb,
int typeflag, struct FTW *ftwbuf);
/* Prints all page names. */
static void list_pages(void);
/* Returns a file path to a given page. */
static char *find_page(const char *page_name);
/* Enables VT100 mode on Win10 1503+ ConHost & wt+mintty; else, empty. */
static void setup_console(void);
/* Restores previous mode on Win10 1503+ ConHost & wt+mintty; else, empty. */
static void restore_console(void);
/* Prints a given page. */
static void display_page(const char *dest_path);
/* Opens index file performing all the necessary checking. */
static FILE *open_index(const char *mode);
/* Save locations, styling, and other settings are set via config.h. */
#include "config.h"
/* Resets console styling back to default (usually white-on-black),
and clears rest of current line for consistency on Windows. */
static const char *RESET_STYLING = "\033[0m\033[0K";
/* Index file to hold available page names. */
static FILE *tldr_index;
/* Path to download the tldr archive to. */
static char zip_path[BUF_SIZE];
inline void
error_terminate(const char *msg, const char *details)
{
fprintf(stderr, "%s; details: %s.\n", msg, details? details : "none");
exit(1);
}
inline void
print_usage(void)
{
printf("USAGE: tldr [options] <[platform/]command>\n\n"
"[options]\n"
"\t-h:\tthis help overview\n"
"\t-l:\tshow all available pages\n"
"\t-u:\tfetch lastest copies of man pages\n\n"
"[platform]\n"
"\tandroid\n"
"\tcommon\n"
"\tindex\n"
"\tlinux\n"
"\tosx\n"
"\tsunos\n"
"\twindows\n\n"
"<command>\n"
"\tShow examples for this command\n");
}
void
fetch_pages(void)
{
CURL *ceh; /* cURL easy handle. */
CURLcode cres; /* cURL operation result. */
char err_curl[CURL_ERROR_SIZE]; /* Curl error message buffer. */
FILE *tldr_archive; /* File to download to. */
if (getenv("TEMP") != NULL) /* Defined by Windows. */
strcpy(zip_path, getenv("TEMP"));
else if (getenv("TEMPDIR") != NULL) /* Can be defined by *nix users. */
strcpy(zip_path, getenv("TEMPDIR"));
else /* If neither defined, presume default *nix tmp path. */
strcpy(zip_path, "/tmp");
strcat(zip_path, "/tldr_pages.zip");
NULL_TERMINATE(zip_path, BUF_SIZE);
/* Write in binary mode to avoid mangling with CRLFs in Windows. */
tldr_archive = fopen(zip_path, "wb");
if (!tldr_archive)
error_terminate("Failed to create a temporary file", NULL);
curl_global_init(CURL_GLOBAL_ALL);
ceh = curl_easy_init();
curl_easy_setopt(ceh, CURLOPT_WRITEDATA, tldr_archive);
curl_easy_setopt(ceh, CURLOPT_URL, PAGES_URL);
curl_easy_setopt(ceh, CURLOPT_ERRORBUFFER, err_curl);
cres = curl_easy_perform(ceh);
curl_easy_cleanup(ceh);
curl_global_cleanup();
fclose(tldr_archive);
if (cres != CURLE_OK)
error_terminate("Failed to fetch pages", err_curl);
}
void
extract_pages(void)
{
char src_path[BUF_SIZE]; /* Path within archive to extract from. */
char dest_path[BUF_SIZE]; /* Path to save pages to. */
FILE *tldr_archive; /* Pointer to downloaded zip file. */
int ares; /* libarchive status. */
struct archive *ap;
struct archive_entry *aep;
tldr_archive = fopen(zip_path, "r");
if (tldr_archive == NULL)
error_terminate("Failed to open the archive", NULL);
ap = archive_read_new();
if (ap == NULL)
error_terminate("Failed to archive_read_new()", NULL);
archive_read_support_format_zip(ap);
ares = archive_read_open_FILE(ap, tldr_archive);
if (ares != ARCHIVE_OK)
error_terminate("Failed to archive_read_open_FILE()",
archive_error_string(ap));
/* A place inside the archive to extract pages from. */
snprintf(src_path, BUF_SIZE, "%s%s/", "tldr-main", PAGES_LANG);
/* Find the folder within the archive to extract from. */
while (archive_read_next_header(ap, &aep) != ARCHIVE_EOF)
if (!strcmp(archive_entry_pathname(aep), src_path))
break;
while (archive_read_next_header(ap, &aep) != ARCHIVE_EOF) {
if (strncmp(archive_entry_pathname(aep),
src_path, strlen(src_path)))
break;
snprintf(dest_path, BUF_SIZE, "%s%s%s",
getenv("HOME"), PAGES_PATH,
strchr(archive_entry_pathname(aep),'/'));
archive_entry_set_pathname(aep, dest_path);
ares = archive_read_extract(ap, aep, 0);
if (ares != ARCHIVE_OK)
error_terminate("Failed to archive_read_extract()",
archive_error_string(ap));
}
archive_read_free(ap);
fclose(tldr_archive);
remove(zip_path);
}
void
index_pages(void)
{
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "%s%s%s",
getenv("HOME"), PAGES_PATH, PAGES_LANG);
tldr_index = open_index("w");
nftw(buf, nftw_callback, 10, FTW_PHYS);
fclose(tldr_index);
}
int
nftw_callback(const char *path, const struct stat *sb,
int typeflag, struct FTW *ftwbuf)
{
(void)sb; /* Suppress compiler warnings about unused arguments. */
(void)ftwbuf;
if (typeflag != FTW_F) /* Skip everything except files. */
return 0;
/* Truncate the full path to include only the filename and last dir. */
fprintf(tldr_index, "%s\n",
strchr(strstr(path, PAGES_LANG)+1, '/')+1);
return 0;
}
void
list_pages(void)
{
char buf[BUF_SIZE];
tldr_index = open_index("r");
while(fgets(buf, BUF_SIZE, tldr_index)) {
NULL_TERMINATE(buf, BUF_SIZE);
printf("%s", buf);
}
fclose(tldr_index);
}
char *
find_page(const char *page_name)
{
static char buf[BUF_SIZE];
char page_filename[strlen(page_name)+5]; /* for '.md\n\0' */
tldr_index = open_index("r");
snprintf(page_filename, BUF_SIZE, "%s.md\n", page_name);
while(fgets(buf, BUF_SIZE, tldr_index)) {
/* page_name is either 'command' or 'platform/command'. */
if (strchr(page_name, '/')) { /* platform/command */
if(!strcmp(page_filename, buf)) {
*strchr(buf, '\n') = '\0';
fclose(tldr_index);
return buf;
}
} else { /* command */
if (!strcmp(page_filename, strchr(buf, '/')+1)) {
*strchr(buf, '\n') = '\0';
fclose(tldr_index);
return buf;
}
}
}
fclose(tldr_index);
return NULL;
}
#ifdef _WIN32
static DWORD outmode_init; /* will be set to initial console mode value. */
static HANDLE stdout_handle; /* handle for current console session. */
/* ref: https://docs.microsoft.com/en-us/windows/console/setconsolemode */
void
setup_console(void)
{
stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(stdout_handle, &outmode_init);
if (!SetConsoleMode(stdout_handle, ENABLE_WIN_VT100_OUT)){
error_terminate("\nYou are likely using an older version of Windows,"
"\nwhich is not yet compatible with this client.\n", NULL);
}
}
void
restore_console(void)
{ /* Error catching would be superfluous here given program flow. */
SetConsoleMode(stdout_handle, outmode_init);
}
#else
void setup_console(void){}
void restore_console(void){}
#endif
void
display_page(const char *page_name)
{
char buf[BUF_SIZE];
char *dest_path;
FILE *page;
dest_path = find_page(page_name);
if (!dest_path)
error_terminate("The page has not been found.", NULL);
snprintf(buf, BUF_SIZE, "%s%s%s/%s",
getenv("HOME"), PAGES_PATH, PAGES_LANG, dest_path);
page = fopen(buf, "r");
setup_console(); /* Enables VT100 processing in Win10 1503+ */
while (fgets(buf, BUF_SIZE, page)) {
NULL_TERMINATE(buf, BUF_SIZE);
if (!strcmp(buf, "\n")) {
continue; /* Skip empty lines. */
}
if (buf[0] == '#') {
printf("%s%s%s", HEADING_STYLE, buf, RESET_STYLING);
}
if (buf[0] == '>') {
printf("%s%s%s", SUBHEADING_STYLE, buf, RESET_STYLING);
}
if (buf[0] == '-') {
printf("%s%s%s", COMMAND_DESC_STYLE, buf, RESET_STYLING);
}
if (buf[0] == '`') {
printf("%s%s%s", COMMAND_STYLE, buf, RESET_STYLING);
}
}
fclose(page);
restore_console(); /* Restores previous console mode in Win10 1503+ */
}
FILE *
open_index(const char *mode)
{
char buf[BUF_SIZE];
FILE *fp;
snprintf(buf, BUF_SIZE, "%s%s/%s",
getenv("HOME"), PAGES_PATH, "index");
fp = fopen(buf, mode);
if (!fp)
error_terminate("Failed to open index; "
"you should probably run 'tldr -u'", mode);
return fp;
}
int
main(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "luh")) != -1) {
switch (opt) {
case 'l':
list_pages();
return 0;
case 'u':
puts("Fetching pages...");
fetch_pages();
puts("Extracting pages...");
extract_pages();
puts("Indexing pages...");
index_pages();
return 0;
case 'h':
print_usage();
return 0;
default:
print_usage();
return 1;
}
}
if (argc != 2) {
print_usage();
return 1;
}
display_page(argv[1]);
return 0;
}