File: FileConverter.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (572 lines) | stat: -rw-r--r-- 14,070 bytes parent folder | download | duplicates (2)
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
unit FileConverter;

{(*}
(*------------------------------------------------------------------------------
 Delphi Code formatter source code

The Original Code is Converter.pas, released January 2001.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved. 
Contributor(s): Anthony Steele.

The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.

Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL") 
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}

{$I ..\Include\JcfGlobal.inc}

interface

uses
  { delphi } Classes,
  { local } Converter, 
  ConvertTypes;

{ AFS 7 July 04
  rewrote this as a wrapper for the string->string converter
  So basically it deals with file issues
  and delegates the convertion to the wrapped TConverter
}


type

  TFileConverter = class(TObject)
  private
    { the string-> string converter }
    fcConverter: TConverter;

    { state }
    fOnStatusMessage: TStatusMessageProc;
    peBackupMode: TBackupMode;
    peSourceMode: TSourceMode;

    { properties }
    fsInput: string;
    fsOriginalFileName: string;
    fsOutFileName: string;
    fbYesAll: boolean;
    fbGuiMessages: Boolean;
    fbAbort: boolean;
    fiConvertCount: integer;

    procedure SendStatusMessage(const psUnit, psMessage: string;
      const peMessageType: TStatusMessageType;
      const piY, piX: integer);

    procedure GetFileNames(const psDir: string; psFiles: TStrings);
    procedure GetDirNames(const psDir: string; psFiles: TStrings);

    function GetOnStatusMessage: TStatusMessageProc;
    procedure SetOnStatusMessage(const Value: TStatusMessageProc);
    procedure FinalSummary;

    function PreProcessChecks(const psInputFileName: string): boolean;

  protected
    function OriginalFileName: string;

    procedure ProcessDirectory(const psDir: string);

  public
    constructor Create;
    destructor Destroy; override;

    procedure ProcessFile(const psInputFileName: string);

    procedure Convert;
    procedure Clear;

    function ConvertError: Boolean;
    function TokenCount: integer;



    property BackupMode: TBackupMode Read peBackupMode Write peBackupMode;
    property SourceMode: TSourceMode Read peSourceMode Write peSourceMode;
    property Input: string Read fsInput Write fsInput;

    property YesAll: boolean read fbYesAll write fbYesAll;
    property GuiMessages: Boolean read fbGuiMessages write fbGuiMessages;

    property Abort: boolean read fbAbort write fbAbort;

    // details of the last file converted
    property OutFileName: string Read fsOutFileName;

    property OnStatusMessage: TStatusMessageProc read GetOnStatusMessage write SetOnStatusMessage;
  end;

implementation

uses
  { delphi }
  {$ifndef fpc}Windows, {$endif} SysUtils, Dialogs, Controls, Forms,
  { local }
  JcfStringUtils, JcfSystemUtils,
  JcfMiscFunctions, JcfLog,
  JcfRegistrySettings, JcfSettings, JcfUnicodeFiles;

constructor TFileConverter.Create;
begin
  inherited;
  fcConverter := TConverter.Create;
  fcConverter.OnStatusMessage := SendStatusMessage;
end;

destructor TFileConverter.Destroy;
begin
  FreeAndNil(fcConverter);
  inherited;
end;

function TFileConverter.PreProcessChecks(const psInputFileName: string): boolean;
var
  lsTemp: string;
begin
  Result := False;

  if psInputFileName = '' then
  begin
    SendStatusMessage('', 'Select a file', mtInputError, -1, -1);
    exit;
  end;

  if not FileExists(psInputFileName) then
  begin
    SendStatusMessage(psInputFileName,
      'The file "' + psInputFileName + '" does not exist',
      mtInputError, -1, -1);
    exit;
  end;

  if FileGetSize(psInputFileName) < 1 then
  begin
    SendStatusMessage(psInputFileName, 'The file "' + psInputFileName + '" is empty',
      mtInputError,
      -1, -1);
    exit;
  end;

  if (SourceMode <> fmSingleFile) then
  begin
    lsTemp := PathExtractFileNameNoExt(psInputFileName);

    if GetRegSettings.FileIsExcluded(lsTemp) then
    begin
      Log.Write('Exluded file: ' + psInputFileName);
      exit;
    end;
  end;

  { all kinds of chaos ensues if you work with readonly files,
    for e.g. you can rename them to .bak, but on the next run you will be unable to delete the old .bak files.
    They are only safe when the source is read not written, ie "output to separate file" backup mode
  }
  if (BackupMode <> cmSeparateOutput) and (FileIsReadOnly(psInputFileName)) then
  begin
    Log.WriteError('File: ' + psInputFileName + ' cannot be processed as it is read only');
    exit;
  end;

  result := True;
end;

procedure TFileConverter.ProcessFile(const psInputFileName: string);
var
  lsMessage, lsOut: string;
  wRes: word;
  lbFileIsChanged: boolean;
  lsOutType: string;
  lsSourceCode: String;
  leContentType: TFileContentType;
begin
  // do checks
  if not PreProcessChecks(psInputFileName) then
    exit;

  // notify owner
  lsMessage := 'Formatting file ' + psInputFileName;

  if GetRegSettings.LogLevel in [eLogFiles, eLogTokens] then
    Log.Write(lsMessage);
  SendStatusMessage(psInputFileName, lsMessage, mtProgress, -1, -1);

  // convert in memory
  fsOriginalFileName := psInputFileName;

  ReadTextFile(psInputFileName, lsSourceCode, leContentType);

  fcConverter.FileName := psInputFileName;
  fcConverter.InputCode := lsSourceCode;
  fcConverter.GuiMessages := GuiMessages;
  fcConverter.Convert;

  // was it converted ?
  if ConvertError then
    exit;

  Inc(fiConvertCount);

  {
   check if the file has changed.
   If not, do not write.
   This is kinder to source control systems (CVS, SVN etc.)
   that check the file timestamp
  }
  lbFileIsChanged := (fcConverter.InputCode <> fcConverter.OutputCode);

  lsOut := GetRegSettings.GetOutputFileName(psInputFileName, peBackupMode);

  // check if an output/backup file must be removed 
  if BackupMode <> cmInplace then
  begin
    if lsOut = '' then
    begin
      SendStatusMessage(psInputFileName, 'No output/backup file specified',
       mtInputError, -1, -1);
      exit;
    end;

    if lbFileIsChanged and FileExists(lsOut) then
    begin
      if YesAll then
        wRes := mrYes
      else
      begin
        if BackupMode = cmInPlaceWithBackup then
          lsOutType := 'Backup'
        else
          lsOutType := 'Output';
          
        wRes := MessageDlg(lsOutType + ' file ' + lsOut + ' exists already. Remove it?',
          mtConfirmation, [mbYes, mbNo, mbAll, mbAbort], 0);
      end;

      if wRes = mrAll then
      begin
        YesAll := True;
        wRes   := mrYes;
      end;

      if wRes = mrYes then
      begin
        if not DeleteFile(lsOut) then
          raise Exception.Create('TFileConverter.ProcessFile: ' +
            'Failed to delete ' + lsOutType + ' file ' + lsOut);
      end
      else if wRes = mrNo then
      begin
        exit;
      end
      else if wRes = mrAbort then
      begin
        fbAbort := True;
        exit;
      end;
    end;
  end;

  // now, depending on mode, write the output to new/old file 
  case BackupMode of
    cmInPlace:
    begin
      fsOutFileName := psInputFileName;

      if lbFileIsChanged then
      begin
        // delete the old one, write the new one
        DeleteFile(psInputFileName);
        WriteTextFile(psInputFileName, fcConverter.OutputCode, leContentType);
      end;
    end;

    cmInPlaceWithBackup:
    begin
      fsOutFileName := psInputFileName;

      if lbFileIsChanged then
      begin

        { rename the original file to the backup file name,
          write processed code back to the original file }
        if not RenameFile(psInputFileName, lsOut) then
        begin
          raise Exception.Create('TFileConverter.ProcessFile: ' +
          ' could not rename source file ' + psInputFileName + ' to ' + lsOut);
        end;

        WriteTextFile(psInputFileName, fcConverter.OutputCode, leContentType);
      end;
    end;

    cmSeparateOutput:
    begin
      fsOutFileName := lsOut;
      { simple. Write to a new file
        doesn't matter if it;s not changed }
      WriteTextFile(lsOut, fcConverter.OutputCode, leContentType);

    end;
    else
      Assert(False, 'Bad backup mode');
  end;

end;

procedure TFileConverter.ProcessDirectory(const psDir: string);
var
  lsMessage: string;
  lsNames:   TStringList;
  lsDir:     string;
  liLoop:    integer;
begin
  if not DirectoryExists(psDir) then
  begin
    SendStatusMessage('', 'The directory ' + psDir + ' does not exist',
      mtInputError, -1, -1);
    exit;
  end;

  if GetRegSettings.DirIsExcluded(GetLastDir(psDir)) then
  begin
    Log.Write('Exluded dir: ' + psDir);
    exit;
  end;

  lsDir := IncludeTrailingPathDelimiter(psDir);

  lsMessage := 'Processing directory ' + lsDir;
  //if Settings.Log.LogLevel in [eLogFiles, eLogTokens] then
  Log.Write(lsMessage);
  SendStatusMessage('', lsMessage, mtProgress, -1, -1);

  lsNames := TStringList.Create;
  try { finally free }
    GetFileNames(lsDir, lsNames);

    for liLoop := 0 to lsNames.Count - 1 do
    begin
      ProcessFile(lsDir + lsNames[liLoop]);
      if fbAbort then
        break;
      
      {$IFNDEF COMMAND_LINE}
      // refresh the GUI
      Application.ProcessMessages;
      {$ENDIF}
    end;

    { all subdirs }
    if SourceMode = fmDirectoryRecursive then
    begin
      lsNames.Clear;
      GetDirNames(lsDir, lsNames);

      for liLoop := 0 to lsNames.Count - 1 do
      begin
        ProcessDirectory(lsDir + lsNames[liLoop]);
        if fbAbort then
          break;
      end;
    end;

  finally
    lsNames.Free;
  end;
end;

procedure TFileConverter.GetFileNames(const psDir: string; psFiles: TStrings);
var
  rSearch: TSearchRec;
  lsName, lsExt, lsSearch: string;
  bDone:   boolean;
begin
  Assert(psDir <> '');
  Assert(psFiles <> nil);

  { for all pas files in the dir }
  {$IFDEF FPC}
  lsSearch := psDir + AllFilesMask;
  {$ELSE}
  lsSearch := psDir + '*.*';
  {$ENDIF}
  FillChar(rSearch{%H-}, Sizeof(TSearchRec), 0);
  bDone := (FindFirst(lsSearch, 0, rSearch) <> 0);

  while not bDone do
  begin
    lsName := rSearch.Name;
    Assert(lsName <> '');
    if (rSearch.Attr and faDirectory > 0) then
      continue;

    lsExt := ExtractFileExt(lsName);
    if FormattingSettings.Clarify.ExtensionIsFormatted(lsExt) then
      psFiles.Add(lsName);

    bDone := (FindNext(rSearch) <> 0);
    Assert(bDone or (rSearch.Name <> lsName));
  end;
  FindClose(rSearch);
end;

procedure TFileConverter.GetDirNames(const psDir: string; psFiles: TStrings);
var
  rSearch:  TSearchRec;
  lsSearch: string;
  bDone:    boolean;
begin
  Assert(psDir <> '');
  Assert(psFiles <> nil);

  {$IFDEF FPC}
  lsSearch := psDir + AllFilesMask;
  {$ELSE}
  lsSearch := psDir + '*.*';
  {$ENDIF}
  
  FillChar(rSearch{%H-}, Sizeof(TSearchRec), 0);
  bDone := (FindFirst(lsSearch, faDirectory, rSearch) <> 0);

  while not bDone do
  begin
    if (rSearch.Attr and faDirectory > 0) and
      (rSearch.Name <> '.') and (rSearch.Name <> '..') then
      psFiles.Add(rSearch.Name);

    bDone := (FindNext(rSearch) <> 0);
  end;
  FindClose(rSearch);
end;


procedure TFileConverter.Convert;
var
  dwStart, dwElapsed: DWord;
begin
  if GetRegSettings.LogTime then
    dwStart := GetTickCount
  else
    dwStart := 0;

  fbAbort := False;
  fiConvertCount := 0;

  { all processors must check thier inclusion settings
    as this may have changed from the UI }

  { process file(s) }
  case SourceMode of
    fmSingleFile:
      ProcessFile(Input);
    fmDirectory, fmDirectoryRecursive:
    begin
      ProcessDirectory(Input);
    end
    else
      raise Exception.Create('TConverter.Convert: Bad file recurse type');
  end;

  if GetRegSettings.LogTime then
  begin
    dwElapsed := GetTickCount - dwStart;
    Log.Write('Run took ' + FloatToStr(dwElapsed / 1000) + ' seconds')
  end;

  FinalSummary;
  Log.CloseLog;

  if GetRegSettings.ViewLogAfterRun then
    GetRegSettings.ViewLog;
end;

function TFileConverter.OriginalFileName: string;
begin
  Result := fsOriginalFileName;
end;


procedure TFileConverter.FinalSummary;
var
  lsMessage: string;
begin
  if fiConvertCount = 0 then
  begin
    if ConvertError then
      lsMessage := 'Aborted due to error'
    else
      lsMessage := 'Nothing done';
  end
  else if fbAbort then
    lsMessage := 'Aborted after ' + DescribeFileCount(fiConvertCount)
  else if fiConvertCount > 1 then
    lsMessage := 'Finished processing ' + DescribeFileCount(fiConvertCount)
  else
    lsMessage := '';

  if lsMessage <> '' then
  begin
    SendStatusMessage('', lsMessage, mtProgress, -1, -1);

    Log.EmptyLine;
    Log.Write(lsMessage);
  end;
end;

procedure TFileConverter.Clear;
begin
  fcConverter.Clear;
end;


function TFileConverter.ConvertError: Boolean;
begin
  Result := fcConverter.ConvertError;
end;


function TFileConverter.TokenCount: integer;
begin
  Result := fcConverter.TokenCount;
end;

function TFileConverter.GetOnStatusMessage: TStatusMessageProc;
begin
  Result := fOnStatusMessage;
end;

procedure TFileConverter.SetOnStatusMessage(const Value: TStatusMessageProc);
begin
  fOnStatusMessage := Value;
end;

procedure TFileConverter.SendStatusMessage(const psUnit, psMessage: string;
  const peMessageType: TStatusMessageType;
  const piY, piX: integer);
var
  lsUnit: string;
begin
  if Assigned(fOnStatusMessage) then
  begin
    lsUnit := psUnit;
    if lsUnit = '' then
      lsUnit := OriginalFileName;

    fOnStatusMessage(lsUnit, psMessage, peMessageType, piY, piX);
  end;
end;

end.