File: extract.c

package info (click to toggle)
swish++ 6.1.5-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 2,256 kB
  • ctags: 1,759
  • sloc: ansic: 11,931; lisp: 804; sh: 629; perl: 366; makefile: 80
file content (513 lines) | stat: -rw-r--r-- 16,438 bytes parent folder | download | duplicates (6)
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
/*
**      SWISH++
**      extract.c
**
**      Copyright (C) 1998  Paul J. Lucas
**
**      This program is free software; you can redistribute it and/or modify
**      it under the terms of the GNU General Public License as published by
**      the Free Software Foundation; either version 2 of the License, or
**      (at your option) any later version.
**
**      This program is distributed in the hope that it will be useful,
**      but WITHOUT ANY WARRANTY; without even the implied warranty of
**      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**      GNU General Public License for more details.
**
**      You should have received a copy of the GNU General Public License
**      along with this program; if not, write to the Free Software
**      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

// standard
#include <cstdlib>                              /* for exit(2) */
#include <cstring>
#include <fstream>
#include <iomanip>                              /* for setfill(), setw() */
#include <iostream>
#include <string>
#include <sys/types.h>
#include <time.h>

// local
#include "platform.h"
#include "config.h"
#include "ExcludeFile.h"
#include "exit_codes.h"
#include "ExtractExtension.h"
#include "ExtractFile.h"
#include "ExtractFilter.h"
#include "FilterFile.h"
#ifndef PJL_NO_SYMBOLIC_LINKS
#include "FollowLinks.h"
#endif
#include "mmap_file.h"
#include "option_stream.h"
#include "postscript.h"
#include "RecurseSubdirs.h"
#include "StopWordFile.h"
#include "stop_words.h"
#include "util.h"
#include "Verbosity.h"
#include "version.h"
#include "word_util.h"

using namespace PJL;
using namespace std;

ExcludeFile         exclude_patterns;           // do not extract these
ExtractFile         include_patterns;           // do extract these
ExtractFilter       extract_as_filter;
ExtractExtension    extract_extension;
FilterFile          file_filters;
static bool         in_postscript;
char const*         me;                         // executable name
int                 num_examined_files;
int                 num_extracted_files;
RecurseSubdirs      recurse_subdirectories;
Verbosity           verbosity;                  // how much to print

static bool         extract_word( char *word, int len, ostream& );
static void         extract_words(
                        mmap_file::const_iterator begin,
                        mmap_file::const_iterator end,
                        ostream&
                    );
static ostream&     usage( ostream& = cerr );

#define EXTRACT
#include "do_file.c"
#include "directory.c"

//*****************************************************************************
//
// SYNOPSIS
//
        int main( int argc, char *argv[] )
