VirtualBox

source: vbox/trunk/src/bldprogs/scm.cpp@ 26557

Last change on this file since 26557 was 26557, checked in by vboxsync, 15 years ago

scm: Added an option for correcting the svn:eol-style property.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 133.7 KB
Line 
1/* $Id: scm.cpp 26557 2010-02-16 00:02:37Z vboxsync $ */
2/** @file
3 * IPRT Testcase / Tool - Source Code Massager.
4 */
5
6/*
7 * Copyright (C) 2010 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31/*******************************************************************************
32* Header Files *
33*******************************************************************************/
34#include <iprt/assert.h>
35#include <iprt/ctype.h>
36#include <iprt/dir.h>
37#include <iprt/env.h>
38#include <iprt/file.h>
39#include <iprt/err.h>
40#include <iprt/getopt.h>
41#include <iprt/initterm.h>
42#include <iprt/mem.h>
43#include <iprt/message.h>
44#include <iprt/param.h>
45#include <iprt/path.h>
46#include <iprt/process.h>
47#include <iprt/stream.h>
48#include <iprt/string.h>
49
50
51/*******************************************************************************
52* Defined Constants And Macros *
53*******************************************************************************/
54/** The name of the settings files. */
55#define SCM_SETTINGS_FILENAME ".scm-settings"
56
57
58/*******************************************************************************
59* Structures and Typedefs *
60*******************************************************************************/
61/** Pointer to const massager settings. */
62typedef struct SCMSETTINGSBASE const *PCSCMSETTINGSBASE;
63
64/** End of line marker type. */
65typedef enum SCMEOL
66{
67 SCMEOL_NONE = 0,
68 SCMEOL_LF = 1,
69 SCMEOL_CRLF = 2
70} SCMEOL;
71/** Pointer to an end of line marker type. */
72typedef SCMEOL *PSCMEOL;
73
74/**
75 * Line record.
76 */
77typedef struct SCMSTREAMLINE
78{
79 /** The offset of the line. */
80 size_t off;
81 /** The line length, excluding the LF character.
82 * @todo This could be derived from the offset of the next line if that wasn't
83 * so tedious. */
84 size_t cch;
85 /** The end of line marker type. */
86 SCMEOL enmEol;
87} SCMSTREAMLINE;
88/** Pointer to a line record. */
89typedef SCMSTREAMLINE *PSCMSTREAMLINE;
90
91/**
92 * Source code massager stream.
93 */
94typedef struct SCMSTREAM
95{
96 /** Pointer to the file memory. */
97 char *pch;
98 /** The current stream position. */
99 size_t off;
100 /** The current stream size. */
101 size_t cb;
102 /** The size of the memory pb points to. */
103 size_t cbAllocated;
104
105 /** Line records. */
106 PSCMSTREAMLINE paLines;
107 /** The current line. */
108 size_t iLine;
109 /** The current stream size given in lines. */
110 size_t cLines;
111 /** The sizeof the the memory backing paLines. */
112 size_t cLinesAllocated;
113
114 /** Set if write-only, clear if read-only. */
115 bool fWriteOrRead;
116 /** Set if the memory pb points to is from RTFileReadAll. */
117 bool fFileMemory;
118 /** Set if fully broken into lines. */
119 bool fFullyLineated;
120
121 /** Stream status code (IPRT). */
122 int rc;
123} SCMSTREAM;
124/** Pointer to a SCM stream. */
125typedef SCMSTREAM *PSCMSTREAM;
126/** Pointer to a const SCM stream. */
127typedef SCMSTREAM const *PCSCMSTREAM;
128
129
130/**
131 * SVN property.
132 */
133typedef struct SCMSVNPROP
134{
135 /** The property. */
136 char *pszName;
137 /** The value.
138 * When used to record updates, this can be set to NULL to trigger the
139 * deletion of the property. */
140 char *pszValue;
141} SCMSVNPROP;
142/** Pointer to a SVN property. */
143typedef SCMSVNPROP *PSCMSVNPROP;
144/** Pointer to a const SVN property. */
145typedef SCMSVNPROP const *PCSCMSVNPROP;
146
147
148/**
149 * Rewriter state.
150 */
151typedef struct SCMRWSTATE
152{
153 /** The filename. */
154 const char *pszFilename;
155 /** Set after the printing the first verbose message about a file under
156 * rewrite. */
157 bool fFirst;
158 /** The number of SVN property changes. */
159 size_t cSvnPropChanges;
160 /** Pointer to an array of SVN property changes. */
161 PSCMSVNPROP paSvnPropChanges;
162} SCMRWSTATE;
163/** Pointer to the rewriter state. */
164typedef SCMRWSTATE *PSCMRWSTATE;
165
166/**
167 * A rewriter.
168 *
169 * This works like a stream editor, reading @a pIn, modifying it and writing it
170 * to @a pOut.
171 *
172 * @returns true if any changes were made, false if not.
173 * @param pIn The input stream.
174 * @param pOut The output stream.
175 * @param pSettings The settings.
176 */
177typedef bool (*PFNSCMREWRITER)(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
178
179
180/**
181 * Configuration entry.
182 */
183typedef struct SCMCFGENTRY
184{
185 /** Number of rewriters. */
186 size_t cRewriters;
187 /** Pointer to an array of rewriters. */
188 PFNSCMREWRITER const *papfnRewriter;
189 /** File pattern (simple). */
190 const char *pszFilePattern;
191} SCMCFGENTRY;
192typedef SCMCFGENTRY *PSCMCFGENTRY;
193typedef SCMCFGENTRY const *PCSCMCFGENTRY;
194
195
196/**
197 * Diff state.
198 */
199typedef struct SCMDIFFSTATE
200{
201 size_t cDiffs;
202 const char *pszFilename;
203
204 PSCMSTREAM pLeft;
205 PSCMSTREAM pRight;
206
207 /** Whether to ignore end of line markers when diffing. */
208 bool fIgnoreEol;
209 /** Whether to ignore trailing whitespace. */
210 bool fIgnoreTrailingWhite;
211 /** Whether to ignore leading whitespace. */
212 bool fIgnoreLeadingWhite;
213 /** Whether to print special characters in human readable form or not. */
214 bool fSpecialChars;
215 /** The tab size. */
216 size_t cchTab;
217 /** Where to push the diff. */
218 PRTSTREAM pDiff;
219} SCMDIFFSTATE;
220/** Pointer to a diff state. */
221typedef SCMDIFFSTATE *PSCMDIFFSTATE;
222
223/**
224 * Source Code Massager Settings.
225 */
226typedef struct SCMSETTINGSBASE
227{
228 bool fConvertEol;
229 bool fConvertTabs;
230 bool fForceFinalEol;
231 bool fForceTrailingLine;
232 bool fStripTrailingBlanks;
233 bool fStripTrailingLines;
234 /** Only process files that are part of a SVN working copy. */
235 bool fOnlySvnFiles;
236 /** Only recurse into directories containing an .svn dir. */
237 bool fOnlySvnDirs;
238 /** Set svn:eol-style if missing or incorrect. */
239 bool fSetSvnEol;
240 /** */
241 unsigned cchTab;
242 /** Only consider files matcihng these patterns. This is only applied to the
243 * base names. */
244 char *pszFilterFiles;
245 /** Filter out files matching the following patterns. This is applied to base
246 * names as well as the aboslute paths. */
247 char *pszFilterOutFiles;
248 /** Filter out directories matching the following patterns. This is applied
249 * to base names as well as the aboslute paths. All absolute paths ends with a
250 * slash and dot ("/."). */
251 char *pszFilterOutDirs;
252} SCMSETTINGSBASE;
253/** Pointer to massager settings. */
254typedef SCMSETTINGSBASE *PSCMSETTINGSBASE;
255
256/**
257 * Option identifiers.
258 *
259 * @note The first chunk, down to SCMOPT_TAB_SIZE, are alternately set &
260 * clear. So, the option setting a flag (boolean) will have an even
261 * number and the one clearing it will have an odd number.
262 * @note Down to SCMOPT_LAST_SETTINGS corresponds exactly to SCMSETTINGSBASE.
263 */
264typedef enum SCMOPT
265{
266 SCMOPT_CONVERT_EOL = 10000,
267 SCMOPT_NO_CONVERT_EOL,
268 SCMOPT_CONVERT_TABS,
269 SCMOPT_NO_CONVERT_TABS,
270 SCMOPT_FORCE_FINAL_EOL,
271 SCMOPT_NO_FORCE_FINAL_EOL,
272 SCMOPT_FORCE_TRAILING_LINE,
273 SCMOPT_NO_FORCE_TRAILING_LINE,
274 SCMOPT_STRIP_TRAILING_BLANKS,
275 SCMOPT_NO_STRIP_TRAILING_BLANKS,
276 SCMOPT_STRIP_TRAILING_LINES,
277 SCMOPT_NO_STRIP_TRAILING_LINES,
278 SCMOPT_ONLY_SVN_DIRS,
279 SCMOPT_NOT_ONLY_SVN_DIRS,
280 SCMOPT_ONLY_SVN_FILES,
281 SCMOPT_NOT_ONLY_SVN_FILES,
282 SCMOPT_SET_SVN_EOL,
283 SCMOPT_DONT_SET_SVN_EOL,
284 SCMOPT_TAB_SIZE,
285 SCMOPT_FILTER_OUT_DIRS,
286 SCMOPT_FILTER_FILES,
287 SCMOPT_FILTER_OUT_FILES,
288 SCMOPT_LAST_SETTINGS = SCMOPT_FILTER_OUT_FILES,
289 //
290 SCMOPT_DIFF_IGNORE_EOL,
291 SCMOPT_DIFF_NO_IGNORE_EOL,
292 SCMOPT_DIFF_IGNORE_SPACE,
293 SCMOPT_DIFF_NO_IGNORE_SPACE,
294 SCMOPT_DIFF_IGNORE_LEADING_SPACE,
295 SCMOPT_DIFF_NO_IGNORE_LEADING_SPACE,
296 SCMOPT_DIFF_IGNORE_TRAILING_SPACE,
297 SCMOPT_DIFF_NO_IGNORE_TRAILING_SPACE,
298 SCMOPT_DIFF_SPECIAL_CHARS,
299 SCMOPT_DIFF_NO_SPECIAL_CHARS,
300 SCMOPT_END
301} SCMOPT;
302
303
304/**
305 * File/dir pattern + options.
306 */
307typedef struct SCMPATRNOPTPAIR
308{
309 char *pszPattern;
310 char *pszOptions;
311} SCMPATRNOPTPAIR;
312/** Pointer to a pattern + option pair. */
313typedef SCMPATRNOPTPAIR *PSCMPATRNOPTPAIR;
314
315
316/** Pointer to a settings set. */
317typedef struct SCMSETTINGS *PSCMSETTINGS;
318/**
319 * Settings set.
320 *
321 * This structure is constructed from the command line arguments or any
322 * .scm-settings file found in a directory we recurse into. When recusing in
323 * and out of a directory, we push and pop a settings set for it.
324 *
325 * The .scm-settings file has two kinds of setttings, first there are the
326 * unqualified base settings and then there are the settings which applies to a
327 * set of files or directories. The former are lines with command line options.
328 * For the latter, the options are preceeded by a string pattern and a colon.
329 * The pattern specifies which files (and/or directories) the options applies
330 * to.
331 *
332 * We parse the base options into the Base member and put the others into the
333 * paPairs array.
334 */
335typedef struct SCMSETTINGS
336{
337 /** Pointer to the setting file below us in the stack. */
338 PSCMSETTINGS pDown;
339 /** Pointer to the setting file above us in the stack. */
340 PSCMSETTINGS pUp;
341 /** File/dir patterns and their options. */
342 PSCMPATRNOPTPAIR paPairs;
343 /** The number of entires in paPairs. */
344 uint32_t cPairs;
345 /** The base settings that was read out of the file. */
346 SCMSETTINGSBASE Base;
347} SCMSETTINGS;
348/** Pointer to a const settings set. */
349typedef SCMSETTINGS const *PCSCMSETTINGS;
350
351
352/*******************************************************************************
353* Internal Functions *
354*******************************************************************************/
355static bool rewrite_StripTrailingBlanks(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
356static bool rewrite_ExpandTabs(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
357static bool rewrite_ForceNativeEol(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
358static bool rewrite_ForceLF(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
359static bool rewrite_ForceCRLF(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
360static bool rewrite_AdjustTrailingLines(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
361static bool rewrite_Makefile_kup(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
362static bool rewrite_Makefile_kmk(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
363static bool rewrite_C_and_CPP(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings);
364
365
366/*******************************************************************************
367* Global Variables *
368*******************************************************************************/
369static const char g_szProgName[] = "scm";
370static const char *g_pszChangedSuff = "";
371static const char g_szTabSpaces[16+1] = " ";
372static bool g_fDryRun = true;
373static bool g_fDiffSpecialChars = true;
374static bool g_fDiffIgnoreEol = false;
375static bool g_fDiffIgnoreLeadingWS = false;
376static bool g_fDiffIgnoreTrailingWS = false;
377static int g_iVerbosity = 2;//99; //0;
378
379/** The global settings. */
380static SCMSETTINGSBASE const g_Defaults =
381{
382 /* .fConvertEol = */ true,
383 /* .fConvertTabs = */ true,
384 /* .fForceFinalEol = */ true,
385 /* .fForceTrailingLine = */ false,
386 /* .fStripTrailingBlanks = */ true,
387 /* .fStripTrailingLines = */ true,
388 /* .fOnlySvnFiles = */ false,
389 /* .fOnlySvnDirs = */ false,
390 /* .fSetSvnEol = */ false,
391 /* .cchTab = */ 8,
392 /* .pszFilterFiles = */ (char *)"",
393 /* .pszFilterOutFiles = */ (char *)"*.exe|*.com|20*-*-*.log",
394 /* .pszFilterOutDirs = */ (char *)".svn|.hg|.git|CVS",
395};
396
397/** Option definitions for the base settings. */
398static RTGETOPTDEF g_aScmOpts[] =
399{
400 { "--convert-eol", SCMOPT_CONVERT_EOL, RTGETOPT_REQ_NOTHING },
401 { "--no-convert-eol", SCMOPT_NO_CONVERT_EOL, RTGETOPT_REQ_NOTHING },
402 { "--convert-tabs", SCMOPT_CONVERT_TABS, RTGETOPT_REQ_NOTHING },
403 { "--no-convert-tabs", SCMOPT_NO_CONVERT_TABS, RTGETOPT_REQ_NOTHING },
404 { "--force-final-eol", SCMOPT_FORCE_FINAL_EOL, RTGETOPT_REQ_NOTHING },
405 { "--no-force-final-eol", SCMOPT_NO_FORCE_FINAL_EOL, RTGETOPT_REQ_NOTHING },
406 { "--force-trailing-line", SCMOPT_FORCE_TRAILING_LINE, RTGETOPT_REQ_NOTHING },
407 { "--no-force-trailing-line", SCMOPT_NO_FORCE_TRAILING_LINE, RTGETOPT_REQ_NOTHING },
408 { "--strip-trailing-blanks", SCMOPT_STRIP_TRAILING_BLANKS, RTGETOPT_REQ_NOTHING },
409 { "--no-strip-trailing-blanks", SCMOPT_NO_STRIP_TRAILING_BLANKS, RTGETOPT_REQ_NOTHING },
410 { "--strip-trailing-lines", SCMOPT_STRIP_TRAILING_LINES, RTGETOPT_REQ_NOTHING },
411 { "--strip-no-trailing-lines", SCMOPT_NO_STRIP_TRAILING_LINES, RTGETOPT_REQ_NOTHING },
412 { "--only-svn-dirs", SCMOPT_ONLY_SVN_DIRS, RTGETOPT_REQ_NOTHING },
413 { "--not-only-svn-dirs", SCMOPT_NOT_ONLY_SVN_DIRS, RTGETOPT_REQ_NOTHING },
414 { "--only-svn-files", SCMOPT_ONLY_SVN_FILES, RTGETOPT_REQ_NOTHING },
415 { "--not-only-svn-files", SCMOPT_NOT_ONLY_SVN_FILES, RTGETOPT_REQ_NOTHING },
416 { "--set-svn-eol", SCMOPT_SET_SVN_EOL, RTGETOPT_REQ_NOTHING },
417 { "--dont-set-svn-eol", SCMOPT_DONT_SET_SVN_EOL, RTGETOPT_REQ_NOTHING },
418 { "--tab-size", SCMOPT_TAB_SIZE, RTGETOPT_REQ_UINT8 },
419 { "--filter-out-dirs", SCMOPT_FILTER_OUT_DIRS, RTGETOPT_REQ_STRING },
420 { "--filter-files", SCMOPT_FILTER_FILES, RTGETOPT_REQ_STRING },
421 { "--filter-out-files", SCMOPT_FILTER_OUT_FILES, RTGETOPT_REQ_STRING },
422};
423
424/** Consider files matching the following patterns (base names only). */
425static const char *g_pszFileFilter = NULL;
426
427static PFNSCMREWRITER const g_aRewritersFor_Makefile_kup[] =
428{
429 rewrite_Makefile_kup
430};
431
432static PFNSCMREWRITER const g_aRewritersFor_Makefile_kmk[] =
433{
434 rewrite_ForceNativeEol,
435 rewrite_StripTrailingBlanks,
436 rewrite_AdjustTrailingLines,
437 rewrite_Makefile_kmk
438};
439
440static PFNSCMREWRITER const g_aRewritersFor_C_and_CPP[] =
441{
442 rewrite_ForceNativeEol,
443 rewrite_ExpandTabs,
444 rewrite_StripTrailingBlanks,
445 rewrite_AdjustTrailingLines,
446 rewrite_C_and_CPP
447};
448
449static PFNSCMREWRITER const g_aRewritersFor_RC[] =
450{
451 rewrite_ForceNativeEol,
452 rewrite_ExpandTabs,
453 rewrite_StripTrailingBlanks,
454 rewrite_AdjustTrailingLines
455};
456
457static PFNSCMREWRITER const g_aRewritersFor_ShellScripts[] =
458{
459 rewrite_ForceLF,
460 rewrite_ExpandTabs,
461 rewrite_StripTrailingBlanks
462};
463
464static PFNSCMREWRITER const g_aRewritersFor_BatchFiles[] =
465{
466 rewrite_ForceCRLF,
467 rewrite_ExpandTabs,
468 rewrite_StripTrailingBlanks
469};
470
471static SCMCFGENTRY const g_aConfigs[] =
472{
473 { RT_ELEMENTS(g_aRewritersFor_Makefile_kup), &g_aRewritersFor_Makefile_kup[0], "Makefile.kup" },
474 { RT_ELEMENTS(g_aRewritersFor_Makefile_kmk), &g_aRewritersFor_Makefile_kmk[0], "Makefile.kmk" },
475 { RT_ELEMENTS(g_aRewritersFor_C_and_CPP), &g_aRewritersFor_C_and_CPP[0], "*.c|*.h|*.cpp|*.hpp|*.C|*.CPP|*.cxx|*.cc" },
476 { RT_ELEMENTS(g_aRewritersFor_RC), &g_aRewritersFor_RC[0], "*.rc" },
477 { RT_ELEMENTS(g_aRewritersFor_ShellScripts), &g_aRewritersFor_ShellScripts[0], "*.sh|configure" },
478 { RT_ELEMENTS(g_aRewritersFor_BatchFiles), &g_aRewritersFor_BatchFiles[0], "*.bat|*.cmd|*.btm|*.vbs|*.ps1" },
479};
480
481
482/* -=-=-=-=-=- memory streams -=-=-=-=-=- */
483
484
485/**
486 * Initializes the stream structure.
487 *
488 * @param pStream The stream structure.
489 * @param fWriteOrRead The value of the fWriteOrRead stream member.
490 */
491static void scmStreamInitInternal(PSCMSTREAM pStream, bool fWriteOrRead)
492{
493 pStream->pch = NULL;
494 pStream->off = 0;
495 pStream->cb = 0;
496 pStream->cbAllocated = 0;
497
498 pStream->paLines = NULL;
499 pStream->iLine = 0;
500 pStream->cLines = 0;
501 pStream->cLinesAllocated = 0;
502
503 pStream->fWriteOrRead = fWriteOrRead;
504 pStream->fFileMemory = false;
505 pStream->fFullyLineated = false;
506
507 pStream->rc = VINF_SUCCESS;
508}
509
510/**
511 * Initialize an input stream.
512 *
513 * @returns IPRT status code.
514 * @param pStream The stream to initialize.
515 * @param pszFilename The file to take the stream content from.
516 */
517int ScmStreamInitForReading(PSCMSTREAM pStream, const char *pszFilename)
518{
519 scmStreamInitInternal(pStream, false /*fWriteOrRead*/);
520
521 void *pvFile;
522 size_t cbFile;
523 int rc = pStream->rc = RTFileReadAll(pszFilename, &pvFile, &cbFile);
524 if (RT_SUCCESS(rc))
525 {
526 pStream->pch = (char *)pvFile;
527 pStream->cb = cbFile;
528 pStream->cbAllocated = cbFile;
529 pStream->fFileMemory = true;
530 }
531 return rc;
532}
533
534/**
535 * Initialize an output stream.
536 *
537 * @returns IPRT status code
538 * @param pStream The stream to initialize.
539 * @param pRelatedStream Pointer to a related stream. NULL is fine.
540 */
541int ScmStreamInitForWriting(PSCMSTREAM pStream, PCSCMSTREAM pRelatedStream)
542{
543 scmStreamInitInternal(pStream, true /*fWriteOrRead*/);
544
545 /* allocate stuff */
546 size_t cbEstimate = pRelatedStream
547 ? pRelatedStream->cb + pRelatedStream->cb / 10
548 : _64K;
549 cbEstimate = RT_ALIGN(cbEstimate, _4K);
550 pStream->pch = (char *)RTMemAlloc(cbEstimate);
551 if (pStream->pch)
552 {
553 size_t cLinesEstimate = pRelatedStream && pRelatedStream->fFullyLineated
554 ? pRelatedStream->cLines + pRelatedStream->cLines / 10
555 : cbEstimate / 24;
556 cLinesEstimate = RT_ALIGN(cLinesEstimate, 512);
557 pStream->paLines = (PSCMSTREAMLINE)RTMemAlloc(cLinesEstimate * sizeof(SCMSTREAMLINE));
558 if (pStream->paLines)
559 {
560 pStream->paLines[0].off = 0;
561 pStream->paLines[0].cch = 0;
562 pStream->paLines[0].enmEol = SCMEOL_NONE;
563 pStream->cbAllocated = cbEstimate;
564 pStream->cLinesAllocated = cLinesEstimate;
565 return VINF_SUCCESS;
566 }
567
568 RTMemFree(pStream->pch);
569 pStream->pch = NULL;
570 }
571 return pStream->rc = VERR_NO_MEMORY;
572}
573
574/**
575 * Frees the resources associated with the stream.
576 *
577 * Nothing is happens to whatever the stream was initialized from or dumped to.
578 *
579 * @param pStream The stream to delete.
580 */
581void ScmStreamDelete(PSCMSTREAM pStream)
582{
583 if (pStream->pch)
584 {
585 if (pStream->fFileMemory)
586 RTFileReadAllFree(pStream->pch, pStream->cbAllocated);
587 else
588 RTMemFree(pStream->pch);
589 pStream->pch = NULL;
590 }
591 pStream->cbAllocated = 0;
592
593 if (pStream->paLines)
594 {
595 RTMemFree(pStream->paLines);
596 pStream->paLines = NULL;
597 }
598 pStream->cLinesAllocated = 0;
599}
600
601/**
602 * Get the stream status code.
603 *
604 * @returns IPRT status code.
605 * @param pStream The stream.
606 */
607int ScmStreamGetStatus(PCSCMSTREAM pStream)
608{
609 return pStream->rc;
610}
611
612/**
613 * Grows the buffer of a write stream.
614 *
615 * @returns IPRT status code.
616 * @param pStream The stream. Must be in write mode.
617 * @param cbAppending The minimum number of bytes to grow the buffer
618 * with.
619 */
620static int scmStreamGrowBuffer(PSCMSTREAM pStream, size_t cbAppending)
621{
622 size_t cbAllocated = pStream->cbAllocated;
623 cbAllocated += RT_MAX(0x1000 + cbAppending, cbAllocated);
624 cbAllocated = RT_ALIGN(cbAllocated, 0x1000);
625 void *pvNew;
626 if (!pStream->fFileMemory)
627 {
628 pvNew = RTMemRealloc(pStream->pch, cbAllocated);
629 if (!pvNew)
630 return pStream->rc = VERR_NO_MEMORY;
631 }
632 else
633 {
634 pvNew = RTMemDupEx(pStream->pch, pStream->off, cbAllocated - pStream->off);
635 if (!pvNew)
636 return pStream->rc = VERR_NO_MEMORY;
637 RTFileReadAllFree(pStream->pch, pStream->cbAllocated);
638 pStream->fFileMemory = false;
639 }
640 pStream->pch = (char *)pvNew;
641 pStream->cbAllocated = cbAllocated;
642
643 return VINF_SUCCESS;
644}
645
646/**
647 * Grows the line array of a stream.
648 *
649 * @returns IPRT status code.
650 * @param pStream The stream.
651 * @param iMinLine Minimum line number.
652 */
653static int scmStreamGrowLines(PSCMSTREAM pStream, size_t iMinLine)
654{
655 size_t cLinesAllocated = pStream->cLinesAllocated;
656 cLinesAllocated += RT_MAX(512 + iMinLine, cLinesAllocated);
657 cLinesAllocated = RT_ALIGN(cLinesAllocated, 512);
658 void *pvNew = RTMemRealloc(pStream->paLines, cLinesAllocated * sizeof(SCMSTREAMLINE));
659 if (!pvNew)
660 return pStream->rc = VERR_NO_MEMORY;
661
662 pStream->paLines = (PSCMSTREAMLINE)pvNew;
663 pStream->cLinesAllocated = cLinesAllocated;
664 return VINF_SUCCESS;
665}
666
667/**
668 * Rewinds the stream and sets the mode to read.
669 *
670 * @param pStream The stream.
671 */
672void ScmStreamRewindForReading(PSCMSTREAM pStream)
673{
674 pStream->off = 0;
675 pStream->iLine = 0;
676 pStream->fWriteOrRead = false;
677 pStream->rc = VINF_SUCCESS;
678}
679
680/**
681 * Rewinds the stream and sets the mode to write.
682 *
683 * @param pStream The stream.
684 */
685void ScmStreamRewindForWriting(PSCMSTREAM pStream)
686{
687 pStream->off = 0;
688 pStream->iLine = 0;
689 pStream->cLines = 0;
690 pStream->fWriteOrRead = true;
691 pStream->fFullyLineated = true;
692 pStream->rc = VINF_SUCCESS;
693}
694
695/**
696 * Checks if it's a text stream.
697 *
698 * Not 100% proof.
699 *
700 * @returns true if it probably is a text file, false if not.
701 * @param pStream The stream. Write or read, doesn't matter.
702 */
703bool ScmStreamIsText(PSCMSTREAM pStream)
704{
705 if (memchr(pStream->pch, '\0', pStream->cb))
706 return false;
707 if (!pStream->cb)
708 return false;
709 return true;
710}
711
712/**
713 * Performs an integrity check of the stream.
714 *
715 * @returns IPRT status code.
716 * @param pStream The stream.
717 */
718int ScmStreamCheckItegrity(PSCMSTREAM pStream)
719{
720 /*
721 * Perform sanity checks.
722 */
723 size_t const cbFile = pStream->cb;
724 for (size_t iLine = 0; iLine < pStream->cLines; iLine++)
725 {
726 size_t offEol = pStream->paLines[iLine].off + pStream->paLines[iLine].cch;
727 AssertReturn(offEol + pStream->paLines[iLine].enmEol <= cbFile, VERR_INTERNAL_ERROR_2);
728 switch (pStream->paLines[iLine].enmEol)
729 {
730 case SCMEOL_LF:
731 AssertReturn(pStream->pch[offEol] == '\n', VERR_INTERNAL_ERROR_3);
732 break;
733 case SCMEOL_CRLF:
734 AssertReturn(pStream->pch[offEol] == '\r', VERR_INTERNAL_ERROR_3);
735 AssertReturn(pStream->pch[offEol + 1] == '\n', VERR_INTERNAL_ERROR_3);
736 break;
737 case SCMEOL_NONE:
738 AssertReturn(iLine + 1 >= pStream->cLines, VERR_INTERNAL_ERROR_4);
739 break;
740 default:
741 AssertReturn(iLine + 1 >= pStream->cLines, VERR_INTERNAL_ERROR_5);
742 }
743 }
744 return VINF_SUCCESS;
745}
746
747/**
748 * Writes the stream to a file.
749 *
750 * @returns IPRT status code
751 * @param pStream The stream.
752 * @param pszFilenameFmt The filename format string.
753 * @param ... Format arguments.
754 */
755int ScmStreamWriteToFile(PSCMSTREAM pStream, const char *pszFilenameFmt, ...)
756{
757 int rc;
758
759#ifdef RT_STRICT
760 /*
761 * Check that what we're going to write makes sense first.
762 */
763 rc = ScmStreamCheckItegrity(pStream);
764 if (RT_FAILURE(rc))
765 return rc;
766#endif
767
768 /*
769 * Do the actual writing.
770 */
771 RTFILE hFile;
772 va_list va;
773 va_start(va, pszFilenameFmt);
774 rc = RTFileOpenV(&hFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_WRITE, pszFilenameFmt, va);
775 if (RT_SUCCESS(rc))
776 {
777 rc = RTFileWrite(hFile, pStream->pch, pStream->cb, NULL);
778 RTFileClose(hFile);
779 }
780 return rc;
781}
782
783/**
784 * Worker for ScmStreamGetLine that builds the line number index while parsing
785 * the stream.
786 *
787 * @returns Same as SCMStreamGetLine.
788 * @param pStream The stream. Must be in read mode.
789 * @param pcchLine Where to return the line length.
790 * @param penmEol Where to return the kind of end of line marker.
791 */
792static const char *scmStreamGetLineInternal(PSCMSTREAM pStream, size_t *pcchLine, PSCMEOL penmEol)
793{
794 AssertReturn(!pStream->fWriteOrRead, NULL);
795 if (RT_FAILURE(pStream->rc))
796 return NULL;
797
798 size_t off = pStream->off;
799 size_t cb = pStream->cb;
800 if (RT_UNLIKELY(off >= cb))
801 {
802 pStream->fFullyLineated = true;
803 return NULL;
804 }
805
806 size_t iLine = pStream->iLine;
807 if (RT_UNLIKELY(iLine >= pStream->cLinesAllocated))
808 {
809 int rc = scmStreamGrowLines(pStream, iLine);
810 if (RT_FAILURE(rc))
811 return NULL;
812 }
813 pStream->paLines[iLine].off = off;
814
815 cb -= off;
816 const char *pchRet = &pStream->pch[off];
817 const char *pch = (const char *)memchr(pchRet, '\n', cb);
818 if (RT_LIKELY(pch))
819 {
820 cb = pch - pchRet;
821 pStream->off = off + cb + 1;
822 if ( cb < 1
823 || pch[-1] != '\r')
824 pStream->paLines[iLine].enmEol = *penmEol = SCMEOL_LF;
825 else
826 {
827 pStream->paLines[iLine].enmEol = *penmEol = SCMEOL_CRLF;
828 cb--;
829 }
830 }
831 else
832 {
833 pStream->off = off + cb;
834 pStream->paLines[iLine].enmEol = *penmEol = SCMEOL_NONE;
835 }
836 *pcchLine = cb;
837 pStream->paLines[iLine].cch = cb;
838 pStream->cLines = pStream->iLine = ++iLine;
839
840 return pchRet;
841}
842
843/**
844 * Internal worker that lineates a stream.
845 *
846 * @returns IPRT status code.
847 * @param pStream The stream. Caller must check that it is in
848 * read mode.
849 */
850static int scmStreamLineate(PSCMSTREAM pStream)
851{
852 /* Save the stream position. */
853 size_t const offSaved = pStream->off;
854 size_t const iLineSaved = pStream->iLine;
855
856 /* Get each line. */
857 size_t cchLine;
858 SCMEOL enmEol;
859 while (scmStreamGetLineInternal(pStream, &cchLine, &enmEol))
860 /* nothing */;
861 Assert(RT_FAILURE(pStream->rc) || pStream->fFullyLineated);
862
863 /* Restore the position */
864 pStream->off = offSaved;
865 pStream->iLine = iLineSaved;
866
867 return pStream->rc;
868}
869
870/**
871 * Get the current stream position as an byte offset.
872 *
873 * @returns The current byte offset
874 * @param pStream The stream.
875 */
876size_t ScmStreamTell(PSCMSTREAM pStream)
877{
878 return pStream->off;
879}
880
881/**
882 * Get the current stream position as a line number.
883 *
884 * @returns The current line (0-based).
885 * @param pStream The stream.
886 */
887size_t ScmStreamTellLine(PSCMSTREAM pStream)
888{
889 return pStream->iLine;
890}
891
892/**
893 * Get the current stream size in bytes.
894 *
895 * @returns Count of bytes.
896 * @param pStream The stream.
897 */
898size_t ScmStreamSize(PSCMSTREAM pStream)
899{
900 return pStream->cb;
901}
902
903/**
904 * Gets the number of lines in the stream.
905 *
906 * @returns The number of lines.
907 * @param pStream The stream.
908 */
909size_t ScmStreamCountLines(PSCMSTREAM pStream)
910{
911 if (!pStream->fFullyLineated)
912 scmStreamLineate(pStream);
913 return pStream->cLines;
914}
915
916/**
917 * Seeks to a given byte offset in the stream.
918 *
919 * @returns IPRT status code.
920 * @retval VERR_SEEK if the new stream position is the middle of an EOL marker.
921 * This is a temporary restriction.
922 *
923 * @param pStream The stream. Must be in read mode.
924 * @param offAbsolute The offset to seek to. If this is beyond the
925 * end of the stream, the position is set to the
926 * end.
927 */
928int ScmStreamSeekAbsolute(PSCMSTREAM pStream, size_t offAbsolute)
929{
930 AssertReturn(!pStream->fWriteOrRead, VERR_ACCESS_DENIED);
931 if (RT_FAILURE(pStream->rc))
932 return pStream->rc;
933
934 /* Must be fully lineated. (lazy bird) */
935 if (RT_UNLIKELY(!pStream->fFullyLineated))
936 {
937 int rc = scmStreamLineate(pStream);
938 if (RT_FAILURE(rc))
939 return rc;
940 }
941
942 /* Ok, do the job. */
943 if (offAbsolute < pStream->cb)
944 {
945 /** @todo Should do a binary search here, but I'm too darn lazy tonight. */
946 pStream->off = ~(size_t)0;
947 for (size_t i = 0; i < pStream->cLines; i++)
948 {
949 if (offAbsolute < pStream->paLines[i].off + pStream->paLines[i].cch + pStream->paLines[i].enmEol)
950 {
951 pStream->off = offAbsolute;
952 pStream->iLine = i;
953 if (offAbsolute > pStream->paLines[i].off + pStream->paLines[i].cch)
954 return pStream->rc = VERR_SEEK;
955 break;
956 }
957 }
958 AssertReturn(pStream->off != ~(size_t)0, pStream->rc = VERR_INTERNAL_ERROR_3);
959 }
960 else
961 {
962 pStream->off = pStream->cb;
963 pStream->iLine = pStream->cLines;
964 }
965 return VINF_SUCCESS;
966}
967
968
969/**
970 * Seeks a number of bytes relative to the current stream position.
971 *
972 * @returns IPRT status code.
973 * @retval VERR_SEEK if the new stream position is the middle of an EOL marker.
974 * This is a temporary restriction.
975 *
976 * @param pStream The stream. Must be in read mode.
977 * @param offRelative The offset to seek to. A negative offset
978 * rewinds and positive one fast forwards the
979 * stream. Will quietly stop at the begining and
980 * end of the stream.
981 */
982int ScmStreamSeekRelative(PSCMSTREAM pStream, ssize_t offRelative)
983{
984 size_t offAbsolute;
985 if (offRelative >= 0)
986 offAbsolute = pStream->off + offRelative;
987 else if ((size_t)-offRelative <= pStream->off)
988 offAbsolute = pStream->off + offRelative;
989 else
990 offAbsolute = 0;
991 return ScmStreamSeekAbsolute(pStream, offAbsolute);
992}
993
994/**
995 * Seeks to a given line in the stream.
996 *
997 * @returns IPRT status code.
998 *
999 * @param pStream The stream. Must be in read mode.
1000 * @param iLine The line to seek to. If this is beyond the end
1001 * of the stream, the position is set to the end.
1002 */
1003int ScmStreamSeekByLine(PSCMSTREAM pStream, size_t iLine)
1004{
1005 AssertReturn(!pStream->fWriteOrRead, VERR_ACCESS_DENIED);
1006 if (RT_FAILURE(pStream->rc))
1007 return pStream->rc;
1008
1009 /* Must be fully lineated. (lazy bird) */
1010 if (RT_UNLIKELY(!pStream->fFullyLineated))
1011 {
1012 int rc = scmStreamLineate(pStream);
1013 if (RT_FAILURE(rc))
1014 return rc;
1015 }
1016
1017 /* Ok, do the job. */
1018 if (iLine < pStream->cLines)
1019 {
1020 pStream->off = pStream->paLines[iLine].off;
1021 pStream->iLine = iLine;
1022 }
1023 else
1024 {
1025 pStream->off = pStream->cb;
1026 pStream->iLine = pStream->cLines;
1027 }
1028 return VINF_SUCCESS;
1029}
1030
1031/**
1032 * Get a numbered line from the stream (changes the position).
1033 *
1034 * A line is always delimited by a LF character or the end of the stream. The
1035 * delimiter is not included in returned line length, but instead returned via
1036 * the @a penmEol indicator.
1037 *
1038 * @returns Pointer to the first character in the line, not NULL terminated.
1039 * NULL if the end of the stream has been reached or some problem
1040 * occured.
1041 *
1042 * @param pStream The stream. Must be in read mode.
1043 * @param iLine The line to get (0-based).
1044 * @param pcchLine The length.
1045 * @param penmEol Where to return the end of line type indicator.
1046 */
1047static const char *ScmStreamGetLineByNo(PSCMSTREAM pStream, size_t iLine, size_t *pcchLine, PSCMEOL penmEol)
1048{
1049 AssertReturn(!pStream->fWriteOrRead, NULL);
1050 if (RT_FAILURE(pStream->rc))
1051 return NULL;
1052
1053 /* Make sure it's fully lineated so we can use the index. */
1054 if (RT_UNLIKELY(!pStream->fFullyLineated))
1055 {
1056 int rc = scmStreamLineate(pStream);
1057 if (RT_FAILURE(rc))
1058 return NULL;
1059 }
1060
1061 /* End of stream? */
1062 if (RT_UNLIKELY(iLine >= pStream->cLines))
1063 {
1064 pStream->off = pStream->cb;
1065 pStream->iLine = pStream->cLines;
1066 return NULL;
1067 }
1068
1069 /* Get the data. */
1070 const char *pchRet = &pStream->pch[pStream->paLines[iLine].off];
1071 *pcchLine = pStream->paLines[iLine].cch;
1072 *penmEol = pStream->paLines[iLine].enmEol;
1073
1074 /* update the stream position. */
1075 pStream->off = pStream->paLines[iLine].off + pStream->paLines[iLine].cch + pStream->paLines[iLine].enmEol;
1076 pStream->iLine = iLine + 1;
1077
1078 return pchRet;
1079}
1080
1081/**
1082 * Get a line from the stream.
1083 *
1084 * A line is always delimited by a LF character or the end of the stream. The
1085 * delimiter is not included in returned line length, but instead returned via
1086 * the @a penmEol indicator.
1087 *
1088 * @returns Pointer to the first character in the line, not NULL terminated.
1089 * NULL if the end of the stream has been reached or some problem
1090 * occured.
1091 *
1092 * @param pStream The stream. Must be in read mode.
1093 * @param pcchLine The length.
1094 * @param penmEol Where to return the end of line type indicator.
1095 */
1096static const char *ScmStreamGetLine(PSCMSTREAM pStream, size_t *pcchLine, PSCMEOL penmEol)
1097{
1098 /** @todo this doesn't work when pStream->off !=
1099 * pStream->paLines[pStream->iLine-1].pff. */
1100 if (!pStream->fFullyLineated)
1101 return scmStreamGetLineInternal(pStream, pcchLine, penmEol);
1102 return ScmStreamGetLineByNo(pStream, pStream->iLine, pcchLine, penmEol);
1103}
1104
1105/**
1106 * Reads @a cbToRead bytes into @a pvBuf.
1107 *
1108 * Will fail if end of stream is encountered before the entire read has been
1109 * completed.
1110 *
1111 * @returns IPRT status code.
1112 * @retval VERR_EOF if there isn't @a cbToRead bytes left to read. Stream
1113 * position will be unchanged.
1114 *
1115 * @param pStream The stream. Must be in read mode.
1116 * @param pvBuf The buffer to read into.
1117 * @param cbToRead The number of bytes to read.
1118 */
1119static int ScmStreamRead(PSCMSTREAM pStream, void *pvBuf, size_t cbToRead)
1120{
1121 AssertReturn(!pStream->fWriteOrRead, NULL);
1122 if (RT_FAILURE(pStream->rc))
1123 return NULL;
1124
1125 /* If there isn't enough stream left, fail already. */
1126 if (RT_UNLIKELY(pStream->cb - pStream->cb < cbToRead))
1127 return VERR_EOF;
1128
1129 /* Copy the data and simply seek to the new stream position. */
1130 memcpy(pvBuf, &pStream->pch[pStream->off], cbToRead);
1131 return ScmStreamSeekAbsolute(pStream, pStream->off + cbToRead);
1132}
1133
1134/**
1135 * Checks if the given line is empty or full of white space.
1136 *
1137 * @returns true if white space only, false if not (or if non-existant).
1138 * @param pStream The stream. Must be in read mode.
1139 * @param iLine The line in question.
1140 */
1141static bool ScmStreamIsWhiteLine(PSCMSTREAM pStream, size_t iLine)
1142{
1143 SCMEOL enmEol;
1144 size_t cchLine;
1145 const char *pchLine = ScmStreamGetLineByNo(pStream, iLine, &cchLine, &enmEol);
1146 if (!pchLine)
1147 return false;
1148 while (cchLine && RT_C_IS_SPACE(*pchLine))
1149 pchLine++, cchLine--;
1150 return cchLine == 0;
1151}
1152
1153/**
1154 * Try figure out the end of line style of the give stream.
1155 *
1156 * @returns Most likely end of line style.
1157 * @param pStream The stream.
1158 */
1159SCMEOL ScmStreamGetEol(PSCMSTREAM pStream)
1160{
1161 SCMEOL enmEol;
1162 if (pStream->cLines > 0)
1163 enmEol = pStream->paLines[0].enmEol;
1164 else if (pStream->cb == 0)
1165 enmEol = SCMEOL_NONE;
1166 else
1167 {
1168 const char *pchLF = (const char *)memchr(pStream->pch, '\n', pStream->cb);
1169 if (pchLF && pchLF != pStream->pch && pchLF[-1] == '\r')
1170 enmEol = SCMEOL_CRLF;
1171 else
1172 enmEol = SCMEOL_LF;
1173 }
1174
1175 if (enmEol == SCMEOL_NONE)
1176#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1177 enmEol = SCMEOL_CRLF;
1178#else
1179 enmEol = SCMEOL_LF;
1180#endif
1181 return enmEol;
1182}
1183
1184/**
1185 * Get the end of line indicator type for a line.
1186 *
1187 * @returns The EOL indicator. If the line isn't found, the default EOL
1188 * indicator is return.
1189 * @param pStream The stream.
1190 * @param iLine The line (0-base).
1191 */
1192SCMEOL ScmStreamGetEolByLine(PSCMSTREAM pStream, size_t iLine)
1193{
1194 SCMEOL enmEol;
1195 if (iLine < pStream->cLines)
1196 enmEol = pStream->paLines[iLine].enmEol;
1197 else
1198#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1199 enmEol = SCMEOL_CRLF;
1200#else
1201 enmEol = SCMEOL_LF;
1202#endif
1203 return enmEol;
1204}
1205
1206/**
1207 * Appends a line to the stream.
1208 *
1209 * @returns IPRT status code.
1210 * @param pStream The stream. Must be in write mode.
1211 * @param pchLine Pointer to the line.
1212 * @param cchLine Line length.
1213 * @param enmEol Which end of line indicator to use.
1214 */
1215int ScmStreamPutLine(PSCMSTREAM pStream, const char *pchLine, size_t cchLine, SCMEOL enmEol)
1216{
1217 AssertReturn(pStream->fWriteOrRead, VERR_ACCESS_DENIED);
1218 if (RT_FAILURE(pStream->rc))
1219 return pStream->rc;
1220
1221 /*
1222 * Make sure the previous line has a new-line indicator.
1223 */
1224 size_t off = pStream->off;
1225 size_t iLine = pStream->iLine;
1226 if (RT_UNLIKELY( iLine != 0
1227 && pStream->paLines[iLine - 1].enmEol == SCMEOL_NONE))
1228 {
1229 AssertReturn(pStream->paLines[iLine].cch == 0, VERR_INTERNAL_ERROR_3);
1230 SCMEOL enmEol2 = enmEol != SCMEOL_NONE ? enmEol : ScmStreamGetEol(pStream);
1231 if (RT_UNLIKELY(off + cchLine + enmEol + enmEol2 > pStream->cbAllocated))
1232 {
1233 int rc = scmStreamGrowBuffer(pStream, cchLine + enmEol + enmEol2);
1234 if (RT_FAILURE(rc))
1235 return rc;
1236 }
1237 if (enmEol2 == SCMEOL_LF)
1238 pStream->pch[off++] = '\n';
1239 else
1240 {
1241 pStream->pch[off++] = '\r';
1242 pStream->pch[off++] = '\n';
1243 }
1244 pStream->paLines[iLine - 1].enmEol = enmEol2;
1245 pStream->paLines[iLine].off = off;
1246 pStream->off = off;
1247 pStream->cb = off;
1248 }
1249
1250 /*
1251 * Ensure we've got sufficient buffer space.
1252 */
1253 if (RT_UNLIKELY(off + cchLine + enmEol > pStream->cbAllocated))
1254 {
1255 int rc = scmStreamGrowBuffer(pStream, cchLine + enmEol);
1256 if (RT_FAILURE(rc))
1257 return rc;
1258 }
1259
1260 /*
1261 * Add a line record.
1262 */
1263 if (RT_UNLIKELY(iLine + 1 >= pStream->cLinesAllocated))
1264 {
1265 int rc = scmStreamGrowLines(pStream, iLine);
1266 if (RT_FAILURE(rc))
1267 return rc;
1268 }
1269
1270 pStream->paLines[iLine].cch = off - pStream->paLines[iLine].off + cchLine;
1271 pStream->paLines[iLine].enmEol = enmEol;
1272
1273 iLine++;
1274 pStream->cLines = iLine;
1275 pStream->iLine = iLine;
1276
1277 /*
1278 * Copy the line
1279 */
1280 memcpy(&pStream->pch[off], pchLine, cchLine);
1281 off += cchLine;
1282 if (enmEol == SCMEOL_LF)
1283 pStream->pch[off++] = '\n';
1284 else if (enmEol == SCMEOL_CRLF)
1285 {
1286 pStream->pch[off++] = '\r';
1287 pStream->pch[off++] = '\n';
1288 }
1289 pStream->off = off;
1290 pStream->cb = off;
1291
1292 /*
1293 * Start a new line.
1294 */
1295 pStream->paLines[iLine].off = off;
1296 pStream->paLines[iLine].cch = 0;
1297 pStream->paLines[iLine].enmEol = SCMEOL_NONE;
1298
1299 return VINF_SUCCESS;
1300}
1301
1302/**
1303 * Writes to the stream.
1304 *
1305 * @returns IPRT status code
1306 * @param pStream The stream. Must be in write mode.
1307 * @param pchBuf What to write.
1308 * @param cchBuf How much to write.
1309 */
1310int ScmStreamWrite(PSCMSTREAM pStream, const char *pchBuf, size_t cchBuf)
1311{
1312 AssertReturn(pStream->fWriteOrRead, VERR_ACCESS_DENIED);
1313 if (RT_FAILURE(pStream->rc))
1314 return pStream->rc;
1315
1316 /*
1317 * Ensure we've got sufficient buffer space.
1318 */
1319 size_t off = pStream->off;
1320 if (RT_UNLIKELY(off + cchBuf > pStream->cbAllocated))
1321 {
1322 int rc = scmStreamGrowBuffer(pStream, cchBuf);
1323 if (RT_FAILURE(rc))
1324 return rc;
1325 }
1326
1327 /*
1328 * Deal with the odd case where we've already pushed a line with SCMEOL_NONE.
1329 */
1330 size_t iLine = pStream->iLine;
1331 if (RT_UNLIKELY( iLine > 0
1332 && pStream->paLines[iLine - 1].enmEol == SCMEOL_NONE))
1333 {
1334 iLine--;
1335 pStream->cLines = iLine;
1336 pStream->iLine = iLine;
1337 }
1338
1339 /*
1340 * Deal with lines.
1341 */
1342 const char *pchLF = (const char *)memchr(pchBuf, '\n', cchBuf);
1343 if (!pchLF)
1344 pStream->paLines[iLine].cch += cchBuf;
1345 else
1346 {
1347 const char *pchLine = pchBuf;
1348 for (;;)
1349 {
1350 if (RT_UNLIKELY(iLine + 1 >= pStream->cLinesAllocated))
1351 {
1352 int rc = scmStreamGrowLines(pStream, iLine);
1353 if (RT_FAILURE(rc))
1354 {
1355 iLine = pStream->iLine;
1356 pStream->paLines[iLine].cch = off - pStream->paLines[iLine].off;
1357 pStream->paLines[iLine].enmEol = SCMEOL_NONE;
1358 return rc;
1359 }
1360 }
1361
1362 size_t cchLine = pchLF - pchLine;
1363 if ( cchLine
1364 ? pchLF[-1] != '\r'
1365 : !pStream->paLines[iLine].cch
1366 || pStream->pch[pStream->paLines[iLine].off + pStream->paLines[iLine].cch - 1] != '\r')
1367 pStream->paLines[iLine].enmEol = SCMEOL_LF;
1368 else
1369 {
1370 pStream->paLines[iLine].enmEol = SCMEOL_CRLF;
1371 cchLine--;
1372 }
1373 pStream->paLines[iLine].cch += cchLine;
1374
1375 iLine++;
1376 size_t offBuf = pchLF + 1 - pchBuf;
1377 pStream->paLines[iLine].off = off + offBuf;
1378 pStream->paLines[iLine].cch = 0;
1379 pStream->paLines[iLine].enmEol = SCMEOL_NONE;
1380
1381 size_t cchLeft = cchBuf - offBuf;
1382 pchLF = (const char *)memchr(pchLF + 1, '\n', cchLeft);
1383 if (!pchLF)
1384 {
1385 pStream->paLines[iLine].cch = cchLeft;
1386 break;
1387 }
1388 }
1389
1390 pStream->iLine = iLine;
1391 pStream->cLines = iLine;
1392 }
1393
1394 /*
1395 * Copy the data and update position and size.
1396 */
1397 memcpy(&pStream->pch[off], pchBuf, cchBuf);
1398 off += cchBuf;
1399 pStream->off = off;
1400 pStream->cb = off;
1401
1402 return VINF_SUCCESS;
1403}
1404
1405/**
1406 * Write a character to the stream.
1407 *
1408 * @returns IPRT status code
1409 * @param pStream The stream. Must be in write mode.
1410 * @param pchBuf What to write.
1411 * @param cchBuf How much to write.
1412 */
1413int ScmStreamPutCh(PSCMSTREAM pStream, char ch)
1414{
1415 AssertReturn(pStream->fWriteOrRead, VERR_ACCESS_DENIED);
1416 if (RT_FAILURE(pStream->rc))
1417 return pStream->rc;
1418
1419 /*
1420 * Only deal with the simple cases here, use ScmStreamWrite for the
1421 * annyoing stuff.
1422 */
1423 size_t off = pStream->off;
1424 if ( ch == '\n'
1425 || RT_UNLIKELY(off + 1 > pStream->cbAllocated))
1426 return ScmStreamWrite(pStream, &ch, 1);
1427
1428 /*
1429 * Just append it.
1430 */
1431 pStream->pch[off] = ch;
1432 pStream->off = off + 1;
1433 pStream->paLines[pStream->iLine].cch++;
1434
1435 return VINF_SUCCESS;
1436}
1437
1438/**
1439 * Copies @a cLines from the @a pSrc stream onto the @a pDst stream.
1440 *
1441 * The stream positions will be used and changed in both streams.
1442 *
1443 * @returns IPRT status code.
1444 * @param pDst The destionation stream. Must be in write mode.
1445 * @param cLines The number of lines. (0 is accepted.)
1446 * @param pSrc The source stream. Must be in read mode.
1447 */
1448int ScmStreamCopyLines(PSCMSTREAM pDst, PSCMSTREAM pSrc, size_t cLines)
1449{
1450 AssertReturn(pDst->fWriteOrRead, VERR_ACCESS_DENIED);
1451 if (RT_FAILURE(pDst->rc))
1452 return pDst->rc;
1453
1454 AssertReturn(!pSrc->fWriteOrRead, VERR_ACCESS_DENIED);
1455 if (RT_FAILURE(pSrc->rc))
1456 return pSrc->rc;
1457
1458 while (cLines-- > 0)
1459 {
1460 SCMEOL enmEol;
1461 size_t cchLine;
1462 const char *pchLine = ScmStreamGetLine(pSrc, &cchLine, &enmEol);
1463 if (!pchLine)
1464 return pDst->rc = (RT_FAILURE(pSrc->rc) ? pSrc->rc : VERR_EOF);
1465
1466 int rc = ScmStreamPutLine(pDst, pchLine, cchLine, enmEol);
1467 if (RT_FAILURE(rc))
1468 return rc;
1469 }
1470
1471 return VINF_SUCCESS;
1472}
1473
1474/* -=-=-=-=-=- diff -=-=-=-=-=- */
1475
1476
1477/**
1478 * Prints a range of lines with a prefix.
1479 *
1480 * @param pState The diff state.
1481 * @param chPrefix The prefix.
1482 * @param pStream The stream to get the lines from.
1483 * @param iLine The first line.
1484 * @param cLines The number of lines.
1485 */
1486static void scmDiffPrintLines(PSCMDIFFSTATE pState, char chPrefix, PSCMSTREAM pStream, size_t iLine, size_t cLines)
1487{
1488 while (cLines-- > 0)
1489 {
1490 SCMEOL enmEol;
1491 size_t cchLine;
1492 const char *pchLine = ScmStreamGetLineByNo(pStream, iLine, &cchLine, &enmEol);
1493
1494 RTStrmPutCh(pState->pDiff, chPrefix);
1495 if (pchLine && cchLine)
1496 {
1497 if (!pState->fSpecialChars)
1498 RTStrmWrite(pState->pDiff, pchLine, cchLine);
1499 else
1500 {
1501 size_t offVir = 0;
1502 const char *pchStart = pchLine;
1503 const char *pchTab = (const char *)memchr(pchLine, '\t', cchLine);
1504 while (pchTab)
1505 {
1506 RTStrmWrite(pState->pDiff, pchStart, pchTab - pchStart);
1507 offVir += pchTab - pchStart;
1508
1509 size_t cchTab = pState->cchTab - offVir % pState->cchTab;
1510 switch (cchTab)
1511 {
1512 case 1: RTStrmPutStr(pState->pDiff, "."); break;
1513 case 2: RTStrmPutStr(pState->pDiff, ".."); break;
1514 case 3: RTStrmPutStr(pState->pDiff, "[T]"); break;
1515 case 4: RTStrmPutStr(pState->pDiff, "[TA]"); break;
1516 case 5: RTStrmPutStr(pState->pDiff, "[TAB]"); break;
1517 default: RTStrmPrintf(pState->pDiff, "[TAB%.*s]", cchTab - 5, g_szTabSpaces); break;
1518 }
1519 offVir += cchTab;
1520
1521 /* next */
1522 pchStart = pchTab + 1;
1523 pchTab = (const char *)memchr(pchStart, '\t', cchLine - (pchStart - pchLine));
1524 }
1525 size_t cchLeft = cchLine - (pchStart - pchLine);
1526 if (cchLeft)
1527 RTStrmWrite(pState->pDiff, pchStart, cchLeft);
1528 }
1529 }
1530
1531 if (!pState->fSpecialChars)
1532 RTStrmPutCh(pState->pDiff, '\n');
1533 else if (enmEol == SCMEOL_LF)
1534 RTStrmPutStr(pState->pDiff, "[LF]\n");
1535 else if (enmEol == SCMEOL_CRLF)
1536 RTStrmPutStr(pState->pDiff, "[CRLF]\n");
1537 else
1538 RTStrmPutStr(pState->pDiff, "[NONE]\n");
1539
1540 iLine++;
1541 }
1542}
1543
1544
1545/**
1546 * Reports a difference and propells the streams to the lines following the
1547 * resync.
1548 *
1549 *
1550 * @returns New pState->cDiff value (just to return something).
1551 * @param pState The diff state. The cDiffs member will be
1552 * incremented.
1553 * @param cMatches The resync length.
1554 * @param iLeft Where the difference starts on the left side.
1555 * @param cLeft How long it is on this side. ~(size_t)0 is used
1556 * to indicate that it goes all the way to the end.
1557 * @param iRight Where the difference starts on the right side.
1558 * @param cRight How long it is.
1559 */
1560static size_t scmDiffReport(PSCMDIFFSTATE pState, size_t cMatches,
1561 size_t iLeft, size_t cLeft,
1562 size_t iRight, size_t cRight)
1563{
1564 /*
1565 * Adjust the input.
1566 */
1567 if (cLeft == ~(size_t)0)
1568 {
1569 size_t c = ScmStreamCountLines(pState->pLeft);
1570 if (c >= iLeft)
1571 cLeft = c - iLeft;
1572 else
1573 {
1574 iLeft = c;
1575 cLeft = 0;
1576 }
1577 }
1578
1579 if (cRight == ~(size_t)0)
1580 {
1581 size_t c = ScmStreamCountLines(pState->pRight);
1582 if (c >= iRight)
1583 cRight = c - iRight;
1584 else
1585 {
1586 iRight = c;
1587 cRight = 0;
1588 }
1589 }
1590
1591 /*
1592 * Print header if it's the first difference
1593 */
1594 if (!pState->cDiffs)
1595 RTStrmPrintf(pState->pDiff, "diff %s %s\n", pState->pszFilename, pState->pszFilename);
1596
1597 /*
1598 * Emit the change description.
1599 */
1600 char ch = cLeft == 0
1601 ? 'a'
1602 : cRight == 0
1603 ? 'd'
1604 : 'c';
1605 if (cLeft > 1 && cRight > 1)
1606 RTStrmPrintf(pState->pDiff, "%zu,%zu%c%zu,%zu\n", iLeft + 1, iLeft + cLeft, ch, iRight + 1, iRight + cRight);
1607 else if (cLeft > 1)
1608 RTStrmPrintf(pState->pDiff, "%zu,%zu%c%zu\n", iLeft + 1, iLeft + cLeft, ch, iRight + 1);
1609 else if (cRight > 1)
1610 RTStrmPrintf(pState->pDiff, "%zu%c%zu,%zu\n", iLeft + 1, ch, iRight + 1, iRight + cRight);
1611 else
1612 RTStrmPrintf(pState->pDiff, "%zu%c%zu\n", iLeft + 1, ch, iRight + 1);
1613
1614 /*
1615 * And the lines.
1616 */
1617 if (cLeft)
1618 scmDiffPrintLines(pState, '<', pState->pLeft, iLeft, cLeft);
1619 if (cLeft && cRight)
1620 RTStrmPrintf(pState->pDiff, "---\n");
1621 if (cRight)
1622 scmDiffPrintLines(pState, '>', pState->pRight, iRight, cRight);
1623
1624 /*
1625 * Reposition the streams (safely ignores return value).
1626 */
1627 ScmStreamSeekByLine(pState->pLeft, iLeft + cLeft + cMatches);
1628 ScmStreamSeekByLine(pState->pRight, iRight + cRight + cMatches);
1629
1630 pState->cDiffs++;
1631 return pState->cDiffs;
1632}
1633
1634/**
1635 * Helper for scmDiffCompare that takes care of trailing spaces and stuff
1636 * like that.
1637 */
1638static bool scmDiffCompareSlow(PSCMDIFFSTATE pState,
1639 const char *pchLeft, size_t cchLeft, SCMEOL enmEolLeft,
1640 const char *pchRight, size_t cchRight, SCMEOL enmEolRight)
1641{
1642 if (pState->fIgnoreTrailingWhite)
1643 {
1644 while (cchLeft > 0 && RT_C_IS_SPACE(pchLeft[cchLeft - 1]))
1645 cchLeft--;
1646 while (cchRight > 0 && RT_C_IS_SPACE(pchRight[cchRight - 1]))
1647 cchRight--;
1648 }
1649
1650 if (pState->fIgnoreLeadingWhite)
1651 {
1652 while (cchLeft > 0 && RT_C_IS_SPACE(*pchLeft))
1653 pchLeft++, cchLeft--;
1654 while (cchRight > 0 && RT_C_IS_SPACE(*pchRight))
1655 pchRight++, cchRight--;
1656 }
1657
1658 if ( cchLeft != cchRight
1659 || (enmEolLeft != enmEolRight && !pState->fIgnoreEol)
1660 || memcmp(pchLeft, pchRight, cchLeft))
1661 return false;
1662 return true;
1663}
1664
1665/**
1666 * Compare two lines.
1667 *
1668 * @returns true if the are equal, false if not.
1669 */
1670DECLINLINE(bool) scmDiffCompare(PSCMDIFFSTATE pState,
1671 const char *pchLeft, size_t cchLeft, SCMEOL enmEolLeft,
1672 const char *pchRight, size_t cchRight, SCMEOL enmEolRight)
1673{
1674 if ( cchLeft != cchRight
1675 || (enmEolLeft != enmEolRight && !pState->fIgnoreEol)
1676 || memcmp(pchLeft, pchRight, cchLeft))
1677 {
1678 if ( pState->fIgnoreTrailingWhite
1679 || pState->fIgnoreTrailingWhite)
1680 return scmDiffCompareSlow(pState,
1681 pchLeft, cchLeft, enmEolLeft,
1682 pchRight, cchRight, enmEolRight);
1683 return false;
1684 }
1685 return true;
1686}
1687
1688/**
1689 * Compares two sets of lines from the two files.
1690 *
1691 * @returns true if they matches, false if they don't.
1692 * @param pState The diff state.
1693 * @param iLeft Where to start in the left stream.
1694 * @param iRight Where to start in the right stream.
1695 * @param cLines How many lines to compare.
1696 */
1697static bool scmDiffCompareLines(PSCMDIFFSTATE pState, size_t iLeft, size_t iRight, size_t cLines)
1698{
1699 for (size_t iLine = 0; iLine < cLines; iLine++)
1700 {
1701 SCMEOL enmEolLeft;
1702 size_t cchLeft;
1703 const char *pchLeft = ScmStreamGetLineByNo(pState->pLeft, iLeft + iLine, &cchLeft, &enmEolLeft);
1704
1705 SCMEOL enmEolRight;
1706 size_t cchRight;
1707 const char *pchRight = ScmStreamGetLineByNo(pState->pRight, iRight + iLine, &cchRight, &enmEolRight);
1708
1709 if (!scmDiffCompare(pState, pchLeft, cchLeft, enmEolLeft, pchRight, cchRight, enmEolRight))
1710 return false;
1711 }
1712 return true;
1713}
1714
1715
1716/**
1717 * Resynchronize the two streams and reports the difference.
1718 *
1719 * Upon return, the streams will be positioned after the block of @a cMatches
1720 * lines where it resynchronized them.
1721 *
1722 * @returns pState->cDiffs (just so we can use it in a return statement).
1723 * @param pState The state.
1724 * @param cMatches The number of lines that needs to match for the
1725 * stream to be considered synchronized again.
1726 */
1727static size_t scmDiffSynchronize(PSCMDIFFSTATE pState, size_t cMatches)
1728{
1729 size_t const iStartLeft = ScmStreamTellLine(pState->pLeft) - 1;
1730 size_t const iStartRight = ScmStreamTellLine(pState->pRight) - 1;
1731 Assert(cMatches > 0);
1732
1733 /*
1734 * Compare each new line from each of the streams will all the preceding
1735 * ones, including iStartLeft/Right.
1736 */
1737 for (size_t iRange = 1; ; iRange++)
1738 {
1739 /*
1740 * Get the next line in the left stream and compare it against all the
1741 * preceding lines on the right side.
1742 */
1743 SCMEOL enmEol;
1744 size_t cchLine;
1745 const char *pchLine = ScmStreamGetLineByNo(pState->pLeft, iStartLeft + iRange, &cchLine, &enmEol);
1746 if (!pchLine)
1747 return scmDiffReport(pState, 0, iStartLeft, ~(size_t)0, iStartRight, ~(size_t)0);
1748
1749 for (size_t iRight = cMatches - 1; iRight < iRange; iRight++)
1750 {
1751 SCMEOL enmEolRight;
1752 size_t cchRight;
1753 const char *pchRight = ScmStreamGetLineByNo(pState->pRight, iStartRight + iRight,
1754 &cchRight, &enmEolRight);
1755 if ( scmDiffCompare(pState, pchLine, cchLine, enmEol, pchRight, cchRight, enmEolRight)
1756 && scmDiffCompareLines(pState,
1757 iStartLeft + iRange + 1 - cMatches,
1758 iStartRight + iRight + 1 - cMatches,
1759 cMatches - 1)
1760 )
1761 return scmDiffReport(pState, cMatches,
1762 iStartLeft, iRange + 1 - cMatches,
1763 iStartRight, iRight + 1 - cMatches);
1764 }
1765
1766 /*
1767 * Get the next line in the right stream and compare it against all the
1768 * lines on the right side.
1769 */
1770 pchLine = ScmStreamGetLineByNo(pState->pRight, iStartRight + iRange, &cchLine, &enmEol);
1771 if (!pchLine)
1772 return scmDiffReport(pState, 0, iStartLeft, ~(size_t)0, iStartRight, ~(size_t)0);
1773
1774 for (size_t iLeft = cMatches - 1; iLeft <= iRange; iLeft++)
1775 {
1776 SCMEOL enmEolLeft;
1777 size_t cchLeft;
1778 const char *pchLeft = ScmStreamGetLineByNo(pState->pLeft, iStartLeft + iLeft,
1779 &cchLeft, &enmEolLeft);
1780 if ( scmDiffCompare(pState, pchLeft, cchLeft, enmEolLeft, pchLine, cchLine, enmEol)
1781 && scmDiffCompareLines(pState,
1782 iStartLeft + iLeft + 1 - cMatches,
1783 iStartRight + iRange + 1 - cMatches,
1784 cMatches - 1)
1785 )
1786 return scmDiffReport(pState, cMatches,
1787 iStartLeft, iLeft + 1 - cMatches,
1788 iStartRight, iRange + 1 - cMatches);
1789 }
1790 }
1791}
1792
1793/**
1794 * Creates a diff of the changes between the streams @a pLeft and @a pRight.
1795 *
1796 * This currently only implements the simplest diff format, so no contexts.
1797 *
1798 * Also, note that we won't detect differences in the final newline of the
1799 * streams.
1800 *
1801 * @returns The number of differences.
1802 * @param pszFilename The filename.
1803 * @param pLeft The left side stream.
1804 * @param pRight The right side stream.
1805 * @param fIgnoreEol Whether to ignore end of line markers.
1806 * @param fIgnoreLeadingWhite Set if leading white space should be ignored.
1807 * @param fIgnoreTrailingWhite Set if trailing white space should be ignored.
1808 * @param fSpecialChars Whether to print special chars in a human
1809 * readable form or not.
1810 * @param cchTab The tab size.
1811 * @param pDiff Where to write the diff.
1812 */
1813size_t ScmDiffStreams(const char *pszFilename, PSCMSTREAM pLeft, PSCMSTREAM pRight, bool fIgnoreEol,
1814 bool fIgnoreLeadingWhite, bool fIgnoreTrailingWhite, bool fSpecialChars,
1815 size_t cchTab, PRTSTREAM pDiff)
1816{
1817#ifdef RT_STRICT
1818 ScmStreamCheckItegrity(pLeft);
1819 ScmStreamCheckItegrity(pRight);
1820#endif
1821
1822 /*
1823 * Set up the diff state.
1824 */
1825 SCMDIFFSTATE State;
1826 State.cDiffs = 0;
1827 State.pszFilename = pszFilename;
1828 State.pLeft = pLeft;
1829 State.pRight = pRight;
1830 State.fIgnoreEol = fIgnoreEol;
1831 State.fIgnoreLeadingWhite = fIgnoreLeadingWhite;
1832 State.fIgnoreTrailingWhite = fIgnoreTrailingWhite;
1833 State.fSpecialChars = fSpecialChars;
1834 State.cchTab = cchTab;
1835 State.pDiff = pDiff;
1836
1837 /*
1838 * Compare them line by line.
1839 */
1840 ScmStreamRewindForReading(pLeft);
1841 ScmStreamRewindForReading(pRight);
1842 const char *pchLeft;
1843 const char *pchRight;
1844
1845 for (;;)
1846 {
1847 SCMEOL enmEolLeft;
1848 size_t cchLeft;
1849 pchLeft = ScmStreamGetLine(pLeft, &cchLeft, &enmEolLeft);
1850
1851 SCMEOL enmEolRight;
1852 size_t cchRight;
1853 pchRight = ScmStreamGetLine(pRight, &cchRight, &enmEolRight);
1854 if (!pchLeft || !pchRight)
1855 break;
1856
1857 if (!scmDiffCompare(&State, pchLeft, cchLeft, enmEolLeft, pchRight, cchRight, enmEolRight))
1858 scmDiffSynchronize(&State, 3);
1859 }
1860
1861 /*
1862 * Deal with any remaining differences.
1863 */
1864 if (pchLeft)
1865 scmDiffReport(&State, 0, ScmStreamTellLine(pLeft) - 1, ~(size_t)0, ScmStreamTellLine(pRight), 0);
1866 else if (pchRight)
1867 scmDiffReport(&State, 0, ScmStreamTellLine(pLeft), 0, ScmStreamTellLine(pRight) - 1, ~(size_t)0);
1868
1869 /*
1870 * Report any errors.
1871 */
1872 if (RT_FAILURE(ScmStreamGetStatus(pLeft)))
1873 RTMsgError("Left diff stream error: %Rrc\n", ScmStreamGetStatus(pLeft));
1874 if (RT_FAILURE(ScmStreamGetStatus(pRight)))
1875 RTMsgError("Right diff stream error: %Rrc\n", ScmStreamGetStatus(pRight));
1876
1877 return State.cDiffs;
1878}
1879
1880
1881
1882/* -=-=-=-=-=- settings -=-=-=-=-=- */
1883
1884/**
1885 * Init a settings structure with settings from @a pSrc.
1886 *
1887 * @returns IPRT status code
1888 * @param pSettings The settings.
1889 * @param pSrc The source settings.
1890 */
1891static int scmSettingsBaseInitAndCopy(PSCMSETTINGSBASE pSettings, PCSCMSETTINGSBASE pSrc)
1892{
1893 *pSettings = *pSrc;
1894
1895 int rc = RTStrDupEx(&pSettings->pszFilterFiles, pSrc->pszFilterFiles);
1896 if (RT_SUCCESS(rc))
1897 {
1898 rc = RTStrDupEx(&pSettings->pszFilterOutFiles, pSrc->pszFilterOutFiles);
1899 if (RT_SUCCESS(rc))
1900 {
1901 rc = RTStrDupEx(&pSettings->pszFilterOutDirs, pSrc->pszFilterOutDirs);
1902 if (RT_SUCCESS(rc))
1903 return VINF_SUCCESS;
1904
1905 RTStrFree(pSettings->pszFilterOutFiles);
1906 }
1907 RTStrFree(pSettings->pszFilterFiles);
1908 }
1909
1910 pSettings->pszFilterFiles = NULL;
1911 pSettings->pszFilterOutFiles = NULL;
1912 pSettings->pszFilterOutDirs = NULL;
1913 return rc;
1914}
1915
1916/**
1917 * Init a settings structure.
1918 *
1919 * @returns IPRT status code
1920 * @param pSettings The settings.
1921 */
1922static int scmSettingsBaseInit(PSCMSETTINGSBASE pSettings)
1923{
1924 return scmSettingsBaseInitAndCopy(pSettings, &g_Defaults);
1925}
1926
1927/**
1928 * Deletes the settings, i.e. free any dynamically allocated content.
1929 *
1930 * @param pSettings The settings.
1931 */
1932static void scmSettingsBaseDelete(PSCMSETTINGSBASE pSettings)
1933{
1934 if (pSettings)
1935 {
1936 Assert(pSettings->cchTab != ~(unsigned)0);
1937 pSettings->cchTab = ~(unsigned)0;
1938
1939 RTStrFree(pSettings->pszFilterFiles);
1940 pSettings->pszFilterFiles = NULL;
1941
1942 RTStrFree(pSettings->pszFilterOutFiles);
1943 pSettings->pszFilterOutFiles = NULL;
1944
1945 RTStrFree(pSettings->pszFilterOutDirs);
1946 pSettings->pszFilterOutDirs = NULL;
1947 }
1948}
1949
1950
1951/**
1952 * Processes a RTGetOpt result.
1953 *
1954 * @retval VINF_SUCCESS if handled.
1955 * @retval VERR_OUT_OF_RANGE if the option value was out of range.
1956 * @retval VERR_GETOPT_UNKNOWN_OPTION if the option was not recognized.
1957 *
1958 * @param pSettings The settings to change.
1959 * @param rc The RTGetOpt return value.
1960 * @param pValueUnion The RTGetOpt value union.
1961 */
1962static int scmSettingsBaseHandleOpt(PSCMSETTINGSBASE pSettings, int rc, PRTGETOPTUNION pValueUnion)
1963{
1964 switch (rc)
1965 {
1966 case SCMOPT_CONVERT_EOL:
1967 pSettings->fConvertEol = true;
1968 return VINF_SUCCESS;
1969 case SCMOPT_NO_CONVERT_EOL:
1970 pSettings->fConvertEol = false;
1971 return VINF_SUCCESS;
1972
1973 case SCMOPT_CONVERT_TABS:
1974 pSettings->fConvertTabs = true;
1975 return VINF_SUCCESS;
1976 case SCMOPT_NO_CONVERT_TABS:
1977 pSettings->fConvertTabs = false;
1978 return VINF_SUCCESS;
1979
1980 case SCMOPT_FORCE_FINAL_EOL:
1981 pSettings->fForceFinalEol = true;
1982 return VINF_SUCCESS;
1983 case SCMOPT_NO_FORCE_FINAL_EOL:
1984 pSettings->fForceFinalEol = false;
1985 return VINF_SUCCESS;
1986
1987 case SCMOPT_FORCE_TRAILING_LINE:
1988 pSettings->fForceTrailingLine = true;
1989 return VINF_SUCCESS;
1990 case SCMOPT_NO_FORCE_TRAILING_LINE:
1991 pSettings->fForceTrailingLine = false;
1992 return VINF_SUCCESS;
1993
1994 case SCMOPT_STRIP_TRAILING_BLANKS:
1995 pSettings->fStripTrailingBlanks = true;
1996 return VINF_SUCCESS;
1997 case SCMOPT_NO_STRIP_TRAILING_BLANKS:
1998 pSettings->fStripTrailingBlanks = false;
1999 return VINF_SUCCESS;
2000
2001 case SCMOPT_STRIP_TRAILING_LINES:
2002 pSettings->fStripTrailingLines = true;
2003 return VINF_SUCCESS;
2004 case SCMOPT_NO_STRIP_TRAILING_LINES:
2005 pSettings->fStripTrailingLines = false;
2006 return VINF_SUCCESS;
2007
2008 case SCMOPT_ONLY_SVN_DIRS:
2009 pSettings->fOnlySvnDirs = true;
2010 return VINF_SUCCESS;
2011 case SCMOPT_NOT_ONLY_SVN_DIRS:
2012 pSettings->fOnlySvnDirs = false;
2013 return VINF_SUCCESS;
2014
2015 case SCMOPT_ONLY_SVN_FILES:
2016 pSettings->fOnlySvnFiles = true;
2017 return VINF_SUCCESS;
2018 case SCMOPT_NOT_ONLY_SVN_FILES:
2019 pSettings->fOnlySvnFiles = false;
2020 return VINF_SUCCESS;
2021
2022 case SCMOPT_SET_SVN_EOL:
2023 pSettings->fSetSvnEol = true;
2024 return VINF_SUCCESS;
2025 case SCMOPT_DONT_SET_SVN_EOL:
2026 return VINF_SUCCESS;
2027
2028 case SCMOPT_TAB_SIZE:
2029 if ( pValueUnion->u8 < 1
2030 || pValueUnion->u8 >= RT_ELEMENTS(g_szTabSpaces))
2031 {
2032 RTMsgError("Invalid tab size: %u - must be in {1..%u}\n",
2033 pValueUnion->u8, RT_ELEMENTS(g_szTabSpaces) - 1);
2034 return VERR_OUT_OF_RANGE;
2035 }
2036 pSettings->cchTab = pValueUnion->u8;
2037 return VINF_SUCCESS;
2038
2039 case SCMOPT_FILTER_OUT_DIRS:
2040 case SCMOPT_FILTER_FILES:
2041 case SCMOPT_FILTER_OUT_FILES:
2042 {
2043 char **ppsz;
2044 switch (rc)
2045 {
2046 case SCMOPT_FILTER_OUT_DIRS: ppsz = &pSettings->pszFilterOutDirs; break;
2047 case SCMOPT_FILTER_FILES: ppsz = &pSettings->pszFilterFiles; break;
2048 case SCMOPT_FILTER_OUT_FILES: ppsz = &pSettings->pszFilterOutFiles; break;
2049 }
2050
2051 /*
2052 * An empty string zaps the current list.
2053 */
2054 if (!*pValueUnion->psz)
2055 return RTStrATruncate(ppsz, 0);
2056
2057 /*
2058 * Non-empty strings are appended to the pattern list.
2059 *
2060 * Strip leading and trailing pattern separators before attempting
2061 * to append it. If it's just separators, don't do anything.
2062 */
2063 const char *pszSrc = pValueUnion->psz;
2064 while (*pszSrc == '|')
2065 pszSrc++;
2066 size_t cchSrc = strlen(pszSrc);
2067 while (cchSrc > 0 && pszSrc[cchSrc - 1] == '|')
2068 cchSrc--;
2069 if (!cchSrc)
2070 return VINF_SUCCESS;
2071
2072 return RTStrAAppendExN(ppsz, 2,
2073 "|", *ppsz && **ppsz ? 1 : 0,
2074 pszSrc, cchSrc);
2075 }
2076
2077 default:
2078 return VERR_GETOPT_UNKNOWN_OPTION;
2079 }
2080}
2081
2082/**
2083 * Parses an option string.
2084 *
2085 * @returns IPRT status code.
2086 * @param pBase The base settings structure to apply the options
2087 * to.
2088 * @param pszOptions The options to parse.
2089 */
2090static int scmSettingsBaseParseString(PSCMSETTINGSBASE pBase, const char *pszLine)
2091{
2092 int cArgs;
2093 char **papszArgs;
2094 int rc = RTGetOptArgvFromString(&papszArgs, &cArgs, pszLine, NULL);
2095 if (RT_SUCCESS(rc))
2096 {
2097 RTGETOPTUNION ValueUnion;
2098 RTGETOPTSTATE GetOptState;
2099 rc = RTGetOptInit(&GetOptState, cArgs, papszArgs, &g_aScmOpts[0], RT_ELEMENTS(g_aScmOpts), 0, 0 /*fFlags*/);
2100 if (RT_SUCCESS(rc))
2101 {
2102 while ((rc = RTGetOpt(&GetOptState, &ValueUnion)) != 0)
2103 {
2104 rc = scmSettingsBaseHandleOpt(pBase, rc, &ValueUnion);
2105 if (RT_FAILURE(rc))
2106 break;
2107 }
2108 }
2109 RTGetOptArgvFree(papszArgs);
2110 }
2111
2112 return rc;
2113}
2114
2115/**
2116 * Parses an unterminated option string.
2117 *
2118 * @returns IPRT status code.
2119 * @param pBase The base settings structure to apply the options
2120 * to.
2121 * @param pchLine The line.
2122 * @param cchLine The line length.
2123 */
2124static int scmSettingsBaseParseStringN(PSCMSETTINGSBASE pBase, const char *pchLine, size_t cchLine)
2125{
2126 char *pszLine = RTStrDupN(pchLine, cchLine);
2127 if (!pszLine)
2128 return VERR_NO_MEMORY;
2129 int rc = scmSettingsBaseParseString(pBase, pszLine);
2130 RTStrFree(pszLine);
2131 return rc;
2132}
2133
2134/**
2135 * Verifies the options string.
2136 *
2137 * @returns IPRT status code.
2138 * @param pszOptions The options to verify .
2139 */
2140static int scmSettingsBaseVerifyString(const char *pszOptions)
2141{
2142 SCMSETTINGSBASE Base;
2143 int rc = scmSettingsBaseInit(&Base);
2144 if (RT_SUCCESS(rc))
2145 {
2146 rc = scmSettingsBaseParseString(&Base, pszOptions);
2147 scmSettingsBaseDelete(&Base);
2148 }
2149 return rc;
2150}
2151
2152/**
2153 * Loads settings found in editor and SCM settings directives within the
2154 * document (@a pStream).
2155 *
2156 * @returns IPRT status code.
2157 * @param pBase The settings base to load settings into.
2158 * @param pStream The stream to scan for settings directives.
2159 */
2160static int scmSettingsBaseLoadFromDocument(PSCMSETTINGSBASE pBase, PSCMSTREAM pStream)
2161{
2162 /** @todo Editor and SCM settings directives in documents. */
2163 return VINF_SUCCESS;
2164}
2165
2166/**
2167 * Creates a new settings file struct, cloning @a pSettings.
2168 *
2169 * @returns IPRT status code.
2170 * @param ppSettings Where to return the new struct.
2171 * @param pSettingsBase The settings to inherit from.
2172 */
2173static int scmSettingsCreate(PSCMSETTINGS *ppSettings, PCSCMSETTINGSBASE pSettingsBase)
2174{
2175 PSCMSETTINGS pSettings = (PSCMSETTINGS)RTMemAlloc(sizeof(*pSettings));
2176 if (!pSettings)
2177 return VERR_NO_MEMORY;
2178 int rc = scmSettingsBaseInitAndCopy(&pSettings->Base, pSettingsBase);
2179 if (RT_SUCCESS(rc))
2180 {
2181 pSettings->pDown = NULL;
2182 pSettings->pUp = NULL;
2183 pSettings->paPairs = NULL;
2184 pSettings->cPairs = 0;
2185 *ppSettings = pSettings;
2186 return VINF_SUCCESS;
2187 }
2188 RTMemFree(pSettings);
2189 return rc;
2190}
2191
2192/**
2193 * Destroys a settings structure.
2194 *
2195 * @param pSettings The settgins structure to destroy. NULL is OK.
2196 */
2197static void scmSettingsDestroy(PSCMSETTINGS pSettings)
2198{
2199 if (pSettings)
2200 {
2201 scmSettingsBaseDelete(&pSettings->Base);
2202 for (size_t i = 0; i < pSettings->cPairs; i++)
2203 {
2204 RTStrFree(pSettings->paPairs[i].pszPattern);
2205 RTStrFree(pSettings->paPairs[i].pszOptions);
2206 pSettings->paPairs[i].pszPattern = NULL;
2207 pSettings->paPairs[i].pszOptions = NULL;
2208 }
2209 RTMemFree(pSettings->paPairs);
2210 pSettings->paPairs = NULL;
2211 RTMemFree(pSettings);
2212 }
2213}
2214
2215/**
2216 * Adds a pattern/options pair to the settings structure.
2217 *
2218 * @returns IPRT status code.
2219 * @param pSettings The settings.
2220 * @param pchLine The line containing the unparsed pair.
2221 * @param cchLine The length of the line.
2222 */
2223static int scmSettingsAddPair(PSCMSETTINGS pSettings, const char *pchLine, size_t cchLine)
2224{
2225 /*
2226 * Split the string.
2227 */
2228 const char *pchOptions = (const char *)memchr(pchLine, ':', cchLine);
2229 if (!pchOptions)
2230 return VERR_INVALID_PARAMETER;
2231 size_t cchPattern = pchOptions - pchLine;
2232 size_t cchOptions = cchLine - cchPattern - 1;
2233 pchOptions++;
2234
2235 /* strip spaces everywhere */
2236 while (cchPattern > 0 && RT_C_IS_SPACE(pchLine[cchPattern - 1]))
2237 cchPattern--;
2238 while (cchPattern > 0 && RT_C_IS_SPACE(*pchLine))
2239 cchPattern--, pchLine++;
2240
2241 while (cchOptions > 0 && RT_C_IS_SPACE(pchOptions[cchOptions - 1]))
2242 cchOptions--;
2243 while (cchOptions > 0 && RT_C_IS_SPACE(*pchOptions))
2244 cchOptions--, pchOptions++;
2245
2246 /* Quietly ignore empty patterns and empty options. */
2247 if (!cchOptions || !cchPattern)
2248 return VINF_SUCCESS;
2249
2250 /*
2251 * Add the pair and verify the option string.
2252 */
2253 uint32_t iPair = pSettings->cPairs;
2254 if ((iPair % 32) == 0)
2255 {
2256 void *pvNew = RTMemRealloc(pSettings->paPairs, (iPair + 32) * sizeof(pSettings->paPairs[0]));
2257 if (!pvNew)
2258 return VERR_NO_MEMORY;
2259 pSettings->paPairs = (PSCMPATRNOPTPAIR)pvNew;
2260 }
2261
2262 pSettings->paPairs[iPair].pszPattern = RTStrDupN(pchLine, cchPattern);
2263 pSettings->paPairs[iPair].pszOptions = RTStrDupN(pchOptions, cchOptions);
2264 int rc;
2265 if ( pSettings->paPairs[iPair].pszPattern
2266 && pSettings->paPairs[iPair].pszOptions)
2267 rc = scmSettingsBaseVerifyString(pSettings->paPairs[iPair].pszOptions);
2268 else
2269 rc = VERR_NO_MEMORY;
2270 if (RT_SUCCESS(rc))
2271 pSettings->cPairs = iPair + 1;
2272 else
2273 {
2274 RTStrFree(pSettings->paPairs[iPair].pszPattern);
2275 RTStrFree(pSettings->paPairs[iPair].pszOptions);
2276 }
2277 return rc;
2278}
2279
2280/**
2281 * Loads in the settings from @a pszFilename.
2282 *
2283 * @returns IPRT status code.
2284 * @param pSettings Where to load the settings file.
2285 * @param pszFilename The file to load.
2286 */
2287static int scmSettingsLoadFile(PSCMSETTINGS pSettings, const char *pszFilename)
2288{
2289 SCMSTREAM Stream;
2290 int rc = ScmStreamInitForReading(&Stream, pszFilename);
2291 if (RT_FAILURE(rc))
2292 {
2293 RTMsgError("%s: ScmStreamInitForReading -> %Rrc\n", pszFilename, rc);
2294 return rc;
2295 }
2296
2297 SCMEOL enmEol;
2298 const char *pchLine;
2299 size_t cchLine;
2300 while ((pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol)) != NULL)
2301 {
2302 /* Ignore leading spaces. */
2303 while (cchLine > 0 && RT_C_IS_SPACE(*pchLine))
2304 pchLine++, cchLine--;
2305
2306 /* Ignore empty lines and comment lines. */
2307 if (cchLine < 1 || *pchLine == '#')
2308 continue;
2309
2310 /* What kind of line is it? */
2311 const char *pchColon = (const char *)memchr(pchLine, ':', cchLine);
2312 if (pchColon)
2313 rc = scmSettingsAddPair(pSettings, pchLine, cchLine);
2314 else
2315 rc = scmSettingsBaseParseStringN(&pSettings->Base, pchLine, cchLine);
2316 if (RT_FAILURE(rc))
2317 {
2318 RTMsgError("%s:%d: %Rrc\n", pszFilename, ScmStreamTellLine(&Stream), rc);
2319 break;
2320 }
2321 }
2322
2323 if (RT_SUCCESS(rc))
2324 {
2325 rc = ScmStreamGetStatus(&Stream);
2326 if (RT_FAILURE(rc))
2327 RTMsgError("%s: ScmStreamGetStatus- > %Rrc\n", pszFilename, rc);
2328 }
2329
2330 ScmStreamDelete(&Stream);
2331 return rc;
2332}
2333
2334/**
2335 * Parse the specified settings file creating a new settings struct from it.
2336 *
2337 * @returns IPRT status code
2338 * @param ppSettings Where to return the new settings.
2339 * @param pszFilename The file to parse.
2340 * @param pSettingsBase The base settings we inherit from.
2341 */
2342static int scmSettingsCreateFromFile(PSCMSETTINGS *ppSettings, const char *pszFilename, PCSCMSETTINGSBASE pSettingsBase)
2343{
2344 PSCMSETTINGS pSettings;
2345 int rc = scmSettingsCreate(&pSettings, pSettingsBase);
2346 if (RT_SUCCESS(rc))
2347 {
2348 rc = scmSettingsLoadFile(pSettings, pszFilename);
2349 if (RT_SUCCESS(rc))
2350 {
2351 *ppSettings = pSettings;
2352 return VINF_SUCCESS;
2353 }
2354
2355 scmSettingsDestroy(pSettings);
2356 }
2357 *ppSettings = NULL;
2358 return rc;
2359}
2360
2361
2362/**
2363 * Create an initial settings structure when starting processing a new file or
2364 * directory.
2365 *
2366 * This will look for .scm-settings files from the root and down to the
2367 * specified directory, combining them into the returned settings structure.
2368 *
2369 * @returns IPRT status code.
2370 * @param ppSettings Where to return the pointer to the top stack
2371 * object.
2372 * @param pBaseSettings The base settings we inherit from (globals
2373 * typically).
2374 * @param pszPath The absolute path to the new directory or file.
2375 */
2376static int scmSettingsCreateForPath(PSCMSETTINGS *ppSettings, PCSCMSETTINGSBASE pBaseSettings, const char *pszPath)
2377{
2378 /*
2379 * We'll be working with a stack copy of the path.
2380 */
2381 char szFile[RTPATH_MAX];
2382 size_t cchDir = strlen(pszPath);
2383 if (cchDir >= sizeof(szFile) - sizeof(SCM_SETTINGS_FILENAME))
2384 return VERR_FILENAME_TOO_LONG;
2385
2386 /*
2387 * Create the bottom-most settings.
2388 */
2389 PSCMSETTINGS pSettings;
2390 int rc = scmSettingsCreate(&pSettings, pBaseSettings);
2391 if (RT_FAILURE(rc))
2392 return rc;
2393
2394 /*
2395 * Enumerate the path components from the root and down. Load any setting
2396 * files we find.
2397 */
2398 size_t cComponents = RTPathCountComponents(pszPath);
2399 for (size_t i = 1; i <= cComponents; i++)
2400 {
2401 rc = RTPathCopyComponents(szFile, sizeof(szFile), pszPath, i);
2402 if (RT_SUCCESS(rc))
2403 rc = RTPathAppend(szFile, sizeof(szFile), SCM_SETTINGS_FILENAME);
2404 if (RT_FAILURE(rc))
2405 break;
2406 if (RTFileExists(szFile))
2407 {
2408 rc = scmSettingsLoadFile(pSettings, szFile);
2409 if (RT_FAILURE(rc))
2410 break;
2411 }
2412 }
2413
2414 if (RT_SUCCESS(rc))
2415 *ppSettings = pSettings;
2416 else
2417 scmSettingsDestroy(pSettings);
2418 return rc;
2419}
2420
2421/**
2422 * Pushes a new settings set onto the stack.
2423 *
2424 * @param ppSettingsStack The pointer to the pointer to the top stack
2425 * element. This will be used as input and output.
2426 * @param pSettings The settings to push onto the stack.
2427 */
2428static void scmSettingsStackPush(PSCMSETTINGS *ppSettingsStack, PSCMSETTINGS pSettings)
2429{
2430 PSCMSETTINGS pOld = *ppSettingsStack;
2431 pSettings->pDown = pOld;
2432 pSettings->pUp = NULL;
2433 if (pOld)
2434 pOld->pUp = pSettings;
2435 *ppSettingsStack = pSettings;
2436}
2437
2438/**
2439 * Pushes the settings of the specified directory onto the stack.
2440 *
2441 * We will load any .scm-settings in the directory. A stack entry is added even
2442 * if no settings file was found.
2443 *
2444 * @returns IPRT status code.
2445 * @param ppSettingsStack The pointer to the pointer to the top stack
2446 * element. This will be used as input and output.
2447 * @param pszDir The directory to do this for.
2448 */
2449static int scmSettingsStackPushDir(PSCMSETTINGS *ppSettingsStack, const char *pszDir)
2450{
2451 char szFile[RTPATH_MAX];
2452 int rc = RTPathJoin(szFile, sizeof(szFile), pszDir, SCM_SETTINGS_FILENAME);
2453 if (RT_SUCCESS(rc))
2454 {
2455 PSCMSETTINGS pSettings;
2456 rc = scmSettingsCreate(&pSettings, &(*ppSettingsStack)->Base);
2457 if (RT_SUCCESS(rc))
2458 {
2459 if (RTFileExists(szFile))
2460 rc = scmSettingsLoadFile(pSettings, szFile);
2461 if (RT_SUCCESS(rc))
2462 {
2463 scmSettingsStackPush(ppSettingsStack, pSettings);
2464 return VINF_SUCCESS;
2465 }
2466
2467 scmSettingsDestroy(pSettings);
2468 }
2469 }
2470 return rc;
2471}
2472
2473
2474/**
2475 * Pops a settings set off the stack.
2476 *
2477 * @returns The popped setttings.
2478 * @param ppSettingsStack The pointer to the pointer to the top stack
2479 * element. This will be used as input and output.
2480 */
2481static PSCMSETTINGS scmSettingsStackPop(PSCMSETTINGS *ppSettingsStack)
2482{
2483 PSCMSETTINGS pRet = *ppSettingsStack;
2484 PSCMSETTINGS pNew = pRet ? pRet->pDown : NULL;
2485 *ppSettingsStack = pNew;
2486 if (pNew)
2487 pNew->pUp = NULL;
2488 if (pRet)
2489 {
2490 pRet->pUp = NULL;
2491 pRet->pDown = NULL;
2492 }
2493 return pRet;
2494}
2495
2496/**
2497 * Pops and destroys the top entry of the stack.
2498 *
2499 * @param ppSettingsStack The pointer to the pointer to the top stack
2500 * element. This will be used as input and output.
2501 */
2502static void scmSettingsStackPopAndDestroy(PSCMSETTINGS *ppSettingsStack)
2503{
2504 scmSettingsDestroy(scmSettingsStackPop(ppSettingsStack));
2505}
2506
2507/**
2508 * Constructs the base settings for the specified file name.
2509 *
2510 * @returns IPRT status code.
2511 * @param pSettingsStack The top element on the settings stack.
2512 * @param pszFilename The file name.
2513 * @param pszBasename The base name (pointer within @a pszFilename).
2514 * @param cchBasename The length of the base name. (For passing to
2515 * RTStrSimplePatternMultiMatch.)
2516 * @param pBase Base settings to initialize.
2517 */
2518static int scmSettingsStackMakeFileBase(PCSCMSETTINGS pSettingsStack, const char *pszFilename,
2519 const char *pszBasename, size_t cchBasename, PSCMSETTINGSBASE pBase)
2520{
2521 int rc = scmSettingsBaseInitAndCopy(pBase, &pSettingsStack->Base);
2522 if (RT_SUCCESS(rc))
2523 {
2524 /* find the bottom entry in the stack. */
2525 PCSCMSETTINGS pCur = pSettingsStack;
2526 while (pCur->pDown)
2527 pCur = pCur->pDown;
2528
2529 /* Work our way up thru the stack and look for matching pairs. */
2530 while (pCur)
2531 {
2532 size_t const cPairs = pCur->cPairs;
2533 if (cPairs)
2534 {
2535 for (size_t i = 0; i < cPairs; i++)
2536 if ( RTStrSimplePatternMultiMatch(pCur->paPairs[i].pszPattern, RTSTR_MAX,
2537 pszBasename, cchBasename, NULL)
2538 || RTStrSimplePatternMultiMatch(pCur->paPairs[i].pszPattern, RTSTR_MAX,
2539 pszFilename, RTSTR_MAX, NULL))
2540 {
2541 rc = scmSettingsBaseParseString(pBase, pCur->paPairs[i].pszOptions);
2542 if (RT_FAILURE(rc))
2543 break;
2544 }
2545 if (RT_FAILURE(rc))
2546 break;
2547 }
2548
2549 /* advance */
2550 pCur = pCur->pUp;
2551 }
2552 }
2553 if (RT_FAILURE(rc))
2554 scmSettingsBaseDelete(pBase);
2555 return rc;
2556}
2557
2558
2559/* -=-=-=-=-=- misc -=-=-=-=-=- */
2560
2561
2562/**
2563 * Prints a verbose message if the level is high enough.
2564 *
2565 * @param pState The rewrite state. Optional.
2566 * @param iLevel The required verbosity level.
2567 * @param pszFormat The message format string. Can be NULL if we
2568 * only want to trigger the per file message.
2569 * @param ... Format arguments.
2570 */
2571static void ScmVerbose(PSCMRWSTATE pState, int iLevel, const char *pszFormat, ...)
2572{
2573 if (iLevel <= g_iVerbosity)
2574 {
2575 if (pState && !pState->fFirst)
2576 {
2577 RTPrintf("%s: info: --= Rewriting '%s' =--\n", g_szProgName, pState->pszFilename);
2578 pState->fFirst = true;
2579 }
2580 if (pszFormat)
2581 {
2582 RTPrintf(pState
2583 ? "%s: info: "
2584 : "%s: info: ",
2585 g_szProgName);
2586 va_list va;
2587 va_start(va, pszFormat);
2588 RTPrintfV(pszFormat, va);
2589 va_end(va);
2590 }
2591 }
2592}
2593
2594
2595/* -=-=-=-=-=- subversion -=-=-=-=-=- */
2596
2597#define SCM_WITHOUT_LIBSVN
2598
2599#ifdef SCM_WITHOUT_LIBSVN
2600
2601/**
2602 * Callback that is call for each path to search.
2603 */
2604static DECLCALLBACK(int) scmSvnFindSvnBinaryCallback(char const *pchPath, size_t cchPath, void *pvUser1, void *pvUser2)
2605{
2606 char *pszDst = (char *)pvUser1;
2607 size_t cchDst = (size_t)pvUser2;
2608 if (cchDst > cchPath)
2609 {
2610 memcpy(pszDst, pchPath, cchPath);
2611 pszDst[cchPath] = '\0';
2612#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2613 int rc = RTPathAppend(pszDst, cchDst, "svn.exe");
2614#else
2615 int rc = RTPathAppend(pszDst, cchDst, "svn");
2616#endif
2617 if ( RT_SUCCESS(rc)
2618 && RTFileExists(pszDst))
2619 return VINF_SUCCESS;
2620 }
2621 return VERR_TRY_AGAIN;
2622}
2623
2624
2625/**
2626 * Finds the svn binary.
2627 *
2628 * @param pszPath Where to store it. Worst case, we'll return
2629 * "svn" here.
2630 * @param cchPath The size of the buffer pointed to by @a pszPath.
2631 */
2632static void scmSvnFindSvnBinary(char *pszPath, size_t cchPath)
2633{
2634 /** @todo code page fun... */
2635 Assert(cchPath >= sizeof("svn"));
2636#ifdef RT_OS_WINDOWS
2637 const char *pszEnvVar = RTEnvGet("Path");
2638#else
2639 const char *pszEnvVar = RTEnvGet("PATH");
2640#endif
2641 if (pszPath)
2642 {
2643#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
2644 int rc = RTPathTraverseList(pszEnvVar, ';', scmSvnFindSvnBinaryCallback, pszPath, (void *)cchPath);
2645#else
2646 int rc = RTPathTraverseList(pszEnvVar, ':', scmSvnFindSvnBinaryCallback, pszPath, (void *)cchPath);
2647#endif
2648 if (RT_SUCCESS(rc))
2649 return;
2650 }
2651 strcpy(pszPath, "svn");
2652}
2653
2654
2655/**
2656 * Construct a dot svn filename for the file being rewritten.
2657 *
2658 * @returns IPRT status code.
2659 * @param pState The rewrite state (for the name).
2660 * @param pszDir The directory, including ".svn/".
2661 * @param pszSuff The filename suffix.
2662 * @param pszDst The output buffer. RTPATH_MAX in size.
2663 */
2664static int scmSvnConstructName(PSCMRWSTATE pState, const char *pszDir, const char *pszSuff, char *pszDst)
2665{
2666 strcpy(pszDst, pState->pszFilename); /* ASSUMES sizeof(szBuf) <= sizeof(szPath) */
2667 RTPathStripFilename(pszDst);
2668
2669 int rc = RTPathAppend(pszDst, RTPATH_MAX, pszDir);
2670 if (RT_SUCCESS(rc))
2671 {
2672 rc = RTPathAppend(pszDst, RTPATH_MAX, RTPathFilename(pState->pszFilename));
2673 if (RT_SUCCESS(rc))
2674 {
2675 size_t cchDst = strlen(pszDst);
2676 size_t cchSuff = strlen(pszSuff);
2677 if (cchDst + cchSuff < RTPATH_MAX)
2678 {
2679 memcpy(&pszDst[cchDst], pszSuff, cchSuff + 1);
2680 return VINF_SUCCESS;
2681 }
2682 else
2683 rc = VERR_BUFFER_OVERFLOW;
2684 }
2685 }
2686 return rc;
2687}
2688
2689/**
2690 * Interprets the specified string as decimal numbers.
2691 *
2692 * @returns true if parsed successfully, false if not.
2693 * @param pch The string (not terminated).
2694 * @param cch The string length.
2695 * @param pu Where to return the value.
2696 */
2697static bool scmSvnReadNumber(const char *pch, size_t cch, size_t *pu)
2698{
2699 size_t u = 0;
2700 while (cch-- > 0)
2701 {
2702 char ch = *pch++;
2703 if (ch < '0' || ch > '9')
2704 return false;
2705 u *= 10;
2706 u += ch - '0';
2707 }
2708 *pu = u;
2709 return true;
2710}
2711
2712#endif /* SCM_WITHOUT_LIBSVN */
2713
2714/**
2715 * Checks if the file we're operating on is part of a SVN working copy.
2716 *
2717 * @returns true if it is, false if it isn't or we cannot tell.
2718 * @param pState The rewrite state to work on.
2719 */
2720static bool scmSvnIsInWorkingCopy(PSCMRWSTATE pState)
2721{
2722#ifdef SCM_WITHOUT_LIBSVN
2723 /*
2724 * Hack: check if the .svn/text-base/<file>.svn-base file exists.
2725 */
2726 char szPath[RTPATH_MAX];
2727 int rc = scmSvnConstructName(pState, ".svn/text-base/", ".svn-base", szPath);
2728 if (RT_SUCCESS(rc))
2729 return RTFileExists(szPath);
2730
2731#else
2732 NOREF(pState);
2733#endif
2734 return false;
2735}
2736
2737/**
2738 * Queries the value of an SVN property.
2739 *
2740 * This will automatically adjust for scheduled changes.
2741 *
2742 * @returns IPRT status code.
2743 * @retval VERR_INVALID_STATE if not a SVN WC file.
2744 * @retval VERR_NOT_FOUND if the property wasn't found.
2745 * @param pState The rewrite state to work on.
2746 * @param pszName The property name.
2747 * @param ppszValue Where to return the property value. Free this
2748 * using RTStrFree. Optional.
2749 */
2750static int scmSvnQueryProperty(PSCMRWSTATE pState, const char *pszName, char **ppszValue)
2751{
2752 /*
2753 * Look it up in the scheduled changes.
2754 */
2755 uint32_t i = pState->cSvnPropChanges;
2756 while (i-- > 0)
2757 if (!strcmp(pState->paSvnPropChanges[i].pszName, pszName))
2758 {
2759 const char *pszValue = pState->paSvnPropChanges[i].pszValue;
2760 if (!pszValue)
2761 return VERR_NOT_FOUND;
2762 if (ppszValue)
2763 return RTStrDupEx(ppszValue, pszValue);
2764 return VINF_SUCCESS;
2765 }
2766
2767#ifdef SCM_WITHOUT_LIBSVN
2768 /*
2769 * Hack: Read the .svn/props/<file>.svn-work file exists.
2770 */
2771 char szPath[RTPATH_MAX];
2772 int rc = scmSvnConstructName(pState, ".svn/props/", ".svn-work", szPath);
2773 if (RT_SUCCESS(rc) && !RTFileExists(szPath))
2774 rc = scmSvnConstructName(pState, ".svn/prop-base/", ".svn-base", szPath);
2775 if (RT_SUCCESS(rc))
2776 {
2777 SCMSTREAM Stream;
2778 rc = ScmStreamInitForReading(&Stream, szPath);
2779 if (RT_SUCCESS(rc))
2780 {
2781 /*
2782 * The current format is K len\n<name>\nV len\n<value>\n" ... END.
2783 */
2784 rc = VERR_NOT_FOUND;
2785 size_t const cchName = strlen(pszName);
2786 SCMEOL enmEol;
2787 size_t cchLine;
2788 const char *pchLine;
2789 while ((pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol)) != NULL)
2790 {
2791 /*
2792 * Parse the 'K num' / 'END' line.
2793 */
2794 if ( cchLine == 3
2795 && !memcmp(pchLine, "END", 3))
2796 break;
2797 size_t cchKey;
2798 if ( cchLine < 3
2799 || pchLine[0] != 'K'
2800 || pchLine[1] != ' '
2801 || !scmSvnReadNumber(&pchLine[2], cchLine - 2, &cchKey)
2802 || cchKey == 0
2803 || cchKey > 4096)
2804 {
2805 RTMsgError("%s:%u: Unexpected data '%.*s'\n", szPath, ScmStreamTellLine(&Stream), cchLine, pchLine);
2806 rc = VERR_PARSE_ERROR;
2807 break;
2808 }
2809
2810 /*
2811 * Match the key and skip to the value line. Don't bother with
2812 * names containing EOL markers.
2813 */
2814 size_t const offKey = ScmStreamTell(&Stream);
2815 bool fMatch = cchName == cchKey;
2816 if (fMatch)
2817 {
2818 pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol);
2819 if (!pchLine)
2820 break;
2821 fMatch = cchLine == cchName
2822 && !memcmp(pchLine, pszName, cchName);
2823 }
2824
2825 if (RT_FAILURE(ScmStreamSeekAbsolute(&Stream, offKey + cchKey)))
2826 break;
2827 if (RT_FAILURE(ScmStreamSeekByLine(&Stream, ScmStreamTellLine(&Stream) + 1)))
2828 break;
2829
2830 /*
2831 * Read and Parse the 'V num' line.
2832 */
2833 pchLine = ScmStreamGetLine(&Stream, &cchLine, &enmEol);
2834 if (!pchLine)
2835 break;
2836 size_t cchValue;
2837 if ( cchLine < 3
2838 || pchLine[0] != 'V'
2839 || pchLine[1] != ' '
2840 || !scmSvnReadNumber(&pchLine[2], cchLine - 2, &cchValue)
2841 || cchValue == 0
2842 || cchValue > _1M)
2843 {
2844 RTMsgError("%s:%u: Unexpected data '%.*s'\n", szPath, ScmStreamTellLine(&Stream), cchLine, pchLine);
2845 rc = VERR_PARSE_ERROR;
2846 break;
2847 }
2848
2849 /*
2850 * If we have a match, allocate a return buffer and read the
2851 * value into it. Otherwise skip this value and continue
2852 * searching.
2853 */
2854 if (fMatch)
2855 {
2856 if (!ppszValue)
2857 rc = VINF_SUCCESS;
2858 else
2859 {
2860 char *pszValue;
2861 rc = RTStrAllocEx(&pszValue, cchValue + 1);
2862 if (RT_SUCCESS(rc))
2863 {
2864 rc = ScmStreamRead(&Stream, pszValue, cchValue);
2865 if (RT_SUCCESS(rc))
2866 *ppszValue = pszValue;
2867 else
2868 RTStrFree(pszValue);
2869 }
2870 }
2871 break;
2872 }
2873
2874 if (RT_FAILURE(ScmStreamSeekRelative(&Stream, cchValue)))
2875 break;
2876 if (RT_FAILURE(ScmStreamSeekByLine(&Stream, ScmStreamTellLine(&Stream) + 1)))
2877 break;
2878 }
2879
2880 if (RT_FAILURE(ScmStreamGetStatus(&Stream)))
2881 {
2882 rc = ScmStreamGetStatus(&Stream);
2883 RTMsgError("%s: stream error %Rrc\n", szPath, rc);
2884 }
2885 ScmStreamDelete(&Stream);
2886 }
2887 }
2888
2889 if (rc == VERR_FILE_NOT_FOUND)
2890 rc = VERR_NOT_FOUND;
2891 return rc;
2892
2893#else
2894 NOREF(pState);
2895#endif
2896 return VERR_NOT_FOUND;
2897}
2898
2899
2900/**
2901 * Schedules the setting of a property.
2902 *
2903 * @returns IPRT status code.
2904 * @retval VERR_INVALID_STATE if not a SVN WC file.
2905 * @param pState The rewrite state to work on.
2906 * @param pszName The name of the property to set.
2907 * @param pszValue The value. NULL means deleting it.
2908 */
2909static int scmSvnSetProperty(PSCMRWSTATE pState, const char *pszName, const char *pszValue)
2910{
2911 /*
2912 * Update any existing entry first.
2913 */
2914 size_t i = pState->cSvnPropChanges;
2915 while (i-- > 0)
2916 if (!strcmp(pState->paSvnPropChanges[i].pszName, pszName))
2917 {
2918 if (!pszValue)
2919 {
2920 RTStrFree(pState->paSvnPropChanges[i].pszValue);
2921 pState->paSvnPropChanges[i].pszValue = NULL;
2922 }
2923 else
2924 {
2925 char *pszCopy;
2926 int rc = RTStrDupEx(&pszCopy, pszValue);
2927 if (RT_FAILURE(rc))
2928 return rc;
2929 pState->paSvnPropChanges[i].pszValue = pszCopy;
2930 }
2931 return VINF_SUCCESS;
2932 }
2933
2934 /*
2935 * Insert a new entry.
2936 */
2937 i = pState->cSvnPropChanges;
2938 if ((i % 32) == 0)
2939 {
2940 void *pvNew = RTMemRealloc(pState->paSvnPropChanges, (i + 32) * sizeof(SCMSVNPROP));
2941 if (!pvNew)
2942 return VERR_NO_MEMORY;
2943 pState->paSvnPropChanges = (PSCMSVNPROP)pvNew;
2944 }
2945
2946 pState->paSvnPropChanges[i].pszName = RTStrDup(pszName);
2947 pState->paSvnPropChanges[i].pszValue = pszValue ? RTStrDup(pszValue) : NULL;
2948 if ( pState->paSvnPropChanges[i].pszName
2949 && (pState->paSvnPropChanges[i].pszValue || !pszValue) )
2950 pState->cSvnPropChanges = i + 1;
2951 else
2952 {
2953 RTStrFree(pState->paSvnPropChanges[i].pszName);
2954 pState->paSvnPropChanges[i].pszName = NULL;
2955 RTStrFree(pState->paSvnPropChanges[i].pszValue);
2956 pState->paSvnPropChanges[i].pszValue = NULL;
2957 return VERR_NO_MEMORY;
2958 }
2959 return VINF_SUCCESS;
2960}
2961
2962
2963/**
2964 * Schedules a property deletion.
2965 *
2966 * @returns IPRT status code.
2967 * @param pState The rewrite state to work on.
2968 * @param pszName The name of the property to delete.
2969 */
2970static int scmSvnDelProperty(PSCMRWSTATE pState, const char *pszName)
2971{
2972 return scmSvnSetProperty(pState, pszName, NULL);
2973}
2974
2975
2976/**
2977 * Applies any SVN property changes to the work copy of the file.
2978 *
2979 * @returns IPRT status code.
2980 * @param pState The rewrite state which SVN property changes
2981 * should be applied.
2982 */
2983static int scmSvnDisplayChanges(PSCMRWSTATE pState)
2984{
2985 size_t i = pState->cSvnPropChanges;
2986 while (i-- > 0)
2987 {
2988 const char *pszName = pState->paSvnPropChanges[i].pszName;
2989 const char *pszValue = pState->paSvnPropChanges[i].pszValue;
2990 if (pszValue)
2991 ScmVerbose(pState, 0, "svn ps '%s' '%s' %s\n", pszName, pszValue, pState->pszFilename);
2992 else
2993 ScmVerbose(pState, 0, "svn pd '%s' %s\n", pszName, pszValue, pState->pszFilename);
2994 }
2995
2996 return VINF_SUCCESS;
2997}
2998
2999/**
3000 * Applies any SVN property changes to the work copy of the file.
3001 *
3002 * @returns IPRT status code.
3003 * @param pState The rewrite state which SVN property changes
3004 * should be applied.
3005 */
3006static int scmSvnApplyChanges(PSCMRWSTATE pState)
3007{
3008#ifdef SCM_WITHOUT_LIBSVN
3009 /*
3010 * This sucks. We gotta find svn(.exe).
3011 */
3012 static char s_szSvnPath[RTPATH_MAX];
3013 if (s_szSvnPath[0] == '\0')
3014 scmSvnFindSvnBinary(s_szSvnPath, sizeof(s_szSvnPath));
3015
3016 /*
3017 * Iterate thru the changes and apply them by starting the svn client.
3018 */
3019 for (size_t i = 0; i <pState->cSvnPropChanges; i++)
3020 {
3021 const char *apszArgv[6];
3022 apszArgv[0] = s_szSvnPath;
3023 apszArgv[1] = pState->paSvnPropChanges[i].pszValue ? "ps" : "pd";
3024 apszArgv[2] = pState->paSvnPropChanges[i].pszName;
3025 int iArg = 3;
3026 if (pState->paSvnPropChanges[i].pszValue)
3027 apszArgv[iArg++] = pState->paSvnPropChanges[i].pszValue;
3028 apszArgv[iArg++] = pState->pszFilename;
3029 apszArgv[iArg++] = NULL;
3030 ScmVerbose(pState, 2, "executing: %s %s %s %s %s\n",
3031 apszArgv[0], apszArgv[1], apszArgv[2], apszArgv[3], apszArgv[4]);
3032
3033 RTPROCESS pid;
3034 int rc = RTProcCreate(s_szSvnPath, apszArgv, RTENV_DEFAULT, 0 /*fFlags*/, &pid);
3035 if (RT_SUCCESS(rc))
3036 {
3037 RTPROCSTATUS Status;
3038 rc = RTProcWait(pid, RTPROCWAIT_FLAGS_BLOCK, &Status);
3039 if ( RT_SUCCESS(rc)
3040 && ( Status.enmReason != RTPROCEXITREASON_NORMAL
3041 || Status.iStatus != 0) )
3042 {
3043 RTMsgError("%s: %s %s %s %s %s -> %s %u\n",
3044 pState->pszFilename, apszArgv[0], apszArgv[1], apszArgv[2], apszArgv[3], apszArgv[4],
3045 Status.enmReason == RTPROCEXITREASON_NORMAL ? "exit code"
3046 : Status.enmReason == RTPROCEXITREASON_SIGNAL ? "signal"
3047 : Status.enmReason == RTPROCEXITREASON_ABEND ? "abnormal end"
3048 : "abducted by alien",
3049 Status.iStatus);
3050 return VERR_GENERAL_FAILURE;
3051 }
3052 }
3053 if (RT_FAILURE(rc))
3054 {
3055 RTMsgError("%s: error executing %s %s %s %s %s: %Rrc\n",
3056 pState->pszFilename, apszArgv[0], apszArgv[1], apszArgv[2], apszArgv[3], apszArgv[4], rc);
3057 return rc;
3058 }
3059 }
3060
3061 return VINF_SUCCESS;
3062#else
3063 return VERR_NOT_IMPLEMENTED;
3064#endif
3065}
3066
3067
3068/* -=-=-=-=-=- rewriters -=-=-=-=-=- */
3069
3070
3071/**
3072 * Strip trailing blanks (space & tab).
3073 *
3074 * @returns True if modified, false if not.
3075 * @param pIn The input stream.
3076 * @param pOut The output stream.
3077 * @param pSettings The settings.
3078 */
3079static bool rewrite_StripTrailingBlanks(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3080{
3081 if (!pSettings->fStripTrailingBlanks)
3082 return false;
3083
3084 bool fModified = false;
3085 SCMEOL enmEol;
3086 size_t cchLine;
3087 const char *pchLine;
3088 while ((pchLine = ScmStreamGetLine(pIn, &cchLine, &enmEol)) != NULL)
3089 {
3090 int rc;
3091 if ( cchLine == 0
3092 || !RT_C_IS_BLANK(pchLine[cchLine - 1]) )
3093 rc = ScmStreamPutLine(pOut, pchLine, cchLine, enmEol);
3094 else
3095 {
3096 cchLine--;
3097 while (cchLine > 0 && RT_C_IS_BLANK(pchLine[cchLine - 1]))
3098 cchLine--;
3099 rc = ScmStreamPutLine(pOut, pchLine, cchLine, enmEol);
3100 fModified = true;
3101 }
3102 if (RT_FAILURE(rc))
3103 return false;
3104 }
3105 if (fModified)
3106 ScmVerbose(pState, 2, " * Stripped trailing blanks\n");
3107 return fModified;
3108}
3109
3110/**
3111 * Expand tabs.
3112 *
3113 * @returns True if modified, false if not.
3114 * @param pIn The input stream.
3115 * @param pOut The output stream.
3116 * @param pSettings The settings.
3117 */
3118static bool rewrite_ExpandTabs(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3119{
3120 if (!pSettings->fConvertTabs)
3121 return false;
3122
3123 size_t const cchTab = pSettings->cchTab;
3124 bool fModified = false;
3125 SCMEOL enmEol;
3126 size_t cchLine;
3127 const char *pchLine;
3128 while ((pchLine = ScmStreamGetLine(pIn, &cchLine, &enmEol)) != NULL)
3129 {
3130 int rc;
3131 const char *pchTab = (const char *)memchr(pchLine, '\t', cchLine);
3132 if (!pchTab)
3133 rc = ScmStreamPutLine(pOut, pchLine, cchLine, enmEol);
3134 else
3135 {
3136 size_t offTab = 0;
3137 const char *pchChunk = pchLine;
3138 for (;;)
3139 {
3140 size_t cchChunk = pchTab - pchChunk;
3141 offTab += cchChunk;
3142 ScmStreamWrite(pOut, pchChunk, cchChunk);
3143
3144 size_t cchToTab = cchTab - offTab % cchTab;
3145 ScmStreamWrite(pOut, g_szTabSpaces, cchToTab);
3146 offTab += cchToTab;
3147
3148 pchChunk = pchTab + 1;
3149 size_t cchLeft = cchLine - (pchChunk - pchLine);
3150 pchTab = (const char *)memchr(pchChunk, '\t', cchLeft);
3151 if (!pchTab)
3152 {
3153 rc = ScmStreamPutLine(pOut, pchChunk, cchLeft, enmEol);
3154 break;
3155 }
3156 }
3157
3158 fModified = true;
3159 }
3160 if (RT_FAILURE(rc))
3161 return false;
3162 }
3163 if (fModified)
3164 ScmVerbose(pState, 2, " * Expanded tabs\n");
3165 return fModified;
3166}
3167
3168/**
3169 * Worker for rewrite_ForceNativeEol, rewrite_ForceLF and rewrite_ForceCRLF.
3170 *
3171 * @returns true if modifications were made, false if not.
3172 * @param pIn The input stream.
3173 * @param pOut The output stream.
3174 * @param pSettings The settings.
3175 * @param enmDesiredEol The desired end of line indicator type.
3176 * @param pszDesiredSvnEol The desired svn:eol-style.
3177 */
3178static bool rewrite_ForceEol(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings,
3179 SCMEOL enmDesiredEol, const char *pszDesiredSvnEol)
3180{
3181 if (!pSettings->fConvertEol)
3182 return false;
3183
3184 bool fModified = false;
3185 SCMEOL enmEol;
3186 size_t cchLine;
3187 const char *pchLine;
3188 while ((pchLine = ScmStreamGetLine(pIn, &cchLine, &enmEol)) != NULL)
3189 {
3190 if ( enmEol != enmDesiredEol
3191 && enmEol != SCMEOL_NONE)
3192 {
3193 fModified = true;
3194 enmEol = enmDesiredEol;
3195 }
3196 int rc = ScmStreamPutLine(pOut, pchLine, cchLine, enmEol);
3197 if (RT_FAILURE(rc))
3198 return false;
3199 }
3200 if (fModified)
3201 ScmVerbose(pState, 2, " * Converted EOL markers\n");
3202
3203 /* Check svn:eol-style if appropriate */
3204 if ( pSettings->fSetSvnEol
3205 && scmSvnIsInWorkingCopy(pState))
3206 {
3207 char *pszEol;
3208 int rc = scmSvnQueryProperty(pState, "svn:eol-style", &pszEol);
3209 if ( (RT_SUCCESS(rc) && strcmp(pszEol, pszDesiredSvnEol))
3210 || rc == VERR_NOT_FOUND)
3211 {
3212 if (rc == VERR_NOT_FOUND)
3213 ScmVerbose(pState, 2, " * Settings svn:eol-style to %s (missing)\n", pszDesiredSvnEol);
3214 else
3215 ScmVerbose(pState, 2, " * Settings svn:eol-style to %s (was: %s)\n", pszDesiredSvnEol, pszEol);
3216 rc = scmSvnSetProperty(pState, "svn:eol-style", pszDesiredSvnEol);
3217 if (RT_FAILURE(rc))
3218 RTMsgError("scmSvnSetProperty: %Rrc\n", rc); /** @todo propagate the error somehow... */
3219 }
3220 }
3221
3222 /** @todo also check the subversion svn:eol-style state! */
3223 return fModified;
3224}
3225
3226/**
3227 * Force native end of line indicator.
3228 *
3229 * @returns true if modifications were made, false if not.
3230 * @param pIn The input stream.
3231 * @param pOut The output stream.
3232 * @param pSettings The settings.
3233 */
3234static bool rewrite_ForceNativeEol(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3235{
3236#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
3237 return rewrite_ForceEol(pState, pIn, pOut, pSettings, SCMEOL_CRLF, "native");
3238#else
3239 return rewrite_ForceEol(pState, pIn, pOut, pSettings, SCMEOL_LF, "native");
3240#endif
3241}
3242
3243/**
3244 * Force the stream to use LF as the end of line indicator.
3245 *
3246 * @returns true if modifications were made, false if not.
3247 * @param pIn The input stream.
3248 * @param pOut The output stream.
3249 * @param pSettings The settings.
3250 */
3251static bool rewrite_ForceLF(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3252{
3253 return rewrite_ForceEol(pState, pIn, pOut, pSettings, SCMEOL_LF, "LF");
3254}
3255
3256/**
3257 * Force the stream to use CRLF as the end of line indicator.
3258 *
3259 * @returns true if modifications were made, false if not.
3260 * @param pIn The input stream.
3261 * @param pOut The output stream.
3262 * @param pSettings The settings.
3263 */
3264static bool rewrite_ForceCRLF(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3265{
3266 return rewrite_ForceEol(pState, pIn, pOut, pSettings, SCMEOL_CRLF, "CRLF");
3267}
3268
3269/**
3270 * Strip trailing blank lines and/or make sure there is exactly one blank line
3271 * at the end of the file.
3272 *
3273 * @returns true if modifications were made, false if not.
3274 * @param pIn The input stream.
3275 * @param pOut The output stream.
3276 * @param pSettings The settings.
3277 *
3278 * @remarks ASSUMES trailing white space has been removed already.
3279 */
3280static bool rewrite_AdjustTrailingLines(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3281{
3282 if ( !pSettings->fStripTrailingLines
3283 && !pSettings->fForceTrailingLine
3284 && !pSettings->fForceFinalEol)
3285 return false;
3286
3287 size_t const cLines = ScmStreamCountLines(pIn);
3288
3289 /* Empty files remains empty. */
3290 if (cLines <= 1)
3291 return false;
3292
3293 /* Figure out if we need to adjust the number of lines or not. */
3294 size_t cLinesNew = cLines;
3295
3296 if ( pSettings->fStripTrailingLines
3297 && ScmStreamIsWhiteLine(pIn, cLinesNew - 1))
3298 {
3299 while ( cLinesNew > 1
3300 && ScmStreamIsWhiteLine(pIn, cLinesNew - 2))
3301 cLinesNew--;
3302 }
3303
3304 if ( pSettings->fForceTrailingLine
3305 && !ScmStreamIsWhiteLine(pIn, cLinesNew - 1))
3306 cLinesNew++;
3307
3308 bool fFixMissingEol = pSettings->fForceFinalEol
3309 && ScmStreamGetEolByLine(pIn, cLinesNew - 1) == SCMEOL_NONE;
3310
3311 if ( !fFixMissingEol
3312 && cLines == cLinesNew)
3313 return false;
3314
3315 /* Copy the number of lines we've arrived at. */
3316 ScmStreamRewindForReading(pIn);
3317
3318 size_t cCopied = RT_MIN(cLinesNew, cLines);
3319 ScmStreamCopyLines(pOut, pIn, cCopied);
3320
3321 if (cCopied != cLinesNew)
3322 {
3323 while (cCopied++ < cLinesNew)
3324 ScmStreamPutLine(pOut, "", 0, ScmStreamGetEol(pIn));
3325 }
3326 /* Fix missing EOL if required. */
3327 else if (fFixMissingEol)
3328 {
3329 if (ScmStreamGetEol(pIn) == SCMEOL_LF)
3330 ScmStreamWrite(pOut, "\n", 1);
3331 else
3332 ScmStreamWrite(pOut, "\r\n", 2);
3333 }
3334
3335 ScmVerbose(pState, 2, " * Adjusted trailing blank lines\n");
3336 return true;
3337}
3338
3339/**
3340 * Makefile.kup are empty files, enforce this.
3341 *
3342 * @returns true if modifications were made, false if not.
3343 * @param pIn The input stream.
3344 * @param pOut The output stream.
3345 * @param pSettings The settings.
3346 */
3347static bool rewrite_Makefile_kup(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3348{
3349 /* These files should be zero bytes. */
3350 if (pIn->cb == 0)
3351 return false;
3352 ScmVerbose(pState, 2, " * Truncated file to zero bytes\n");
3353 return true;
3354}
3355
3356/**
3357 * Rewrite a kBuild makefile.
3358 *
3359 * @returns true if modifications were made, false if not.
3360 * @param pIn The input stream.
3361 * @param pOut The output stream.
3362 * @param pSettings The settings.
3363 *
3364 * @todo
3365 *
3366 * Ideas for Makefile.kmk and Config.kmk:
3367 * - sort if1of/ifn1of sets.
3368 * - line continuation slashes should only be preceeded by one space.
3369 */
3370static bool rewrite_Makefile_kmk(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3371{
3372 return false;
3373}
3374
3375/**
3376 * Rewrite a C/C++ source or header file.
3377 *
3378 * @returns true if modifications were made, false if not.
3379 * @param pIn The input stream.
3380 * @param pOut The output stream.
3381 * @param pSettings The settings.
3382 *
3383 * @todo
3384 *
3385 * Ideas for C/C++:
3386 * - space after if, while, for, switch
3387 * - spaces in for (i=0;i<x;i++)
3388 * - complex conditional, bird style.
3389 * - remove unnecessary parentheses.
3390 * - sort defined RT_OS_*|| and RT_ARCH
3391 * - sizeof without parenthesis.
3392 * - defined without parenthesis.
3393 * - trailing spaces.
3394 * - parameter indentation.
3395 * - space after comma.
3396 * - while (x--); -> multi line + comment.
3397 * - else statement;
3398 * - space between function and left parenthesis.
3399 * - TODO, XXX, @todo cleanup.
3400 * - Space before/after '*'.
3401 * - ensure new line at end of file.
3402 * - Indentation of precompiler statements (#ifdef, #defines).
3403 * - space between functions.
3404 */
3405static bool rewrite_C_and_CPP(PSCMRWSTATE pState, PSCMSTREAM pIn, PSCMSTREAM pOut, PCSCMSETTINGSBASE pSettings)
3406{
3407
3408 return false;
3409}
3410
3411/* -=-=-=-=-=- file and directory processing -=-=-=-=-=- */
3412
3413/**
3414 * Processes a file.
3415 *
3416 * @returns IPRT status code.
3417 * @param pState The rewriter state.
3418 * @param pszFilename The file name.
3419 * @param pszBasename The base name (pointer within @a pszFilename).
3420 * @param cchBasename The length of the base name. (For passing to
3421 * RTStrSimplePatternMultiMatch.)
3422 * @param pBaseSettings The base settings to use. It's OK to modify
3423 * these.
3424 */
3425static int scmProcessFileInner(PSCMRWSTATE pState, const char *pszFilename, const char *pszBasename, size_t cchBasename,
3426 PSCMSETTINGSBASE pBaseSettings)
3427{
3428 /*
3429 * Do the file level filtering.
3430 */
3431 if ( pBaseSettings->pszFilterFiles
3432 && *pBaseSettings->pszFilterFiles
3433 && !RTStrSimplePatternMultiMatch(pBaseSettings->pszFilterFiles, RTSTR_MAX, pszBasename, cchBasename, NULL))
3434 {
3435 ScmVerbose(NULL, 5, "skipping '%s': file filter mismatch\n", pszFilename);
3436 return VINF_SUCCESS;
3437 }
3438 if ( pBaseSettings->pszFilterOutFiles
3439 && *pBaseSettings->pszFilterOutFiles
3440 && ( RTStrSimplePatternMultiMatch(pBaseSettings->pszFilterOutFiles, RTSTR_MAX, pszBasename, cchBasename, NULL)
3441 || RTStrSimplePatternMultiMatch(pBaseSettings->pszFilterOutFiles, RTSTR_MAX, pszFilename, RTSTR_MAX, NULL)) )
3442 {
3443 ScmVerbose(NULL, 5, "skipping '%s': filterd out\n", pszFilename);
3444 return VINF_SUCCESS;
3445 }
3446 if ( pBaseSettings->fOnlySvnFiles
3447 && !scmSvnIsInWorkingCopy(pState))
3448 {
3449 ScmVerbose(NULL, 5, "skipping '%s': not in SVN WC\n", pszFilename);
3450 return VINF_SUCCESS;
3451 }
3452
3453 /*
3454 * Try find a matching rewrite config for this filename.
3455 */
3456 PCSCMCFGENTRY pCfg = NULL;
3457 for (size_t iCfg = 0; iCfg < RT_ELEMENTS(g_aConfigs); iCfg++)
3458 if (RTStrSimplePatternMultiMatch(g_aConfigs[iCfg].pszFilePattern, RTSTR_MAX, pszBasename, cchBasename, NULL))
3459 {
3460 pCfg = &g_aConfigs[iCfg];
3461 break;
3462 }
3463 if (!pCfg)
3464 {
3465 ScmVerbose(NULL, 4, "skipping '%s': no rewriters configured\n", pszFilename);
3466 return VINF_SUCCESS;
3467 }
3468 ScmVerbose(pState, 4, "matched \"%s\"\n", pCfg->pszFilePattern);
3469
3470 /*
3471 * Create an input stream from the file and check that it's text.
3472 */
3473 SCMSTREAM Stream1;
3474 int rc = ScmStreamInitForReading(&Stream1, pszFilename);
3475 if (RT_FAILURE(rc))
3476 {
3477 RTMsgError("Failed to read '%s': %Rrc\n", pszFilename, rc);
3478 return rc;
3479 }
3480 if (ScmStreamIsText(&Stream1))
3481 {
3482 ScmVerbose(pState, 3, NULL);
3483
3484 /*
3485 * Gather SCM and editor settings from the stream.
3486 */
3487 rc = scmSettingsBaseLoadFromDocument(pBaseSettings, &Stream1);
3488 if (RT_SUCCESS(rc))
3489 {
3490 ScmStreamRewindForReading(&Stream1);
3491
3492 /*
3493 * Create two more streams for output and push the text thru all the
3494 * rewriters, switching the two streams around when something is
3495 * actually rewritten. Stream1 remains unchanged.
3496 */
3497 SCMSTREAM Stream2;
3498 rc = ScmStreamInitForWriting(&Stream2, &Stream1);
3499 if (RT_SUCCESS(rc))
3500 {
3501 SCMSTREAM Stream3;
3502 rc = ScmStreamInitForWriting(&Stream3, &Stream1);
3503 if (RT_SUCCESS(rc))
3504 {
3505 bool fModified = false;
3506 PSCMSTREAM pIn = &Stream1;
3507 PSCMSTREAM pOut = &Stream2;
3508 for (size_t iRw = 0; iRw < pCfg->cRewriters; iRw++)
3509 {
3510 bool fRc = pCfg->papfnRewriter[iRw](pState, pIn, pOut, pBaseSettings);
3511 if (fRc)
3512 {
3513 PSCMSTREAM pTmp = pOut;
3514 pOut = pIn == &Stream1 ? &Stream3 : pIn;
3515 pIn = pTmp;
3516 fModified = true;
3517 }
3518 ScmStreamRewindForReading(pIn);
3519 ScmStreamRewindForWriting(pOut);
3520 }
3521
3522 rc = ScmStreamGetStatus(&Stream1);
3523 if (RT_SUCCESS(rc))
3524 rc = ScmStreamGetStatus(&Stream2);
3525 if (RT_SUCCESS(rc))
3526 rc = ScmStreamGetStatus(&Stream3);
3527 if (RT_SUCCESS(rc))
3528 {
3529 /*
3530 * If rewritten, write it back to disk.
3531 */
3532 if (fModified)
3533 {
3534 if (!g_fDryRun)
3535 {
3536 ScmVerbose(pState, 1, "writing modified file to \"%s%s\"\n", pszFilename, g_pszChangedSuff);
3537 rc = ScmStreamWriteToFile(pIn, "%s%s", pszFilename, g_pszChangedSuff);
3538 if (RT_FAILURE(rc))
3539 RTMsgError("Error writing '%s%s': %Rrc\n", pszFilename, g_pszChangedSuff, rc);
3540 }
3541 else
3542 {
3543 ScmVerbose(pState, 1, NULL);
3544 ScmDiffStreams(pszFilename, &Stream1, pIn, g_fDiffIgnoreEol, g_fDiffIgnoreLeadingWS,
3545 g_fDiffIgnoreTrailingWS, g_fDiffSpecialChars, pBaseSettings->cchTab, g_pStdOut);
3546 ScmVerbose(pState, 3, "would have modified the file \"%s%s\"\n", pszFilename, g_pszChangedSuff);
3547 scmSvnDisplayChanges(pState);
3548 }
3549 }
3550
3551 /*
3552 * If pending SVN property changes, apply them.
3553 */
3554 if (pState->cSvnPropChanges && RT_SUCCESS(rc))
3555 {
3556 if (!g_fDryRun)
3557 {
3558 rc = scmSvnApplyChanges(pState);
3559 if (RT_FAILURE(rc))
3560 RTMsgError("%s: failed to apply SVN property changes (%Rrc)\n", pszFilename, rc);
3561 }
3562 else
3563 scmSvnDisplayChanges(pState);
3564 }
3565
3566 if (!fModified && !pState->cSvnPropChanges);
3567 ScmVerbose(pState, 3, "no change\n", pszFilename);
3568 }
3569 else
3570 RTMsgError("%s: stream error %Rrc\n", pszFilename);
3571 ScmStreamDelete(&Stream3);
3572 }
3573 else
3574 RTMsgError("Failed to init stream for writing: %Rrc\n", rc);
3575 ScmStreamDelete(&Stream2);
3576 }
3577 else
3578 RTMsgError("Failed to init stream for writing: %Rrc\n", rc);
3579 }
3580 else
3581 RTMsgError("scmSettingsBaseLoadFromDocument: %Rrc\n", rc);
3582 }
3583 else
3584 ScmVerbose(pState, 4, "not text file: \"%s\"\n", pszFilename);
3585 ScmStreamDelete(&Stream1);
3586
3587 return rc;
3588}
3589
3590/**
3591 * Processes a file.
3592 *
3593 * This is just a wrapper for scmProcessFileInner for avoid wasting stack in the
3594 * directory recursion method.
3595 *
3596 * @returns IPRT status code.
3597 * @param pszFilename The file name.
3598 * @param pszBasename The base name (pointer within @a pszFilename).
3599 * @param cchBasename The length of the base name. (For passing to
3600 * RTStrSimplePatternMultiMatch.)
3601 * @param pSettingsStack The settings stack (pointer to the top element).
3602 */
3603static int scmProcessFile(const char *pszFilename, const char *pszBasename, size_t cchBasename,
3604 PSCMSETTINGS pSettingsStack)
3605{
3606 SCMSETTINGSBASE Base;
3607 int rc = scmSettingsStackMakeFileBase(pSettingsStack, pszFilename, pszBasename, cchBasename, &Base);
3608 if (RT_SUCCESS(rc))
3609 {
3610 SCMRWSTATE State;
3611 State.fFirst = false;
3612 State.pszFilename = pszFilename;
3613 State.cSvnPropChanges = 0;
3614 State.paSvnPropChanges = NULL;
3615
3616 rc = scmProcessFileInner(&State, pszFilename, pszBasename, cchBasename, &Base);
3617
3618 size_t i = State.cSvnPropChanges;
3619 while (i-- > 0)
3620 {
3621 RTStrFree(State.paSvnPropChanges[i].pszName);
3622 RTStrFree(State.paSvnPropChanges[i].pszValue);
3623 }
3624 RTMemFree(State.paSvnPropChanges);
3625
3626 scmSettingsBaseDelete(&Base);
3627 }
3628 return rc;
3629}
3630
3631
3632/**
3633 * Tries to correct RTDIRENTRY_UNKNOWN.
3634 *
3635 * @returns Corrected type.
3636 * @param pszPath The path to the object in question.
3637 */
3638static RTDIRENTRYTYPE scmFigureUnknownType(const char *pszPath)
3639{
3640 RTFSOBJINFO Info;
3641 int rc = RTPathQueryInfo(pszPath, &Info, RTFSOBJATTRADD_NOTHING);
3642 if (RT_FAILURE(rc))
3643 return RTDIRENTRYTYPE_UNKNOWN;
3644 if (RTFS_IS_DIRECTORY(Info.Attr.fMode))
3645 return RTDIRENTRYTYPE_DIRECTORY;
3646 if (RTFS_IS_FILE(Info.Attr.fMode))
3647 return RTDIRENTRYTYPE_FILE;
3648 return RTDIRENTRYTYPE_UNKNOWN;
3649}
3650
3651/**
3652 * Recurse into a sub-directory and process all the files and directories.
3653 *
3654 * @returns IPRT status code.
3655 * @param pszBuf Path buffer containing the directory path on
3656 * entry. This ends with a dot. This is passed
3657 * along when recusing in order to save stack space
3658 * and avoid needless copying.
3659 * @param cchDir Length of our path in pszbuf.
3660 * @param pEntry Directory entry buffer. This is also passed
3661 * along when recursing to save stack space.
3662 * @param pSettingsStack The settings stack (pointer to the top element).
3663 * @param iRecursion The recursion depth. This is used to restrict
3664 * the recursions.
3665 */
3666static int scmProcessDirTreeRecursion(char *pszBuf, size_t cchDir, PRTDIRENTRY pEntry,
3667 PSCMSETTINGS pSettingsStack, unsigned iRecursion)
3668{
3669 int rc;
3670 Assert(cchDir > 1 && pszBuf[cchDir - 1] == '.');
3671
3672 /*
3673 * Make sure we stop somewhere.
3674 */
3675 if (iRecursion > 128)
3676 {
3677 RTMsgError("recursion too deep: %d\n", iRecursion);
3678 return VINF_SUCCESS; /* ignore */
3679 }
3680
3681 /*
3682 * Check if it's excluded by --only-svn-dir.
3683 */
3684 if (pSettingsStack->Base.fOnlySvnDirs)
3685 {
3686 rc = RTPathAppend(pszBuf, RTPATH_MAX, ".svn");
3687 if (RT_FAILURE(rc))
3688 {
3689 RTMsgError("RTPathAppend: %Rrc\n", rc);
3690 return rc;
3691 }
3692 if (!RTDirExists(pszBuf))
3693 return VINF_SUCCESS;
3694
3695 Assert(RTPATH_IS_SLASH(pszBuf[cchDir]));
3696 pszBuf[cchDir] = '\0';
3697 pszBuf[cchDir - 1] = '.';
3698 }
3699
3700 /*
3701 * Try open and read the directory.
3702 */
3703 PRTDIR pDir;
3704 rc = RTDirOpenFiltered(&pDir, pszBuf, RTDIRFILTER_NONE);
3705 if (RT_FAILURE(rc))
3706 {
3707 RTMsgError("Failed to enumerate directory '%s': %Rrc", pszBuf, rc);
3708 return rc;
3709 }
3710 for (;;)
3711 {
3712 /* Read the next entry. */
3713 rc = RTDirRead(pDir, pEntry, NULL);
3714 if (RT_FAILURE(rc))
3715 {
3716 if (rc == VERR_NO_MORE_FILES)
3717 rc = VINF_SUCCESS;
3718 else
3719 RTMsgError("RTDirRead -> %Rrc\n", rc);
3720 break;
3721 }
3722
3723 /* Skip '.' and '..'. */
3724 if ( pEntry->szName[0] == '.'
3725 && ( pEntry->cbName == 1
3726 || ( pEntry->cbName == 2
3727 && pEntry->szName[1] == '.')))
3728 continue;
3729
3730 /* Enter it into the buffer so we've got a full name to work
3731 with when needed. */
3732 if (pEntry->cbName + cchDir >= RTPATH_MAX)
3733 {
3734 RTMsgError("Skipping too long entry: %s", pEntry->szName);
3735 continue;
3736 }
3737 memcpy(&pszBuf[cchDir - 1], pEntry->szName, pEntry->cbName + 1);
3738
3739 /* Figure the type. */
3740 RTDIRENTRYTYPE enmType = pEntry->enmType;
3741 if (enmType == RTDIRENTRYTYPE_UNKNOWN)
3742 enmType = scmFigureUnknownType(pszBuf);
3743
3744 /* Process the file or directory, skip the rest. */
3745 if (enmType == RTDIRENTRYTYPE_FILE)
3746 rc = scmProcessFile(pszBuf, pEntry->szName, pEntry->cbName, pSettingsStack);
3747 else if (enmType == RTDIRENTRYTYPE_DIRECTORY)
3748 {
3749 /* Append the dot for the benefit of the pattern matching. */
3750 if (pEntry->cbName + cchDir + 5 >= RTPATH_MAX)
3751 {
3752 RTMsgError("Skipping too deep dir entry: %s", pEntry->szName);
3753 continue;
3754 }
3755 memcpy(&pszBuf[cchDir - 1 + pEntry->cbName], "/.", sizeof("/."));
3756 size_t cchSubDir = cchDir - 1 + pEntry->cbName + sizeof("/.") - 1;
3757
3758 if ( !pSettingsStack->Base.pszFilterOutDirs
3759 || !*pSettingsStack->Base.pszFilterOutDirs
3760 || ( !RTStrSimplePatternMultiMatch(pSettingsStack->Base.pszFilterOutDirs, RTSTR_MAX,
3761 pEntry->szName, pEntry->cbName, NULL)
3762 && !RTStrSimplePatternMultiMatch(pSettingsStack->Base.pszFilterOutDirs, RTSTR_MAX,
3763 pszBuf, cchSubDir, NULL)
3764 )
3765 )
3766 {
3767 rc = scmSettingsStackPushDir(&pSettingsStack, pszBuf);
3768 if (RT_SUCCESS(rc))
3769 {
3770 rc = scmProcessDirTreeRecursion(pszBuf, cchSubDir, pEntry, pSettingsStack, iRecursion + 1);
3771 scmSettingsStackPopAndDestroy(&pSettingsStack);
3772 }
3773 }
3774 }
3775 if (RT_FAILURE(rc))
3776 break;
3777 }
3778 RTDirClose(pDir);
3779 return rc;
3780
3781}
3782
3783/**
3784 * Process a directory tree.
3785 *
3786 * @returns IPRT status code.
3787 * @param pszDir The directory to start with. This is pointer to
3788 * a RTPATH_MAX sized buffer.
3789 */
3790static int scmProcessDirTree(char *pszDir, PSCMSETTINGS pSettingsStack)
3791{
3792 /*
3793 * Setup the recursion.
3794 */
3795 int rc = RTPathAppend(pszDir, RTPATH_MAX, ".");
3796 if (RT_SUCCESS(rc))
3797 {
3798 RTDIRENTRY Entry;
3799 rc = scmProcessDirTreeRecursion(pszDir, strlen(pszDir), &Entry, pSettingsStack, 0);
3800 }
3801 else
3802 RTMsgError("RTPathAppend: %Rrc\n", rc);
3803 return rc;
3804}
3805
3806
3807/**
3808 * Processes a file or directory specified as an command line argument.
3809 *
3810 * @returns IPRT status code
3811 * @param pszSomething What we found in the commad line arguments.
3812 * @param pSettingsStack The settings stack (pointer to the top element).
3813 */
3814static int scmProcessSomething(const char *pszSomething, PSCMSETTINGS pSettingsStack)
3815{
3816 char szBuf[RTPATH_MAX];
3817 int rc = RTPathAbs(pszSomething, szBuf, sizeof(szBuf));
3818 if (RT_SUCCESS(rc))
3819 {
3820 RTPathChangeToUnixSlashes(szBuf, false /*fForce*/);
3821
3822 PSCMSETTINGS pSettings;
3823 rc = scmSettingsCreateForPath(&pSettings, &pSettingsStack->Base, szBuf);
3824 if (RT_SUCCESS(rc))
3825 {
3826 scmSettingsStackPush(&pSettingsStack, pSettings);
3827
3828 if (RTFileExists(szBuf))
3829 {
3830 const char *pszBasename = RTPathFilename(szBuf);
3831 if (pszBasename)
3832 {
3833 size_t cchBasename = strlen(pszBasename);
3834 rc = scmProcessFile(szBuf, pszBasename, cchBasename, pSettingsStack);
3835 }
3836 else
3837 {
3838 RTMsgError("RTPathFilename: NULL\n");
3839 rc = VERR_IS_A_DIRECTORY;
3840 }
3841 }
3842 else
3843 rc = scmProcessDirTree(szBuf, pSettingsStack);
3844
3845 PSCMSETTINGS pPopped = scmSettingsStackPop(&pSettingsStack);
3846 Assert(pPopped == pSettings);
3847 scmSettingsDestroy(pSettings);
3848 }
3849 else
3850 RTMsgError("scmSettingsInitStack: %Rrc\n", rc);
3851 }
3852 else
3853 RTMsgError("RTPathAbs: %Rrc\n", rc);
3854 return rc;
3855}
3856
3857int main(int argc, char **argv)
3858{
3859 int rc = RTR3Init();
3860 if (RT_FAILURE(rc))
3861 return 1;
3862
3863 /*
3864 * Init the settings.
3865 */
3866 PSCMSETTINGS pSettings;
3867 rc = scmSettingsCreate(&pSettings, &g_Defaults);
3868 if (RT_FAILURE(rc))
3869 {
3870 RTMsgError("scmSettingsCreate: %Rrc\n", rc);
3871 return 1;
3872 }
3873
3874 /*
3875 * Parse arguments and process input in order (because this is the only
3876 * thing that works at the moment).
3877 */
3878 static RTGETOPTDEF s_aOpts[14 + RT_ELEMENTS(g_aScmOpts)] =
3879 {
3880 { "--dry-run", 'd', RTGETOPT_REQ_NOTHING },
3881 { "--real-run", 'D', RTGETOPT_REQ_NOTHING },
3882 { "--file-filter", 'f', RTGETOPT_REQ_STRING },
3883 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
3884 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
3885 { "--diff-ignore-eol", SCMOPT_DIFF_IGNORE_EOL, RTGETOPT_REQ_NOTHING },
3886 { "--diff-no-ignore-eol", SCMOPT_DIFF_NO_IGNORE_EOL, RTGETOPT_REQ_NOTHING },
3887 { "--diff-ignore-space", SCMOPT_DIFF_IGNORE_SPACE, RTGETOPT_REQ_NOTHING },
3888 { "--diff-no-ignore-space", SCMOPT_DIFF_NO_IGNORE_SPACE, RTGETOPT_REQ_NOTHING },
3889 { "--diff-ignore-leading-space", SCMOPT_DIFF_IGNORE_LEADING_SPACE, RTGETOPT_REQ_NOTHING },
3890 { "--diff-no-ignore-leading-space", SCMOPT_DIFF_NO_IGNORE_LEADING_SPACE, RTGETOPT_REQ_NOTHING },
3891 { "--diff-ignore-trailing-space", SCMOPT_DIFF_IGNORE_TRAILING_SPACE, RTGETOPT_REQ_NOTHING },
3892 { "--diff-no-ignore-trailing-space", SCMOPT_DIFF_NO_IGNORE_TRAILING_SPACE, RTGETOPT_REQ_NOTHING },
3893 { "--diff-special-chars", SCMOPT_DIFF_SPECIAL_CHARS, RTGETOPT_REQ_NOTHING },
3894 { "--diff-no-special-chars", SCMOPT_DIFF_NO_SPECIAL_CHARS, RTGETOPT_REQ_NOTHING },
3895 };
3896 memcpy(&s_aOpts[RT_ELEMENTS(s_aOpts) - RT_ELEMENTS(g_aScmOpts)], &g_aScmOpts[0], sizeof(g_aScmOpts));
3897
3898 RTGETOPTUNION ValueUnion;
3899 RTGETOPTSTATE GetOptState;
3900 rc = RTGetOptInit(&GetOptState, argc, argv, &s_aOpts[0], RT_ELEMENTS(s_aOpts), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3901 AssertReleaseRCReturn(rc, 1);
3902 size_t cProcessed = 0;
3903
3904 while ((rc = RTGetOpt(&GetOptState, &ValueUnion)) != 0)
3905 {
3906 switch (rc)
3907 {
3908 case 'd':
3909 g_fDryRun = true;
3910 break;
3911 case 'D':
3912 g_fDryRun = false;
3913 break;
3914
3915 case 'f':
3916 g_pszFileFilter = ValueUnion.psz;
3917 break;
3918
3919 case 'h':
3920 RTPrintf("VirtualBox Source Code Massager\n"
3921 "\n"
3922 "Usage: %s [options] <files & dirs>\n"
3923 "\n"
3924 "Options:\n", g_szProgName);
3925 for (size_t i = 0; i < RT_ELEMENTS(s_aOpts); i++)
3926 {
3927 bool fAdvanceTwo = false;
3928 if ((s_aOpts[i].fFlags & RTGETOPT_REQ_MASK) == RTGETOPT_REQ_NOTHING)
3929 {
3930 fAdvanceTwo = i + 1 < RT_ELEMENTS(s_aOpts)
3931 && ( strstr(s_aOpts[i+1].pszLong, "-no-") != NULL
3932 || strstr(s_aOpts[i+1].pszLong, "-not-") != NULL
3933 || strstr(s_aOpts[i+1].pszLong, "-dont-") != NULL
3934 );
3935 if (fAdvanceTwo)
3936 RTPrintf(" %s, %s\n", s_aOpts[i].pszLong, s_aOpts[i + 1].pszLong);
3937 else
3938 RTPrintf(" %s\n", s_aOpts[i].pszLong);
3939 }
3940 else if ((s_aOpts[i].fFlags & RTGETOPT_REQ_MASK) == RTGETOPT_REQ_STRING)
3941 RTPrintf(" %s string\n", s_aOpts[i].pszLong);
3942 else
3943 RTPrintf(" %s value\n", s_aOpts[i].pszLong);
3944 switch (s_aOpts[i].iShort)
3945 {
3946 case SCMOPT_CONVERT_EOL: RTPrintf(" Default: %RTbool\n", g_Defaults.fConvertEol); break;
3947 case SCMOPT_CONVERT_TABS: RTPrintf(" Default: %RTbool\n", g_Defaults.fConvertTabs); break;
3948 case SCMOPT_FORCE_FINAL_EOL: RTPrintf(" Default: %RTbool\n", g_Defaults.fForceFinalEol); break;
3949 case SCMOPT_FORCE_TRAILING_LINE: RTPrintf(" Default: %RTbool\n", g_Defaults.fForceTrailingLine); break;
3950 case SCMOPT_STRIP_TRAILING_BLANKS: RTPrintf(" Default: %RTbool\n", g_Defaults.fStripTrailingBlanks); break;
3951 case SCMOPT_STRIP_TRAILING_LINES: RTPrintf(" Default: %RTbool\n", g_Defaults.fStripTrailingLines); break;
3952 case SCMOPT_ONLY_SVN_DIRS: RTPrintf(" Default: %RTbool\n", g_Defaults.fOnlySvnDirs); break;
3953 case SCMOPT_ONLY_SVN_FILES: RTPrintf(" Default: %RTbool\n", g_Defaults.fOnlySvnFiles); break;
3954 case SCMOPT_TAB_SIZE: RTPrintf(" Default: %u\n", g_Defaults.cchTab); break;
3955 case SCMOPT_FILTER_OUT_DIRS: RTPrintf(" Default: %s\n", g_Defaults.pszFilterOutDirs); break;
3956 case SCMOPT_FILTER_FILES: RTPrintf(" Default: %s\n", g_Defaults.pszFilterFiles); break;
3957 case SCMOPT_FILTER_OUT_FILES: RTPrintf(" Default: %s\n", g_Defaults.pszFilterOutFiles); break;
3958 }
3959 i += fAdvanceTwo;
3960 }
3961 return 1;
3962
3963 case 'q':
3964 g_iVerbosity = 0;
3965 break;
3966
3967 case 'v':
3968 g_iVerbosity++;
3969 break;
3970
3971 case 'V':
3972 {
3973 /* The following is assuming that svn does it's job here. */
3974 static const char s_szRev[] = "$Revision: 26557 $";
3975 const char *psz = RTStrStripL(strchr(s_szRev, ' '));
3976 RTPrintf("r%.*s\n", strchr(psz, ' ') - psz, psz);
3977 return 0;
3978 }
3979
3980 case SCMOPT_DIFF_IGNORE_EOL:
3981 g_fDiffIgnoreEol = true;
3982 break;
3983 case SCMOPT_DIFF_NO_IGNORE_EOL:
3984 g_fDiffIgnoreEol = false;
3985 break;
3986
3987 case SCMOPT_DIFF_IGNORE_SPACE:
3988 g_fDiffIgnoreTrailingWS = g_fDiffIgnoreLeadingWS = true;
3989 break;
3990 case SCMOPT_DIFF_NO_IGNORE_SPACE:
3991 g_fDiffIgnoreTrailingWS = g_fDiffIgnoreLeadingWS = false;
3992 break;
3993
3994 case SCMOPT_DIFF_IGNORE_LEADING_SPACE:
3995 g_fDiffIgnoreLeadingWS = true;
3996 break;
3997 case SCMOPT_DIFF_NO_IGNORE_LEADING_SPACE:
3998 g_fDiffIgnoreLeadingWS = false;
3999 break;
4000
4001 case SCMOPT_DIFF_IGNORE_TRAILING_SPACE:
4002 g_fDiffIgnoreTrailingWS = true;
4003 break;
4004 case SCMOPT_DIFF_NO_IGNORE_TRAILING_SPACE:
4005 g_fDiffIgnoreTrailingWS = false;
4006 break;
4007
4008 case SCMOPT_DIFF_SPECIAL_CHARS:
4009 g_fDiffSpecialChars = true;
4010 break;
4011 case SCMOPT_DIFF_NO_SPECIAL_CHARS:
4012 g_fDiffSpecialChars = false;
4013 break;
4014
4015 case VINF_GETOPT_NOT_OPTION:
4016 {
4017 if (!g_fDryRun)
4018 {
4019 if (!cProcessed)
4020 {
4021 RTPrintf("%s: Warning! This program will make changes to your source files and\n"
4022 "%s: there is a slight risk that bugs or a full disk may cause\n"
4023 "%s: LOSS OF DATA. So, please make sure you have checked in\n"
4024 "%s: all your changes already. If you didn't, then don't blame\n"
4025 "%s: anyone for not warning you!\n"
4026 "%s:\n"
4027 "%s: Press any key to continue...\n",
4028 g_szProgName, g_szProgName, g_szProgName, g_szProgName, g_szProgName,
4029 g_szProgName, g_szProgName);
4030 RTStrmGetCh(g_pStdIn);
4031 }
4032 cProcessed++;
4033 }
4034 rc = scmProcessSomething(ValueUnion.psz, pSettings);
4035 if (RT_FAILURE(rc))
4036 return rc;
4037 break;
4038 }
4039
4040 default:
4041 {
4042 int rc2 = scmSettingsBaseHandleOpt(&pSettings->Base, rc, &ValueUnion);
4043 if (RT_SUCCESS(rc2))
4044 break;
4045 if (rc2 != VERR_GETOPT_UNKNOWN_OPTION)
4046 return 2;
4047 return RTGetOptPrintError(rc, &ValueUnion);
4048 }
4049 }
4050 }
4051
4052 scmSettingsDestroy(pSettings);
4053 return 0;
4054}
4055
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette