File: lintex.c

package info (click to toggle)
lintex 1.06-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 204 kB
  • ctags: 88
  • sloc: cpp: 431; ansic: 397; makefile: 33
file content (686 lines) | stat: -rw-r--r-- 18,859 bytes parent folder | download
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*------------------------------------------------------*
 | Author: Maurizio Loreti, aka MLO or (HAM) I3NOO      |
 | Work:   University of Padova - Department of Physics |
 |         Via F. Marzolo, 8 - 35131 PADOVA - Italy     |
 | Phone:  ++39(49) 827-7216     FAX: ++39(49) 827-7102 |
 | EMail:  loreti@padova.infn.it                        |
 | WWW:    http://wwwcdf.pd.infn.it/~loreti/mlo.html    |
 *------------------------------------------------------*

   $Id: lintex.c,v 1.6 2006/09/11 12:47:38 loreti Exp $


  Description: the command "lintex [-i] [-r] [dir1 [dir2 ...]]" scans
    the directories given as parameters (the default is the current
    directory), looking for TeX-related files no more needed and to be
    removed.  With the option -i the user is asked before actually
    removing any file; with the option -r, the given directories are
    scanned recursively.

  Environment: the program has been developed under Solaris 2; but
    should run on every system supporting opendir/readdir/closedir and
    stat.  The file names in the struct dirent (defined in <dirent.h>)
    are assumed to be null terminated (this is guaranteed under Solaris
    2).

  Compiler flags: -DDEBUG to list remove commands without their actual
    execution; -DFULLDEBUG for the above and a lot of printouts.

  History:
    1.00 - 1996-07-05 , first release
    1.01 - 1996-07-25 , improved (modify time in nodes)
    1.02 - 1996-10-16 , list garbage files w/out .tex
    1.03 - 1997-05-21 , call to basename; uploaded to CTAN, where lives
                        in /tex-archive/support/lintex .  Added a man
                        page and a Makefile.
    1.04 - 1998-06-22 , multiple directories in the command line; -r
                        command option; -I and -R accepted, in addition
                        to -i and -r; more extensions in protoTree; code
                        cleanup.
    1.05 - 2001-12-02 , linked list structure optimized.
    1.06 - 2002-09-25 , added .pdf extension.

  ---------------------------------------------------------------------*/

/**
 | Included files
**/

#include <stdio.h>              /* Standard library */
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#include <sys/types.h>          /* Unix proper */
#include <sys/stat.h>
#include <dirent.h>

/**
 | Definitions:
 | - LONG_ENOUGH: length of the buffer used to read the answer from the
 |   user, when the -i command option is specified;
 | - MAX_B_EXT: maximum length of the extension for backup files (including
 |   the leading dot and the trailing '\0').
 | - TRUE, FALSE: guess what?
**/

#define LONG_ENOUGH 48
#define MAX_B_EXT    8
#define TRUE         1
#define FALSE        0

/**
 | Type definitions:
 | - Froot: the root of a linked list structure, where file names having a
 |     given extension (pointed to by Froot.extension) will be stored;
 |     these linked lists are also used to store directory names (with fake
 |     extension strings).
 | - Fnode: an entry in the linked list of the file names; contains the
 |     file modification time, the file name and a pointer to the next node.
 |     As a side note, the so called 'struct hack', here used to store the
 |     file name, is not guaranteed to work by the current C ANSI standard;
 |     but no environment/compiler where it does not work is currently
 |     known.
**/

typedef struct sFroot {
  char *extension;
  struct sFnode *firstNode;
  struct sFnode *lastNode;
} Froot;

typedef struct sFnode {
  time_t mTime;
  struct sFnode *next;
  char name[1];
} Fnode;

/**
 | Global variables:
 | - confirm: will be 0 or 1 according to the -i command option;
 | - recurse: will be 0 or 1 according to the -r command option;
 | - bExt: the extension for backup files: defaults to "~" (the emacs
 |   convention);
 | - n_bExt: the length of the previous string;
 | - programName: the name of the executable;
 | - protoTree: Froot's of the file names having extensions relevant to
 |   TeX.  ".tex" extensions are assumed to be pointed to by protoTree[0].
**/

