-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtabconv.c
More file actions
512 lines (458 loc) · 15 KB
/
tabconv.c
File metadata and controls
512 lines (458 loc) · 15 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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/**
* @file tabconv.c
* @brief Unified tab conversion utility for converting between tabs and spaces.
*
* @details This program can convert tabs to spaces or spaces to tabs based on
* command-line options, with configurable tab width.
*
* Copyright (c) 2019-2025, Vlad Shurupov
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
* See LICENSE.md for full license text.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>
static int col;
/**
* @brief Conversion mode enumeration.
*/
typedef enum {
MODE_SPACES, /* Convert tabs to spaces (default) */
MODE_TABS, /* Convert spaces to tabs */
MODE_NORMALIZE /* Auto-detect and normalise to specified style */
} conversion_mode_t;
/**
* @brief Indentation style detection result.
*/
typedef enum {
INDENT_TABS, /* File uses tabs for indentation */
INDENT_SPACES, /* File uses spaces for indentation */
INDENT_MIXED, /* File uses both tabs and spaces inconsistently */
INDENT_NONE /* File has no indentation (or detection inconclusive) */
} indent_style_t;
/**
* @brief Detect the indentation style of a file.
* @param in Input file pointer (will be rewound after detection).
* @param tab_width Tab width in spaces.
* @return Detected indentation style.
*/
static indent_style_t detect_ident(FILE *in, int tab_width)
{
(void)tab_width;
int c;
bool line_start = true;
bool in_indent = true;
int tabs_found = 0;
int spaces_found = 0;
bool line_has_tabs = false;
bool line_has_spaces = false;
bool mixed_line_found = false;
int lines_sampled = 0;
const int max_lines = 100; // Sample first 100 lines
// Store current position
long start_pos = ftell(in);
while (lines_sampled < max_lines && (c = fgetc(in)) != EOF) {
if (line_start) {
in_indent = true;
line_has_tabs = false;
line_has_spaces = false;
}
if (c == '\n') {
line_start = true;
in_indent = false;
lines_sampled++;
if (line_has_tabs && line_has_spaces) {
mixed_line_found = true;
}
continue;
}
if (line_start) {
if (in_indent) {
if (c == '\t') {
tabs_found++;
line_has_tabs = true;
} else if (c == ' ') {
spaces_found++;
line_has_spaces = true;
} else {
// First non-whitespace character
in_indent = false;
line_start = false;
}
}
} else {
line_start = false;
}
}
// Rewind to start
fseek(in, start_pos, SEEK_SET);
// Analyse results
(void)mixed_line_found;
if (tabs_found > 0 && spaces_found == 0) {
return INDENT_TABS;
} else if (spaces_found > 0 && tabs_found == 0) {
return INDENT_SPACES;
} else if (tabs_found > 0 && spaces_found > 0) {
return INDENT_MIXED;
} else {
return INDENT_NONE;
}
}
/**
* @brief Process accumulated spaces, converting to tabs + spaces.
* @param out Output file pointer.
* @param space_count Number of accumulated spaces.
* @param tab_width Tab width in spaces.
*/
static void process_spaces(FILE *out, int space_count, int tab_width)
{
int remaining = space_count;
while (remaining > 0) {
// Calculate spaces to next tab stop
int spaces_to_next_tab = tab_width - (col % tab_width);
if (spaces_to_next_tab <= remaining) {
// We can replace these spaces with a tab
fputc('\t', out);
col += spaces_to_next_tab;
remaining -= spaces_to_next_tab;
} else {
// Not enough spaces to reach next tab stop, output as spaces
for (int i = 0; i < remaining; i++) {
fputc(' ', out);
col++;
}
remaining = 0;
}
}
}
/**
* @brief Process character in spaces-to-tabs conversion mode.
* @param c The current character read from the file.
* @param out Output file pointer.
* @param tab_width Tab width in spaces.
* @param space_count Pointer to accumulated space count.
*/
static void proc_char_tabs_mode(int c, FILE *out, int tab_width, int *space_count)
{
switch (c) {
case ' ':
// Accumulate spaces
(*space_count)++;
break;
case '\n':
// At newline, process any accumulated spaces first
if (*space_count > 0) {
process_spaces(out, *space_count, tab_width);
*space_count = 0;
}
fputc(c, out);
col = 0;
break;
default:
// For any other character, process accumulated spaces first
if (*space_count > 0) {
process_spaces(out, *space_count, tab_width);
*space_count = 0;
}
fputc(c, out);
col++;
break;
}
}
/**
* @brief Process character in tabs-to-spaces conversion mode.
* @param c The current character read from the file.
* @param out A pointer to the output file where formatted characters are written.
* @param tab_width The number of spaces per tab.
*/
static void proc_char_spaces_mode(int c, FILE *out, int tab_width)
{
switch (c) {
case '\t':
{
int spaces = tab_width - (tab_width > 0 ? col % tab_width : 0);
for (int i = 0; i < spaces; i++) {
fputc(' ', out);
col++;
}
}
break;
case '\n':
col = 0;
fputc(c, out);
break;
default:
fputc(c, out);
col++;
break;
}
}
/**
* @brief Print usage information.
* @param program_name Name of the program (argv[0]).
*/
static void print_usage(const char *program_name)
{
fprintf(stderr, "Usage: %s [OPTIONS] <tab-width> <file(s)>\n", program_name);
fprintf(stderr, "Unified tab conversion utility\n\n");
fprintf(stderr, "Conversion modes (default: --spaces):\n");
fprintf(stderr, " -s, --spaces Convert tabs to spaces (default)\n");
fprintf(stderr, " -t, --tabs Convert spaces to tabs\n");
fprintf(stderr, " -n, --normalize Auto-detect and convert to specified style\n");
fprintf(stderr, "\nCommon options:\n");
fprintf(stderr, " -h, --help Show this help message\n");
fprintf(stderr, " -v, --verbose Show detailed output\n");
fprintf(stderr, " -b, --backup Create backup copies before modification\n");
fprintf(stderr, "\nExamples:\n");
fprintf(stderr, " %s 4 file.c # Convert tabs to 4 spaces\n", program_name);
fprintf(stderr, " %s --tabs 4 file.c # Convert spaces to tabs (4-space width)\n", program_name);
fprintf(stderr, " %s --spaces 2 *.py # Convert tabs to 2 spaces\n", program_name);
}
/**
* @brief Process a single file.
* @param filename Path to the file to process.
* @param tab_width Tab width in spaces.
* @param mode Conversion mode.
* @param verbose Verbose output flag.
* @param backup Backup flag (create backup copy if non-zero).
* @return 0 on success, 1 on error.
*/
static int process_file(const char *filename, int tab_width, conversion_mode_t mode, bool verbose, bool backup)
{
char tmp_name[1024];
if (verbose) {
fprintf(stderr, "Processing: %s (width: %d, mode: %s)\n",
filename, tab_width,
mode == MODE_SPACES ? "tabs→spaces" :
mode == MODE_TABS ? "spaces→tabs" : "normalise");
}
// Get original file permissions
struct stat st;
if (stat(filename, &st) != 0) {
perror("Could not stat the file");
return 1;
}
FILE *in = fopen(filename, "r");
if (!in) {
perror("Could not open the file");
return 1;
}
// Create backup if requested
if (backup) {
char backup_name[1024];
snprintf(backup_name, sizeof(backup_name), "%s.bak", filename);
FILE *backup_file = fopen(backup_name, "w");
if (!backup_file) {
perror("Could not create backup file");
fclose(in);
return 1;
}
// Copy permissions to backup file
if (chmod(backup_name, st.st_mode) != 0) {
perror("Could not set permissions on backup file");
fclose(backup_file);
fclose(in);
remove(backup_name);
return 1;
}
// Preserve timestamps on backup file
struct timespec backup_times[2];
backup_times[0].tv_sec = st.st_atime;
backup_times[0].tv_nsec = 0;
backup_times[1].tv_sec = st.st_mtime;
backup_times[1].tv_nsec = 0;
if (utimensat(AT_FDCWD, backup_name, backup_times, 0) != 0) {
perror("Could not preserve timestamps on backup file");
// Continue anyway - timestamps are less critical
}
// Copy file contents
int ch;
while ((ch = fgetc(in)) != EOF) {
fputc(ch, backup_file);
}
fclose(backup_file);
// Rewind input file for processing
rewind(in);
}
// Create temporary file name
snprintf(tmp_name, sizeof(tmp_name), "%.24s.}}{{", filename);
FILE *out = fopen(tmp_name, "w");
if (!out) {
perror("Could not create the temporary file");
fclose(in);
return 1;
}
// Apply original file permissions to temporary file
if (chmod(tmp_name, st.st_mode) != 0) {
perror("Could not set permissions on temporary file");
fclose(out);
fclose(in);
remove(tmp_name);
return 1;
}
// Preserve original file timestamps
struct timespec times[2];
times[0].tv_sec = st.st_atime; // Access time (seconds)
times[0].tv_nsec = 0; // Nanoseconds (not available in st_atime)
times[1].tv_sec = st.st_mtime; // Modification time (seconds)
times[1].tv_nsec = 0; // Nanoseconds (not available in st_mtime)
if (utimensat(AT_FDCWD, tmp_name, times, 0) != 0) {
perror("Could not preserve timestamps on temporary file");
// Continue anyway - timestamps are less critical than permissions
}
int c;
int space_count = 0;
col = 0;
// For normalise mode, detect indentation style first
bool using_tabs_mode = false;
bool copy_unchanged = false;
if (mode == MODE_NORMALIZE) {
indent_style_t detected = detect_ident(in, tab_width);
if (verbose) {
const char *style_names[] = {"tabs", "spaces", "mixed", "none"};
fprintf(stderr, "Detected indentation: %s\n", style_names[detected]);
}
// Decision logic:
// - Tabs or mixed → convert to spaces (cleanest result)
// - Spaces → convert to tabs (optimise)
// - None → copy unchanged
if (detected == INDENT_TABS || detected == INDENT_MIXED) {
// Convert to spaces
using_tabs_mode = false;
copy_unchanged = false;
} else if (detected == INDENT_SPACES) {
// Convert to tabs
using_tabs_mode = true;
copy_unchanged = false;
} else { // INDENT_NONE
// Copy unchanged
using_tabs_mode = false;
copy_unchanged = true;
}
} else {
using_tabs_mode = (mode == MODE_TABS);
copy_unchanged = false;
}
// Process each character based on conversion mode
while ((c = fgetc(in)) != EOF) {
if (copy_unchanged) {
// Simple copy for INDENT_NONE case
fputc(c, out);
if (c == '\n')
col = 0;
else
col++;
} else if (using_tabs_mode) {
proc_char_tabs_mode(c, out, tab_width, &space_count);
} else {
proc_char_spaces_mode(c, out, tab_width);
}
}
// Process any trailing spaces at EOF (tabs mode only)
if (using_tabs_mode && space_count > 0)
process_spaces(out, space_count, tab_width);
fclose(in);
fclose(out);
// Replace original with temporary file
if (remove(filename)) {
perror("Could not remove the file");
remove(tmp_name);
return 1;
}
if (rename(tmp_name, filename)) {
perror("Error renaming temp file");
return 1;
}
return 0;
}
/**
* @brief Main function.
* @param argn Number of command-line arguments.
* @param argv Array of command-line arguments.
* @return Exit status (0 = success, 1 = error).
*/
int main(int argn, char **argv)
{
conversion_mode_t mode = MODE_SPACES; // Default mode
bool verbose = false;
bool backup = false;
bool help = false;
int tab_width = 0;
// Parse command-line options
static struct option long_options[] = {
{"spaces", no_argument, 0, 's'},
{"tabs", no_argument, 0, 't'},
{"normalize", no_argument, 0, 'n'},
{"verbose", no_argument, 0, 'v'},
{"backup", no_argument, 0, 'b'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
int opt;
int option_index = 0;
while ((opt = getopt_long(argn, argv, "stnvhb", long_options, &option_index)) != -1) {
switch (opt) {
case 's':
mode = MODE_SPACES;
break;
case 't':
mode = MODE_TABS;
break;
case 'n':
mode = MODE_NORMALIZE;
break;
case 'v':
verbose = true;
break;
case 'b':
backup = true;
break;
case 'h':
help = true;
break;
case '?':
// getopt_long already printed an error message
return 1;
default:
fprintf(stderr, "Unknown option: %c\n", opt);
return 1;
}
}
if (help) {
print_usage(argv[0]);
return 0;
}
// Check remaining arguments: need tab-width and at least one file
if (optind >= argn) {
fprintf(stderr, "Error: Missing tab width argument\n");
print_usage(argv[0]);
return 1;
}
// Parse tab width
tab_width = atoi(argv[optind]);
if (tab_width <= 0) {
fprintf(stderr, "Error: tab width must be positive integer\n");
return 1;
}
optind++;
// Check for file arguments
if (optind >= argn) {
fprintf(stderr, "Error: No files specified\n");
print_usage(argv[0]);
return 1;
}
// Process each file
int exit_code = 0;
for (int i = optind; i < argn; i++) {
if (process_file(argv[i], tab_width, mode, verbose, backup) != 0)
exit_code = 1;
}
return exit_code;
}