summaryrefslogblamecommitdiffstats
path: root/private/utils/find.old/find.cxx
blob: ff847b462dc3b81d5ece3e91966a9815ae12ffa2 (plain) (tree)
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


















































































































































































































































































































































































































































































































































































































































































                                                                                                                                   
/*++

Copyright (c) 1991  Microsoft Corporation

Module Name:

	find.cxx

Abstract:

	This utility allows the user to search for strings in a file
	It is functionaly compatible with DOS 5 find utility.
	
    SYNTAX (Command line)

          FIND [/?][/V][/C][/N][/I] "string" [[d:][path]filename[.ext]...]

          where:

			/? - Display this help
            /V - Display all lines NOT containing the string
            /C - Display only a count of lines containing string
            /N - Display number of line containing string
            /I - Ignore case

    UTILITY FUNCTION:

      Searches the specified file(s) looking for the string the user
      entered from the command line.  If file name(s) are specifeied,
      those names are displayed, and if the string is found, then the
      entire line containing that string will be displayed.  Optional
      parameters modify that behavior and are described above.  String
      arguments have to be enclosed in double quotes.  (Two double quotes
      if a double quote is to be included).  Only one string argument is
      presently allowed.  The maximum line size is determined by buffer
      size.  Bigger lines will bomb the program.  If no file name is given
      then it will asssume the input is coming from the standard Input.
      No errors are reported when reading from standard Input.


    EXIT:
     The program returns errorlevel:
       0 - OK, and some matches
       1 -
       2 - Some Error


Author:

	Bruce Wilson (w-wilson) 08-May-1991

Environment:

	ULIB, User Mode

Revision History:

	08-May-1991		w-wilson

		created

--*/

#include "ulib.hxx"
#include "ulibcl.hxx"
#include "error.hxx"
#include "arg.hxx"
#include "array.hxx"
#include "path.hxx"
#include "wstring.hxx"
#include "substrng.hxx"
#include "filestrm.hxx"
#include "file.hxx"
#include "system.hxx"
#include "arrayit.hxx"
#include "smsg.hxx"
#include "rtmsg.h"
#include "find.hxx"


extern "C" {
#include <stdio.h>
#include <string.h>
}

#define MAX_LINE_LEN		1024


ERRSTACK*		perrstk;
static STR		TmpBuf[MAX_LINE_LEN];

DEFINE_CONSTRUCTOR( FIND, PROGRAM );


BOOLEAN
FIND::Initialize(
	)

/*++

Routine Description:

	Initializes an FIND class.

Arguments:

	None.

Return Value:

	BOOLEAN - Indicates if the initialization succeeded.


--*/