static int     confirm         = FALSE;
static int     recurse         = FALSE;
static char    bExt[MAX_B_EXT] = "~";
static size_t  n_bExt;
static char   *programName;

static Froot protoTree[] = {
  {".tex", 0, 0},                        /* Must be first */
  {".aux", 0, 0},
  {".log", 0, 0},
  {".dvi", 0, 0},
  {".ps",  0, 0},
  {".pdf", 0, 0},
  {".toc", 0, 0},
  {".lof", 0, 0},
  {".lot", 0, 0},
  {".idx", 0, 0},
  {".ind", 0, 0},
  {".ilg", 0, 0},
  {0, 0, 0}                              /* Must be last (sentinel) */
};

/**
 | Procedure prototypes (in alphabetical order)
**/

static char  *baseName(char *);
static Froot *buildTree(char *, Froot *);
static void   clean(char *);
static void   examineTree(Froot *, char *);
static void   insertNode(char *, size_t, time_t, Froot *);
static void   noMemory(void);
static void   nuke(char *);
static void   releaseTree(Froot *);
static void   syntax(void);

#ifdef FULLDEBUG
static void   printTree(Froot *);
#endif   /* FULLDEBUG */

/*---------------------------*
 | And now, our main program |
 *---------------------------*/

int main(
  int argc,
  char *argv[]
){
  Froot *dirNames;              /* To hold the directories to be scanned */
  Fnode *pFN;                   /* Running pointer over directory names  */
  int    to_bExt  = FALSE;      /* Flag "next parameter to bExt"         */

  /**
   | Scans the arguments appropriately; the required directories are stored
   | in the linked list starting at "dirNames".
  **/

  programName = baseName(argv[0]);

  if ((dirNames = calloc(2, sizeof(Froot))) == 0) {
    noMemory();
  }
  dirNames->extension = "argv";

  while (--argc) {
    if ((*++argv)[0] == '-') {
      switch ( (*argv)[1] ) {
        case 'i':   case 'I':
          confirm = TRUE;
          break;

        case 'r':   case 'R':
          recurse = TRUE;
          break;

        case 'b':   case 'B':
          to_bExt = TRUE;
          break;

        default:
          syntax();
      }

    } else {
      if (to_bExt) {
        strcpy(bExt, *argv);
        to_bExt = FALSE;
      } else {
        insertNode(*argv, 0, 0, dirNames);
      }
    }
  }

  if (to_bExt) {
    syntax();
  }
  n_bExt = strlen(bExt);

  /**
   | If no parameter has been given, clean the current directory
  **/

  if ((pFN = dirNames->firstNode) == 0) {
    clean(".");
  } else {
    while (pFN != 0) {
      clean(pFN->name);
      pFN = pFN->next;
    }
  }
  releaseTree(dirNames);

  return EXIT_SUCCESS;
}

/*------------------------------------------*
 | The called procedures (in logical order) |
 *------------------------------------------*/

static void insertNode(
  char   *name,
  size_t  lName,
  time_t  mTime,
  Froot  *root
){

  /**
   | Creates a new Fnode, to be inserted at the _end_ of the linked
   | list pointed to by root->firstNode (i.e., the list is organized
   | as a "queue", a.k.a. "FIFO" list): if a new node cannot be created,
   | an error message is printed and the program aborted.
   | If "lName" is bigger than zero, the file name is represented by the
   | first lName characters of "name"; otherwise by the whole string in
   | "name".
  **/

  Fnode  *pFN;                  /* The new node created by insertNode */
  size_t  sSize;                /* Structure size                     */

  sSize = sizeof(Fnode) + (lName == 0 ? strlen(name) : lName);

  if ((pFN = malloc(sSize)) == 0) {
    noMemory();
  }
  pFN->mTime = mTime;
  pFN->next  = 0;

  if (lName == 0) {
    strcpy(pFN->name, name);
  } else {
    strncpy(pFN->name, name, lName);
    pFN->name[lName] = '\0';
  }

  if (root->lastNode == 0) {
    root->firstNode = pFN;
  } else {
    root->lastNode->next = pFN;
  }
  root->lastNode = pFN;
}