//
// DESCRIPTION
//
//      Parse the command line, initialize, call other functions ... the usual
//      things that are done in main().
//
// PARAMETERS
//
//      argc    The number of arguments.
//
//      argv    A vector of the arguments; argv[argc] is null.  Aside from the
//              options below, the arguments are the names of the files and
//              directories to be extracted.
//
// SEE ALSO
//
//      Bjarne Stroustrup.  "The C++ Programming Language, 3rd ed."
//      Addison-Wesley, Reading, MA, 1997.  pp. 116-118.
//
//*****************************************************************************
{
    me = ::strrchr( argv[0], '/' );             // determine base name...
    me = me ? me + 1 : argv[0];                 // ...of executable

#ifdef  RLIMIT_CPU                              /* SVR4, 4.2+BSD */
    //
    // Max-out the amount of CPU time we can run since extraction can take a
    // while.
    //
    max_out_limit( RLIMIT_CPU );
#endif
    /////////// Process command-line options //////////////////////////////////

    static option_stream::spec const opt_spec[] = {
        "help",         0, '?',
        "config",       1, 'c',
        "pattern",      1, 'e',
        "no-pattern",   1, 'E',
        "filter",       0, 'f',
#ifndef PJL_NO_SYMBOLIC_LINKS
        "follow-links", 0, 'l',
#endif
        "no-recurse",   0, 'r',
        "stop-file",    1, 's',
        "dump-stop",    0, 'S',
        "verbose",      1, 'v',
        "version",      0, 'V',
        "extension",    1, 'x',
        0
    };

    char const*     config_file_name_arg = ConfigFile_Default;
    bool            dump_stop_words_opt = false;
    bool            extract_as_filter_opt = false;
    char const*     extract_extension_arg = 0;
#ifndef PJL_NO_SYMBOLIC_LINKS
    bool            follow_symbolic_links_opt = false;
#endif
    bool            recurse_subdirectories_opt = false;
    StopWordFile    stop_word_file_name;
    char const*     stop_word_file_name_arg = 0;
    char const*     verbosity_arg = 0;

    option_stream opt_in( argc, argv, opt_spec );
    for ( option_stream::option opt; opt_in >> opt; )
        switch ( opt ) {

            case '?': // Print help.
                cerr << usage;

            case 'c': // Specify config. file.
                config_file_name_arg = opt.arg();
                break;

            case 'e': { // Filename pattern(s) to extract.
                char *a = opt.arg();
                for ( char *pat; pat = ::strtok( a, "," ); ) {
                    include_patterns.insert( pat, 0 );
                    a = 0;
                }
                break;
            }

            case 'E': { // Filename pattern(s) not to extract.
                char *a = opt.arg();
                for ( char *pat; pat = ::strtok( a, "," ); ) {
                    exclude_patterns.insert( pat );
                    a = 0;
                }
                break;
            }

            case 'f': // Run as a filter.
                extract_as_filter_opt = true;
                break;
#ifndef PJL_NO_SYMBOLIC_LINKS
            case 'l': // Follow symbolic links during extraction.
                follow_symbolic_links_opt = true;
                break;
#endif
            case 'r': // Specify whether to extract recursively.
                recurse_subdirectories_opt = true;
                break;

            case 's': // Specify stop-word list.
                stop_word_file_name_arg = opt.arg();
                break;

            case 'S': // Dump stop-word list.
                dump_stop_words_opt = true;
                break;

            case 'v': // Specify verbosity level.
                verbosity_arg = opt.arg();
                break;

            case 'V': // Display version and exit.
                cout << "SWISH++ " << version << endl;
                ::exit( Exit_Success );

            case 'x': // Specify filename extension to append.
                extract_extension_arg = opt.arg();
                break;

            default: // Bad option.
                cerr << usage;
        }
    argc -= opt_in.shift(), argv += opt_in.shift();

    //
    // First, parse the config. file (if any); then override variables
    // specified on the command line with options.
    //
    conf_var::parse_file( config_file_name_arg );

    if ( extract_as_filter_opt )
        extract_as_filter = true;
    if ( extract_as_filter ) {
        //
        // When running as a filter, patterns aren't used.  We clear them here
        // in case some were set via an IncludeFile directive in a
        // configuration file.  That let's us get away with not having to
        // special-case the code in do_file().
        //
        exclude_patterns.clear();
        include_patterns.clear();
    }
    if ( extract_extension_arg )
        extract_extension = extract_extension_arg;
    if ( *extract_extension != '.' )            // prepend '.' if needed
        extract_extension =
            string( "." ) + (char const*)extract_extension;
#ifndef PJL_NO_SYMBOLIC_LINKS
    if ( follow_symbolic_links_opt )
        follow_symbolic_links = true;
#endif
    if ( recurse_subdirectories_opt )
        recurse_subdirectories = false;
    if ( stop_word_file_name_arg )
        stop_word_file_name = stop_word_file_name_arg;
    if ( verbosity_arg )
        verbosity = verbosity_arg;

    /////////// Deal with stop-words //////////////////////////////////////////

    stop_words = new stop_word_set( stop_word_file_name );
    if ( dump_stop_words_opt ) {
        ::copy( stop_words->begin(), stop_words->end(),
            ostream_iterator< char const* >( cout, "\n" )
        );
        ::exit( Exit_Success );
    }

    /////////// Extract specified directories and files ///////////////////////

    bool const using_stdin = *argv && (*argv)[0] == '-' && !(*argv)[1];
    if ( !( extract_as_filter || using_stdin ) &&
        include_patterns.empty() && exclude_patterns.empty()
    )
        error() << "filename patterns must be specified when not"
                   " a filter nor\nusing standard input\n" << usage;

    if ( !argc )
        cerr << usage;

    ////////// Extract text from specified files //////////////////////////////

    time_t time = ::time( 0 );                  // Go!

    if ( extract_as_filter ) {
        //
        // Do a single file.
        //
        if ( !file_exists( *argv ) ) {
            error() << *argv << " does not exist\n";
            ::exit( Exit_No_Such_File );
        }
        do_file( *argv );
    } else if ( using_stdin ) {
        //
        // Read file/directory names from standard input.
        //
        char file_name[ PATH_MAX + 1 ];
        while ( cin.getline( file_name, PATH_MAX ) ) {
            if ( !file_exists( file_name ) ) {
                if ( verbosity > 3 )
                    cout << "  " << file_name << " (skipped: does not exist)\n";
                continue;
            }
            if ( is_directory() )
                do_directory( new_strdup( file_name ) );
            else
                do_file( file_name );
        }
    } else {
        //
        // Read file/directory names from command line.
        //
        for ( ; *argv; ++argv ) {
            if ( !file_exists( *argv ) ) {
                if ( verbosity > 3 )
                    cout << "  " << *argv << " (skipped: does not exist)\n";
                continue;
            }
            if ( is_directory() )
                do_directory( *argv );
            else
                do_file( *argv );
        }
    }

    if ( verbosity ) {
        time = ::time( 0 ) - time;              // Stop!
        cout << '\n' << me << ": done:\n  "
             << setfill('0')
             << setw(2) << (time / 60) << ':'
             << setw(2) << (time % 60)
             << " (min:sec) elapsed time\n  "
             << num_examined_files << " files, "
             << num_extracted_files << " extracted\n\n";
    }

    ::exit( Exit_Success );
}