{
	ARGUMENT_LEXEMIZER	ArgLex;
	ARRAY				LexArray;

	ARRAY				ArgumentArray;

	STRING_ARGUMENT		ProgramNameArgument;
	FLAG_ARGUMENT		FlagCaseInsensitive;
	FLAG_ARGUMENT		FlagNegativeSearch;
	FLAG_ARGUMENT		FlagCountLines;
	FLAG_ARGUMENT		FlagDisplayNumbers;
	FLAG_ARGUMENT		FlagDisplayHelp;
	FLAG_ARGUMENT		FlagInvalid;
	STRING_ARGUMENT		StringPattern;

	PROGRAM::Initialize();

	_ErrorLevel = 0;

	if( !SYSTEM::IsCorrectVersion() ) {
		DisplayMessage(MSG_FIND_INCORRECT_VERSION);
		// BUGBUG: (w-wilson) this seems stupid - shouldn't it be 1 or 2??
		_ErrorLevel = 0;
		return(FALSE);
	}

	//
	// - init the array that will contain the command-line args
	//
	if ( !ArgumentArray.Initialize() ) {
		DbgAbort( "ArgumentArray.Initialize() failed \n" );
	}

	//
	// - init the individual arguments
	//
	if( !ProgramNameArgument.Initialize("*")
		|| !FlagCaseInsensitive.Initialize( "/I" )
		|| !FlagNegativeSearch.Initialize( "/V" )
		|| !FlagCountLines.Initialize( "/C" )
		|| !FlagDisplayNumbers.Initialize( "/N" )
		|| !FlagDisplayHelp.Initialize( "/?" )
		|| !FlagInvalid.Initialize( "/*" )
		|| !StringPattern.Initialize( "\"*\"" )
        || !_PathArguments.Initialize( "*", FALSE, TRUE ) ) {

		DbgAbort( "Unable to initialize flag or string arguments \n" );
	}

	//
	// - put the arguments in the array
	//
	if( !ArgumentArray.Put( &ProgramNameArgument )
		|| !ArgumentArray.Put( &FlagCaseInsensitive )
		|| !ArgumentArray.Put( &FlagNegativeSearch )
		|| !ArgumentArray.Put( &FlagCountLines )
		|| !ArgumentArray.Put( &FlagDisplayNumbers )
		|| !ArgumentArray.Put( &FlagDisplayHelp )
		|| !ArgumentArray.Put( &FlagInvalid )
		|| !ArgumentArray.Put( &StringPattern )
		|| !ArgumentArray.Put( &_PathArguments ) ) {

		DbgAbort( "ArgumentArray.Put() failed \n" );
	}
	//
	// - init the lexemizer
	//
	if ( !LexArray.Initialize() ) {
		DbgAbort( "LexArray.Initialize() failed \n" );
    }
	if ( !ArgLex.Initialize( &LexArray ) ) {
		DbgAbort( "ArgLex.Initialize() failed \n" );
    }

	//
	// - set up the defaults
	//
	ArgLex.PutSwitches( "/" );
	ArgLex.PutStartQuotes( "\"" );
	ArgLex.PutEndQuotes( "\"" );
	ArgLex.PutSeparators( " \"" );
	ArgLex.SetCaseSensitive( FALSE );
	if( !ArgLex.PrepareToParse() ) {

		//
		// invalid format
		//
		DisplayMessage(MSG_FIND_INVALID_FORMAT);
			
		_ErrorLevel = 2;
		return( FALSE );
	}


	//
	// - now parse the command line.  The args in the array will be set
	//   if they are found on the command line.
	//
	if( !ArgLex.DoParsing( &ArgumentArray ) ) {
		if( FlagInvalid.QueryFlag() ) {
			//
			// invalid switch
			//
			DisplayMessage(MSG_FIND_INVALID_SWITCH);

        } else {
			//
            // invalid format
			//
			DisplayMessage(MSG_FIND_INVALID_FORMAT);
		}
		_ErrorLevel = 2;
		return( FALSE );
    } else if ( _PathArguments.WildCardExpansionFailed() ) {

        //
        //  No files matched
        //
        DisplayMessage(MSG_FIND_FILE_NOT_FOUND, ERROR_MESSAGE, "%W", _PathArguments.GetLexemeThatFailed() );

        _ErrorLevel = 2;
        return( FALSE );

    } else {

//		DbgPrint( "\nargs parsed ok\n" );
	}
	
	if( FlagInvalid.QueryFlag() ) {
		//
		// invalid switch
		//
		DisplayMessage(MSG_FIND_INVALID_SWITCH, ERROR_MESSAGE );
		_ErrorLevel = 2;
		return( FALSE );
	}

	//
	// - now do semantic checking/processing
	//    - if they ask for help, do it right away and return
	//    - set flags
	//
	if( FlagDisplayHelp.QueryFlag() ) {
		DisplayMessage(MSG_FIND_USAGE);
		_ErrorLevel = 0;
		return( FALSE );
	}

	if( !StringPattern.IsValueSet() ) {
		DisplayMessage(MSG_FIND_INVALID_FORMAT);
		_ErrorLevel = 2;
		return( FALSE );
	} else {
		//
		// - keep a copy of the pattern string
		//
		
		DbgAssert(StringPattern.GetString());
		_PatternString = *StringPattern.GetString();

		_PatternString.QuerySTR( 0, TO_END,  TmpBuf, sizeof( TmpBuf ));
//		DbgPrint("pattern is ");
//		DbgPrint(TmpBuf);
//		DbgPrint("\n");
	}

	_CaseSensitive = (BOOLEAN)!FlagCaseInsensitive.QueryFlag();

	_LinesContainingPattern = (BOOLEAN)!FlagNegativeSearch.QueryFlag();

	_OutputLines = (BOOLEAN)!FlagCountLines.QueryFlag();

	_OutputLineNumbers = (BOOLEAN)FlagDisplayNumbers.QueryFlag();

	DbgAssert(sprintf(TmpBuf,
			"flags:caseSens %1d, +veSrch %1d, outLines %1d, line#'s %1d\n",
			_CaseSensitive, _LinesContainingPattern, _OutputLines,
			_OutputLineNumbers) > 0);
//	DbgPrint(TmpBuf);

    return( TRUE );
}



BOOLEAN
FIND::IsDos5CompatibleFileName(
	IN PCPATH	Path
	)