static void noMemory(void)
{
  fprintf(stderr, "%s: couldn't obtain heap memory\n", programName);
  exit(EXIT_FAILURE);
}

static void clean(
  char *dirName
){

  /**
   | Does the job for the directory "dirName".
   |
   | Builds a structure holding the TeX-related files, and does the
   | required cleanup; finally, removes the file structure.
   | If the list appended to "dirs" has been filled, recurse over the
   | tree of subdirectories.
  **/

  Froot *teXTree;               /* Root node of the TeX-related files  */
  Froot *dirs;                  /* Subdirectories in this directory    */
  Fnode *pFN;                   /* Running pointer over subdirectories */

  if ((dirs = calloc(2, sizeof(Froot))) == 0) {
    noMemory();
  }
  dirs->extension = "subs";

  if ((teXTree = buildTree(dirName, dirs)) != 0) {

#ifdef FULLDEBUG
    printTree(teXTree);
#endif   /* FULLDEBUG */

    examineTree(teXTree, dirName);
    releaseTree(teXTree);
  }

  for (pFN = dirs->firstNode;   pFN != 0;   pFN = pFN->next) {
    clean(pFN->name);
  }
  releaseTree(dirs);
}

static Froot *buildTree(
  char  *dirName,
  Froot *subDirs
){

  /**
   | - Opens the required directory;
   | - allocates a structure to hold the names of the TeX-related files,
   |   initialized from the global structure "protoTree";
   | - starts a loop over all the files of the given directory.
  **/

  DIR           *pDir;         /* Pointer returned from opendir()    */
  struct dirent *pDe;          /* Pointer returned from readdir()    */
  Froot         *teXTree;      /* Root node of the TeX-related files */

#ifdef FULLDEBUG
  printf("* Scanning directory \"%s\" - confirm = %c, recurse = %c\n",
         dirName, (confirm ? 'Y' : 'N'), (recurse ? 'Y' : 'N'));
  printf("* Editor trailer: \"%s\"\n", bExt);
  puts("------------------------------Phase 1: directory scan");
#endif   /* FULLDEBUG */

  if ((pDir = opendir(dirName)) == 0) {
    fprintf(stderr,
            "%s: \"%s\" cannot be opened (or is not a directory)\n",
            programName, dirName);
    return 0;
  }

  if ((teXTree = malloc(sizeof(protoTree))) == 0) {
    noMemory();
  }
  memcpy(teXTree, protoTree, sizeof(protoTree));

  while ((pDe = readdir(pDir)) != 0) {
    char    tName[FILENAME_MAX];         /* Fully qualified file name       */
    struct  stat sStat;                  /* To be filled by stat(2)         */
    size_t  len;                         /* Lenght of the current file name */
    size_t  last;                        /* Index of its last character     */
    char   *pFe;                         /* Pointer to file extension       */

    /**
     | - Tests for empty inodes (already removed files);
     | - skips the . and .. (current and previous directory);
     | - tests the trailing part of the file name against the extension of
     |   the backup files, to be always deleted.
    **/

    if (pDe->d_ino == 0)                continue;
    if (strcmp(pDe->d_name, ".")  == 0) continue;
    if (strcmp(pDe->d_name, "..") == 0) continue;

    sprintf(tName, "%s/%s", dirName, pDe->d_name);

    len  = strlen(pDe->d_name);
    last = len - 1;

    if (n_bExt != 0) {                  /* If 0, no backup files to delete */
      int crit;                         /* What exceeds backup extensions  */

      crit = len - n_bExt;
      if (crit > 0   &&   strcmp(pDe->d_name + crit, bExt) == 0) {
        nuke(tName);
        continue;
      }
    }

    /**
     | If the file is a directory and the -r option has been given, stores
     | the directory name in the linked list pointed to by "subDirs", for
     | recursive calls.
     |
     | N.B.: if stat(2) fails, the file is skipped.
    **/

    if (stat(tName, &sStat) != 0) {
      fprintf(stderr, "File \"%s", tName);
      perror("\"");
      continue;
    }

    if (S_ISDIR(sStat.st_mode) != 0) {

#ifdef FULLDEBUG
      printf("File %s - is a directory\n", pDe->d_name);
#endif   /* FULLDEBUG */

      if (recurse) {
        insertNode(tName, 0, 0, subDirs);
      }
      continue;
    }

    /**
     | If the file has an extension (the rightmost dot followed by at
     | least one character), and if that extension matches one of the
     | entries in teXTree[i].extension: stores the file name (with the
     | extension stripped) in the appropriate linked list, together with
     | its modification time.
    **/

    if ((pFe = strrchr(pDe->d_name, '.')) != 0) {
      size_t nameLen;

      nameLen = pFe - pDe->d_name;
      if (nameLen < last) {
        Froot *pTT;

#ifdef FULLDEBUG
        printf("File %s - extension %s", pDe->d_name, pFe);
#endif   /* FULLDEBUG */

        /**
         | Loop on recognized TeX-related file extensions
        **/

        for (pTT = teXTree;   pTT->extension != 0;   pTT++) {
          if (strcmp(pFe, pTT->extension) == 0) {
            insertNode(pDe->d_name, nameLen, sStat.st_mtime, pTT);

#ifdef FULLDEBUG
            printf(" - inserted in tree");
#endif   /* FULLDEBUG */
            break;
          }
        } /* loop on known extensions */

#ifdef FULLDEBUG
        puts("");

      } else {
        printf("File %s - empty extension\n", pDe->d_name);
#endif   /* FULLDEBUG */
      }

#ifdef FULLDEBUG
    } else {
      printf("File %s - without extension\n", pDe->d_name);
#endif   /* FULLDEBUG */
    }
  }             /* while (readdir) ... */

  if (closedir(pDir) != 0) {
    fprintf(stderr, "Directory \"%s", dirName);
    perror("\"");
  }

  return teXTree;
}