//*****************************************************************************
//
// SYNOPSIS
//
        bool extract_word( register char *word, register int len, ostream &out )
//
// DESCRIPTION
//
//      Potentially extract the given word.
//
// PARAMETERS
//
//      word    The candidate word to be extracted.
//
//      len     The length of the word since it is not null-terminated.
//
//      out     The ostream to write the word to.
//
// RETURN VALUE
//
//      Returns true only if the word was extracted.
//
//*****************************************************************************
{
    if ( len < Word_Hard_Min_Size )
        return false;

    word[ len ] = '\0';

    ////////// Look for Encapsulated PostScript code and skip it //////////////

    if ( in_postscript ) {
        if ( !::strcmp( word, "%%Trailer" ) )
            in_postscript = false;
        return false;
    }
    static postscript_comment_set const postscript_comments;
    if ( postscript_comments.contains( word ) ) {
        in_postscript = true;
        return false;
    }
    static postscript_operator_set const postscript_operators;
    if ( postscript_operators.contains( word ) )
        return false;

    ////////// Strip chars not in Word_Begin_Chars/Word_End_Chars /////////////

    for ( register int i = len - 1; i >= 0; --i ) {
        if ( is_word_end_char( word[ i ] ) )
            break;
        --len;
    }
    if ( len < Word_Hard_Min_Size )
        return false;

    word[ len ] = '\0';

    while ( *word ) {
        if ( is_word_begin_char( *word ) || *word == '%' )
            break;
        --len, ++word;
    }
    if ( len < Word_Hard_Min_Size )
        return false;

    ////////// Discard what looks like ASCII hex data /////////////////////////

    if ( len > Word_Hex_Max_Size &&
         (int)::strspn( word, "0123456789abcdefABCDEF" ) == len
    )
        return false;

    ////////// Stop-word checks ///////////////////////////////////////////////

    if ( !is_ok_word( word ) || stop_words->contains( to_lower( word ) ) )
        return false;

    out << word << '\n';
    return true;
}

//*****************************************************************************
//
// SYNOPSIS
//
        void extract_words(
            register mmap_file::const_iterator c,
            register mmap_file::const_iterator end,
            ostream &out
        )
//
// DESCRIPTION
//
//      Extract the words between the given iterators.
//
// PARAMETERS
//
//      c       The iterator marking the beginning of the text to extract.
//
//      end     The iterator marking the end of the text to extract.
//
//      out     The ostream to write the words to.
//
//*****************************************************************************
{
    char    word[ Word_Hard_Max_Size + 1 ];
    int     len;
    int     num_words = 0;
    bool    in_word = false;

    in_postscript = false;

    while ( c != end ) {
        register char const ch = *c++;

        ////////// Collect a word /////////////////////////////////////////////

        if ( is_word_char( ch ) || ch == '%' ) {
            if ( !in_word ) {                   // start a new word
                word[ 0 ] = ch;
                len = 1;
                in_word = true;
                continue;
            }
            if ( len < Word_Hard_Max_Size ) {   // continue same word
                word[ len++ ] = ch;
                continue;
            }
            in_word = false;                    // too big: skip chars
            while ( c != end && is_word_char( *c++ ) ) ;
            continue;
        }

        if ( in_word ) {
            //
            // We ran into a non-word character, so extract the word up to, but
            // not including, it.
            //
            in_word = false;
            num_words += extract_word( word, len, out );
        }
    }
    if ( in_word ) {
        //
        // We ran into 'end' while still accumulating characters into a word,
        // so just extract what we've got.
        //
        num_words += extract_word( word, len, out );
    }

    if ( verbosity > 2 )
        cout << " (" << num_words << " words)" << endl;
}

//*****************************************************************************
//
//  Miscellaneous function(s)
//
//*****************************************************************************

ostream& usage( ostream &err ) {
    err << "usage: " << me << " [options] dir ... file ...\n"
    "options: (unambiguous abbreviations may be used for long options)\n"
    "========\n"
    "-?   | --help             : Print this help message\n"
    "-c f | --config-file f    : Name of configuration file [default: " << ConfigFile_Default << "]\n"
    "-e p | --pattern p        : Filename pattern to extract [default: none]\n"
    "-E p | --no-pattern p     : Filename pattern not to extract [default: none]\n"
    "-f   | --filter           : Filter one file to standard output [default: no]\n"
#ifndef PJL_NO_SYMBOLIC_LINKS
    "-l   | --follow-links     : Follow symbolic links [default: no]\n"
#endif
    "-r   | --no-recurse       : Don't extract subdirectories [default: do]\n"
    "-s f | --stop-file f      : Stop-word file to use instead of built-in default\n"
    "-S   | --dump-stop        : Dump stop-words, exit\n"
    "-v v | --verbosity v      : Verbosity level [0-4; default: 0]\n"
    "-V   | --version          : Print version number, exit\n"
    "-x e | --extension e      : Extension to append to filename [default: txt]\n";
    ::exit( Exit_Usage );
    return err;                                 // just to make compiler happy
}
/* vim:set et sw=4 ts=4: */