/*++

Routine Description:

	Parses the path string and returns FALSE if DOS5 would reject
	the path.

Arguments:

	Path	-	Supplies the path

Return Value:

	BOOLEAN -	Returns FALSE if DOS5 would reject the path,
				TRUE otherwise

--*/

{

	PWSTRING	String;

	DbgPtrAssert( Path );

	String = (PWSTRING)Path->GetPathString();

	DbgPtrAssert( String );

	if ( String->QueryChCount() > 0 ) {

		if ( String->QueryChAt(0) == '\"' ) {
			return FALSE;
		}
	}

	return TRUE;

}



ULONG
FIND::SearchStream(
	PSTREAM			StreamToSearch
	)

/*++

Routine Description:

	Does the search on an open file_stream.

Arguments:

	None.

Return Value:

	Number of lines found/not found.


--*/

{
	ULONG		LineCount;
	ULONG		FoundCount;
	CHNUM		PatternLen;
	CHNUM		PositionInLine;
	CHNUM		LastPosInLine;
	WSTRING		CurrentLine;
	WSTRING		Delim;
	USHORT		CompareFlags;
	WCHAR		Wchar;
    BOOLEAN     Found;

	LineCount = FoundCount = 0;
	PatternLen = _PatternString.QueryChCount();
	if( !Delim.Initialize( "\r\n" ) ) {
		DbgAbort( "Delim.Initialize() failed \n" );
	}
	if( !CurrentLine.Initialize("") ) {
		DbgAbort( "CurrentLine.Initialize() failed \n" );
    }
	CompareFlags = (_CaseSensitive) ? 0 : CF_IGNORECASE;

	//
	//    - for each line from stream
	//       - do strstr to see if pattern string is in line
	//       - if -ve search and not in line || +ve search and in line
	//          - output line and number or inc counter appropriately
	//
//	DbgPrint("searching stream\n");
	while( !StreamToSearch->IsAtEnd() ) {

		//
		// BUGBUG: the following can be replaced with ReadLine() when
		//         it's ready
		//
        //if( !StreamToSearch->ReadString(&CurrentLine, &Delim) ) {
        //    DbgAbort( "ReadString() failed \n" );
        //}
        //if( !StreamToSearch->IsAtEnd() ) {
        //    if( !StreamToSearch->ReadChar( &Wchar ) ) {
        //        DbgAbort( "ReadChar() failed \n" );
        //    }
        //    if( Wchar == ( WCHAR )'\r' ) {
        //        if( !StreamToSearch->IsAtEnd() ) {
        //            if( !StreamToSearch->ReadChar( &Wchar ) ) {
        //                DbgAbort( "ReadChar() failed \n" );
        //            }
        //        }
        //    }
        //}

        if ( !StreamToSearch->ReadLine( &CurrentLine ) ) {
            DbgAbort( "ReadLine failed\n" );
        }

        LineCount++;
//		DbgPrint(".");

		//
		//	- look for pattern string in the current line
		//		- note: a 0-length pattern ("") never matches a line.
		//		  A 0-length pattern can produce output with the /v
		//		  switch.
		//	- start at the end (saves a var)
		//
		
        Found = FALSE;

        if( PatternLen && CurrentLine.QueryChCount() >= PatternLen ) {

            LastPosInLine = CurrentLine.QueryChCount() - PatternLen;

            for( PositionInLine = 0;
                 PositionInLine <= LastPosInLine; PositionInLine++ ) {

                if( CurrentLine.StringCompare(PositionInLine, PatternLen,
                                              &_PatternString, 0, PatternLen,
                                              CompareFlags) == 0 ) {
                    //
                    // found a match so exit loop
                    //
                    Found = TRUE;
                    break;
                }
            }
		}
	
		//
		// - if either (search is +ve and found a match)
		//          or (search is -ve and no match found)
		//   then print line/line number based on options
		//
		if( (_LinesContainingPattern && Found)
			|| (!_LinesContainingPattern && !Found) ) {

			FoundCount++;
			if( _OutputLines ) {
				if( _OutputLineNumbers ) {
					DisplayMessage( MSG_FIND_LINE_AND_NUMBER, NORMAL_MESSAGE, "%d%W", LineCount, &CurrentLine);
				} else {
					DisplayMessage( MSG_FIND_LINEONLY, NORMAL_MESSAGE, "%W", &CurrentLine);
				}
			}
		}
	}
//	DbgPrint("\n");
	return(FoundCount);
}



VOID
FIND::SearchFiles(
	)

/*++

Routine Description:

	Does the search on the files specified on the command line.

Arguments:

	None.

Return Value:

	None.


--*/