#ifdef FULLDEBUG
static void printTree(
  Froot *teXTree
){

  /**
   | Prints all the file names archived in the linked lists (for
   | debugging purposes).
  **/

  Froot *pTT;           /* Running pointer over teXTree elements */

  puts("------------------------------Phase 2: tree printout");
  for (pTT = teXTree;   pTT->extension != 0;   pTT++) {
    Fnode *pTeX;              /* Running pointer over TeX-related files */
    int    nNodes = 0;        /* Counter */

    for (pTeX = pTT->firstNode;   pTeX != 0;   pTeX = pTeX->next) {
      ++nNodes;
      printf("%s%s\n", pTeX->name, pTT->extension);
    }
    printf("  --> %d file%s with extension %s\n", nNodes,
           (nNodes == 1 ? "" : "s"), pTT->extension);
  }
}
#endif   /* FULLDEBUG */

static void examineTree(
  Froot *teXTree,
  char  *dirName
){

  /**
   | Examines the linked lists for this directory doing the effective
   | cleanup.
  **/

  Froot *pTT;           /* Pointer over linked list trees      */
  Fnode *pTeX;          /* Running pointer over the .tex files */

  /**
   | Looks, for all the .tex files, if a corresponding entry with the same
   | name exists (with a different extension) in the other lists; if so,
   | and if its modification time is later than the one of the related
   | .tex file, removes it from the file system.
  **/
#ifdef FULLDEBUG
  puts("------------------------------Phase 3: effective cleanup");
#endif   /* FULLDEBUG */

  for (pTeX = teXTree->firstNode;   pTeX != 0;   pTeX = pTeX->next) {
    char tName[FILENAME_MAX];

    sprintf(tName, "%s/%s.tex", dirName, pTeX->name);
    pTT = teXTree;

#ifdef FULLDEBUG
    printf("    Finding files related to %s:\n", tName);
#endif   /* FULLDEBUG */

    for (pTT++;   pTT->extension != 0;   pTT++) {
      Fnode *pComp;

      for (pComp = pTT->firstNode;   pComp != 0;   pComp = pComp->next) {
        char cName[FILENAME_MAX];

        if (strcmp(pTeX->name, pComp->name) == 0) {
          sprintf(cName, "%s/%s%s", dirName, pTeX->name, pTT->extension);
          pComp->name[0] = '\0';

          if (difftime(pComp->mTime, pTeX->mTime) > 0.0) {
            nuke(cName);
          } else {
            printf("*** %s not removed; %s is newer ***\n", cName, tName);
          }
          break;
        }
      }
    }
  }

  /**
   | If some garbage file has not been deleted, list it
  **/

#ifdef FULLDEBUG
  puts("------------------------------Phase 4: left garbage files");
#endif   /* FULLDEBUG */

  pTT = teXTree;
  for (pTT++;  pTT->extension != 0;  pTT++) {
    Fnode *pComp;

    for (pComp = pTT->firstNode;   pComp != 0;   pComp = pComp->next) {
      if (pComp->name[0] != '\0') {
        char cName[FILENAME_MAX];

        sprintf(cName, "%s/%s%s", dirName, pComp->name, pTT->extension);
        printf("*** %s not removed; no .tex file found ***\n", cName);
      }
    }
  }
}