{
//	STR				nameBuf[ MAX_PATH ];
	PARRAY			PathArray;
	PARRAY_ITERATOR	PIterator;
	PPATH			CurrentPath;
	PFSN_FILE		CurrentFSNode   = NULL;
	PFSN_DIRECTORY	CurrentFSDir;
	PFILE_STREAM	CurrentFile     = NULL;
	WSTRING			CurrentPathString;
	ULONG			LinesFound;
	

	if( !_PathArguments.IsValueSet() ) {
//		DbgPrint( "no paths specified\n" );
	} else {
//		DbgPrint( "paths specified\n" );
	}

	//
	// - if 0 paths on cmdline then open stdin
	// - if more than one path set OutputName flag
	//
    if( (_PathArguments.QueryPathCount() == 0) ) {
//		DbgPrint("PathCount == 0 so searching stdin\n");
		// use stdin
		LinesFound = SearchStream( Get_Standard_Input_Stream() );
		if( !_OutputLines ) {
			DisplayMessage(MSG_FIND_COUNT, NORMAL_MESSAGE, "%d", LinesFound);
		}
		return;
	}

	PathArray = _PathArguments.GetPathArray();
	PIterator = (PARRAY_ITERATOR)PathArray->QueryIterator();

	//
	// - for each path specified on the command line
	//    - open a stream for the path
	//    - print filename if supposed to
	//    - call SearchStream
	//
	while( (CurrentPath = (PPATH)PIterator->GetNext()) != NULL ) {
		CurrentPathString.Initialize( CurrentPath->GetPathString() );
		CurrentPathString.Strupr();

//			->QuerySTR( 0,	TO_END, nameBuf, sizeof(nameBuf));
//		DbgAssert(sprintf(TmpBuf, "path is <%s>\n", nameBuf) > 0);
//		DbgPrint(TmpBuf);

		// if the system object can return a FSN_DIRECTORY for this
		// path then the user is trying to 'find' on a dir so print
		// access denied and skip this file
		
		if( CurrentFSDir = SYSTEM::QueryDirectory(CurrentPath) ) {

			if (CurrentPath->IsDrive()) {

				DisplayMessage(MSG_FIND_FILE_NOT_FOUND, ERROR_MESSAGE, "%W", &CurrentPathString);

			} else {

				DisplayMessage( MSG_ACCESS_DENIED, ERROR_MESSAGE, "%W", &CurrentPathString);

			}
			
			DELETE( CurrentFSDir );
			continue;
		}


		if( !(CurrentFSNode = SYSTEM::QueryFile(CurrentPath)) ||
			!(CurrentFile = CurrentFSNode->QueryStream(READ_ACCESS)) ) {

			//
			//	If the file name is "", DOS5 prints an invalid parameter
			//	format message.  There is no clean way to filter this
			//	kind of stuff in the ULIB library, so we will have to
			//	parse the path ourselves.
			//
			if ( IsDos5CompatibleFileName( CurrentPath ) ) {
				DisplayMessage(MSG_FIND_FILE_NOT_FOUND, ERROR_MESSAGE, "%W", &CurrentPathString);
			} else {
				DisplayMessage(MSG_FIND_INVALID_FORMAT, ERROR_MESSAGE );
                break;
			}
			DELETE( CurrentFile );
            DELETE( CurrentFSNode );
            CurrentFile     =   NULL;
            CurrentFSNode   =   NULL;
			continue;
		}


		if( _OutputLines ) {
			DisplayMessage( MSG_FIND_BANNER, NORMAL_MESSAGE, "%W", &CurrentPathString);
		}

		LinesFound = SearchStream( CurrentFile );

		if( !_OutputLines ) {
			DisplayMessage(MSG_FIND_COUNT_BANNER, NORMAL_MESSAGE, "%W%d", &CurrentPathString, LinesFound);
		}

		DELETE( CurrentFSNode );
		DELETE( CurrentFile );
        CurrentFSNode   = NULL;
        CurrentFile     = NULL;
	}

	return;
}



VOID
FIND::Terminate(
	)

/*++

Routine Description:

	Deletes objects created during initialization.

Arguments:

	None.

Return Value:

	None.


--*/

{
	exit(_ErrorLevel);
}



VOID
main()

{
    DEFINE_CLASS_DESCRIPTOR( FIND );

	{
		FIND	Find;

		perrstk = NEW ERRSTACK;

		if( Find.Initialize() ) {
	//		DbgPrint("done init\n" );
			Find.SearchFiles();
		}
		Find.Terminate();
	}
}