static void releaseTree(
  Froot *teXTree
){

  /**
   | Cleanup of the file name storage structures: an _array_ of Froot's,
   | terminated by a NULL extension pointer as a sentinel, is assumed.
   | Every linked list nodes is freed; then releaseTree frees also the
   | root structure.
  **/

  Froot *pFR;

#ifdef FULLDEBUG
  puts("------------------------------Phase 5: tree cleanup");
#endif   /* FULLDEBUG */

  for (pFR = teXTree;   pFR->extension != 0;   pFR++) {
    Fnode *pFN, *p;

#ifdef FULLDEBUG
    int nNodes = 0;

    printf("Dealing with extensions %s ...", pFR->extension);
#endif   /* FULLDEBUG */

    for (pFN = pFR->firstNode;   pFN != 0;   pFN = p) {
      p = pFN->next;
      free(pFN);

#ifdef FULLDEBUG
      nNodes++;
#endif   /* FULLDEBUG */
    }

#ifdef FULLDEBUG
    printf("   %d nodes freed\n", nNodes);
#endif   /* FULLDEBUG */
  }

  free(teXTree);
}

static void nuke(
  char *name
){

  /**
   | Removes "name" (the fully qualified file name) from the file system
  **/

#if defined(FULLDEBUG) || defined(DEBUG)
  printf("*** File \"%s\" would have been removed ***\n", name);
#else

  if (confirm) {
    char yn[LONG_ENOUGH], c;

    do {
      printf("Remove %s (y|n) ? ", name);
      if (fgets(yn, LONG_ENOUGH, stdin) == 0) return;
      if (yn[0] == '\0' || (c = tolower((unsigned char) yn[0])) == 'n') {
        return;
      }
    } while (c != 'y');
  }

  if (remove(name) != 0) {
    fprintf(stderr, "File \"%s", name);
    perror("\"");
  } else {
    printf("%s has been removed\n", name);
  }

#endif   /* FULLDEBUG or DEBUG */
}

static char *baseName(
  char *pc
){
  char *p;

/**
 | Strips the (eventual) path information from the string pointed
 | to by 'pc'; if no file name is given, returns an empty string.
**/

  p = strrchr(pc, '/');
  if (p == 0) return pc;
  return ++p;
}

static void syntax()
{
  puts("Usage:");
  printf("  %s [-i] [-r] [-b ext] [dir [dir ... ]]\n", programName);
  puts("Purpose:");
  puts("  removes unneeded TeX auxiliary files and editor backup files from"
       " the");
  puts("  given directories (default: the current directory); the TeX files"
       " are");
  puts("  actually removed only if their modification time is more recent"
       " than");
  puts("  the one of the related TeX source.");
  puts("Options:");
  puts("  -i : asks the user before removing any file;");
  puts("  -r : scans recursively the subdirectories of the given"
       " directories;");
  puts("  -b : \"ext\" is the trailing string identifying editor backup"
       " files");
  puts("       (defaults to \"~\").  -b \"\" avoids any cleanup of special"
       " files.");

  exit(EXIT_SUCCESS);
}