1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package Torello.Java.Build;

import Torello.Java.FileNode;
import Torello.Java.FileRW;
import Torello.Java.LFEC;
import Torello.Java.Q;
import Torello.Java.StrCmpr;
import Torello.Java.StringParse;
import Torello.Java.RTC;

import static Torello.Java.C.*;

import java.util.*;
import java.util.regex.*;
import java.io.*;

import java.util.function.IntFunction;

/**
 * A very basic utility for ensuring that the Java Doc Comment portion of a source-file does not
 * exceed a maximum line-length.
 * 
 * <BR /><BR /><EMBED CLASS='external-html' DATA-FILE-ID=LINT>
 */
public class Lint
{
    private Lint() { }


    // ********************************************************************************************
    // ********************************************************************************************
    // MAIN COMMAND-LINE METHOD
    // ********************************************************************************************
    // ********************************************************************************************


    private static final String man_page = '\n' +
        "\tjava Torello.Java.Lint 1 <Java-Source-File>\n" +
        "\tjava Torello.Java.Lint 1 INNERCLASS <Java-Source-File>\n" +
        "\tjava Torello.Java.Lint 2 <external-html-directory> (replaces ' * ' and {@code })\n" +
        "\tjava Torello.Java.Lint 3 <external-html-directory> (line-length checker)\n";

    /**
     * This class' operations are all performed via the command line.  It asks questions of the
     * user from the command line, and lints the Java Doc Comments parts of {@code '.java'} files
     * to ensure that no line comment line is longer than 100 characters.  This class is probably
     * not too useful - <I>outside of the Java HTML Library!</I>  It did help me make all of my
     * source-code files look nice when you click on the "Hi-Lited Source Code" links.
     */
    public static void main(String[] argv) throws IOException
    {
        if (    ((argv.length < 2) || (argv.length > 3))
            ||  StrCmpr.equalsNAND(argv[0], "1", "2", "3")
        )
            System.out.println(man_page);

        else if (argv[0].equals("1")) // Java Doc Linter
        {
            if (argv.length == 2) lint(argv[1]);
            else
            {
                if (! argv[1].equals("INNERCLASS"))
                {
                    System.out.println(man_page);
                    System.exit(0);
                }

                LONG_JD_COMMENT = LONG_JD_COMMENT_INNERCLASS;
                COMMENT_LINE_BEGINNING = "    " + COMMENT_LINE_BEGINNING;
                lint(argv[2]);
            }
        }

        else if (argv[0].equals("2")) // External-HTML File Linter
            externalHTML(argv[1]);

        else if (argv[0].equals("3")) // External-HTML File Linter
            lineLengthChecker(argv[1]);

        else System.out.println(man_page);
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Java Doc Comments Linter
    // ********************************************************************************************
    // ********************************************************************************************


    /** Regular Expression for breaking up long lines of JavaDoc Comments */
    public static Pattern LONG_JD_COMMENT = Pattern.compile
        ("^(     \\* [^\\n]{0,92})\\s([^\\n]+)\n");

    /** Regular Expression for breaking up long lines of JavaDoc Comments */
    public static final Pattern LONG_JD_COMMENT_INNERCLASS = Pattern.compile
        ("^(         \\* [^\\n]{0,88})\\s([^\\n]+)\n");

    /** Regular Expression for matching lines that have JavaDoc Upgrade HiLite Dividers */
    public static final Pattern OPENING_HILITE_DIV = Pattern.compile(
        "<DIV\\s+CLASS=['\\\"](EXAMPLE|SNIP|LOC|SHELL|HTML|REGEX|SHELLBLOCK|COMPLETE)" +
        "(-SCROLL)?['\\\"]\\w*>\\w*\\{",
        Pattern.CASE_INSENSITIVE);

    /** Regular Expression for matching lines that have 'closing' HiLite Divider Elements. */
    public static final Pattern CLOSING_HILITE_DIV = Pattern.compile
        ("\\}\\w*<\\/DIV>", Pattern.CASE_INSENSITIVE);

    /** Long lines that don't require being queried by the user, because they only have text */
    public static final Pattern SAFE_ENDING = Pattern.compile
        ("^.*?[\\w\\d\\s,\\-\\.]{20}$");

    /** The first 7 characters of a line of text in JavaDoc Comments portions of source files. */
    public static String COMMENT_LINE_BEGINNING = "     * ";

    private static final String[] PREV_LINE_MUST_BE_STRS =
    {
        "* @",
        "* <EMBED ",
        "* <BR /><BR />",

        "* <DIV ",
        "* <BR /><DIV ",

        "* <UL ",
        "* <BR /><UL ",

        "* <OL ",
        "* <BR /><OL ",

        "* <TABLE ",
        "* <BR /><TABLE "
    };

    private static final String[] CANNOT_PREPEND_TO_LINE_STRS =
        new String[11 + PREV_LINE_MUST_BE_STRS.length];
    static
    {
        System.arraycopy(
            PREV_LINE_MUST_BE_STRS, 0, CANNOT_PREPEND_TO_LINE_STRS,
            11, PREV_LINE_MUST_BE_STRS.length
        );

        CANNOT_PREPEND_TO_LINE_STRS[0]  = "* </UL>";
        CANNOT_PREPEND_TO_LINE_STRS[1]  = "* </OL>";
        CANNOT_PREPEND_TO_LINE_STRS[2]  = "* </TABLE>";
        CANNOT_PREPEND_TO_LINE_STRS[3]  = "* <LI>";
        CANNOT_PREPEND_TO_LINE_STRS[4]  = "* </LI>";
        CANNOT_PREPEND_TO_LINE_STRS[5]  = "* <TD>";
        CANNOT_PREPEND_TO_LINE_STRS[6]  = "* </TD>";
        CANNOT_PREPEND_TO_LINE_STRS[7]  = "* <TR>";
        CANNOT_PREPEND_TO_LINE_STRS[8]  = "* </TR>";
        CANNOT_PREPEND_TO_LINE_STRS[9]  = "* <TH>";
        CANNOT_PREPEND_TO_LINE_STRS[10] = "* </TH>";
    }

    /**
     * Performs a 'LINT' on the input Java Source Code File.
     * 
     * @param inFileOrDir This is any file or directory.  If this is a directory, the entire
     * directory will be scanned for {@code '.java'} source-files.  If this is a file, then it
     * will be the only file that is linted.
     * 
     * @throws FileNotFoundException If this file or directory is not found.
     */
    public static void lint(String inFileOrDir) throws IOException
    {
        File            f = new File(inFileOrDir);
        Vector<String>  files;

        if (! f.exists()) throw new FileNotFoundException
            ("A file or directory named [" + inFileOrDir + "], was not found.");

        boolean lintingDirectory = true;

        if (f.isDirectory()) files = FileNode
            .createRoot(inFileOrDir)
            .loadTree(1, (File file, String name) -> name.endsWith(".java"), null)
            .flattenJustFiles(RTC.FULLPATH_VECTOR());
        else 
        {
            files = new Vector<>();
            files.add(inFileOrDir);
            lintingDirectory = false;
        }

        for (int fNum=0; fNum < files.size(); fNum++)
        {
            String file = files.elementAt(fNum);

            System.out.println(
                "Linting File [" + BCYAN + (fNum+1) + " of " + files.size() + RESET + "]\n" +
                "Visiting File: " + BYELLOW + file + RESET + "\n"
            );

            Vector<String>  javaFile        = FileRW.loadFileToVector(file, true);
            boolean         insideHiLiteDIV = false;
            int             linesAdded      = 0;

            for (int i=1; i < (javaFile.size()-1); i++)
            {
                String  line                    = javaFile.elementAt(i);
                String  prevLine                = javaFile.elementAt(i-1);
                String  nextLine                = javaFile.elementAt(i+1);

                String  lineTrimmed             = line.trim();
                String  prevLineTrimmed         = prevLine.trim();
                String  nextLineTrimmed         = nextLine.trim();

                boolean lineIsComment           = line.startsWith(COMMENT_LINE_BEGINNING);
                boolean nextLineIsComment       = nextLine.startsWith(COMMENT_LINE_BEGINNING);
                boolean prevLineWasComment      = prevLine.startsWith(COMMENT_LINE_BEGINNING);

                boolean lineIsTooLong           = line.length() > 100;
                boolean prevLineWasBlankComment = prevLineTrimmed.equals("*");
                boolean nextLineIsEndingComment = nextLineTrimmed.equals("*/");
                boolean nthSeeTagInARow         = lineTrimmed.startsWith("* @see") && 
                                                    prevLineTrimmed.startsWith("* @see");

                boolean hasOpeningHiLiteDIV     = lineIsComment && 
                                                    OPENING_HILITE_DIV.matcher(lineTrimmed).find();

                boolean hasClosingHiLiteDIV     = lineIsComment && 
                                                    CLOSING_HILITE_DIV.matcher(lineTrimmed).find();

                boolean mustBePreceededByBlankCommentLine =
                    lineIsComment &&
                    StrCmpr.startsWithXOR_CI(lineTrimmed, PREV_LINE_MUST_BE_STRS);

                boolean appendToStartOfNextLineIsOK =
                    nextLineIsComment &&
                    (! StrCmpr.startsWithXOR_CI(nextLineTrimmed, CANNOT_PREPEND_TO_LINE_STRS)) &&
                    (! nextLineIsEndingComment);

                // ************************************************************
                // MAIN LOOP PART
                // ************************************************************

                if (hasOpeningHiLiteDIV)
                    insideHiLiteDIV = true;
                else
                {
                    if (hasClosingHiLiteDIV)
                    { insideHiLiteDIV = false; System.out.print(line); continue; }

                    if (insideHiLiteDIV)
                    { System.out.print(line); continue; }
                } // tricky...

                if (    mustBePreceededByBlankCommentLine
                    &&  (! prevLineWasBlankComment)
                    &&  (! nthSeeTagInARow)
                    )
                {
                    linesAdded++;
                    javaFile.add(i, COMMENT_LINE_BEGINNING + '\n');
                    System.out.print(BGREEN + COMMENT_LINE_BEGINNING + RESET + '\n');
                }
                else if (lineIsComment && lineIsTooLong)
                {
                    System.out.print(BRED + line + RESET);
                    Matcher m = LONG_JD_COMMENT.matcher(line);

                    if (! m.find()) throw new IllegalStateException("MESSED UP, WTF?");

                    String shortenedLine    = StringParse.trimRight(m.group(1));
                    String restOfThisLine   = line.substring(m.end(1)).trim();

                    System.out.print(shortenedLine + '\n');
                    javaFile.setElementAt(shortenedLine + '\n', i);

                    if (! SAFE_ENDING.matcher(shortenedLine).find())

                        while (! Q.YN(
                            "Break OK?  (Currently on Line #" + i + " of " +
                            javaFile.size() + ")"
                        ))
                        {
                            int pos = shortenedLine.lastIndexOf(' ');
                            if (pos == -1) System.exit(0);

                            restOfThisLine = shortenedLine.substring(pos + 1).trim() +
                                ' ' + restOfThisLine;
        
                            shortenedLine = StringParse.trimRight(shortenedLine.substring(0, pos));

                            System.out.print(BRED + shortenedLine + RESET + '\n');
                            javaFile.setElementAt(shortenedLine + '\n', i);
                        }

                    if (restOfThisLine.length() == 0) continue;

                    if (appendToStartOfNextLineIsOK)
                    {
                        nextLine = COMMENT_LINE_BEGINNING + restOfThisLine + ' ' + 
                            nextLine.substring(COMMENT_LINE_BEGINNING.length());

                        javaFile.setElementAt(nextLine, i+1);
                    }
                    else
                    {
                        linesAdded++;
                        javaFile.add(i+1, COMMENT_LINE_BEGINNING + restOfThisLine + '\n');
                    }
                }
                else System.out.print(line);
            }

            System.out.println(
                "Finished File:\t" + BYELLOW + file + RESET + '\n' +
                "Added [" + BCYAN + StringParse.zeroPad(linesAdded) + RESET + "] new lines " +
                "to  the file."
            );

            for (int count=5; count > 0; count--) 
                Q.YN(
                    "Press Y/N " + BCYAN + StringParse.zeroPad(count) + RESET +
                    " more times..."
                );

            String question = lintingDirectory
                ? "Save and continue to next file?"
                : "Save file?";

            if (! Q.YN(GREEN + question + RESET)) System.exit(0);
            FileRW.writeFile_NO_NEWLINE(javaFile, file);
            System.out.println("Wrote File:\t" + BYELLOW + file + RESET);
        }
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // External HTML File Converter
    // ********************************************************************************************
    // ********************************************************************************************


    private static final Pattern CODES = Pattern.compile("\\{@code [^\\}]+\\}");
    private static final Pattern LINKS = Pattern.compile("\\{@link ([\\w.]+)?#?([^\\}]+)?\\}");
    private static final Pattern JDSTARS = Pattern.compile("^\\s+\\*( |$)", Pattern.MULTILINE);

    /**
     * This can be a really great tool for transitioning a Source-File to use External-HTML Files.
     * This method merely scans an HTML-File for items that need to be escaped or converted to 
     * constructs that are usable in {@code '.html'} rather than {@code '.java'} files.
     * 
     * @param directoryName The name of a directory containing {@code '.html'} files.
     */
    public static void externalHTML(String directoryName) throws IOException
    {
        Iterator<String> externalHTMLFiles = FileNode
            .createRoot(directoryName)
            .loadTree(-1, (File dir, String fileName) -> fileName.endsWith(".html"), null)
            .flattenJustFiles(RTC.FULLPATH_ITERATOR());

        while (externalHTMLFiles.hasNext())
        {
            String  fileName    = externalHTMLFiles.next();
            String  fileAsStr   = FileRW.loadFileToString(fileName);
            String  newFileStr  = fileAsStr;
            Matcher codes       = CODES.matcher(fileAsStr);

            System.out.println("Linting File: " + BYELLOW + fileName + RESET);

            if (! Q.YN("Shall We Lint?"))
            {
                if (! Q.YN("Continue to Next File? (say 'no' to Exit)")) System.exit(0);
                else continue;
            }



            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Replace the {@code ...}
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            while (codes.find())
            {
                String s = codes.group();

                String newS = 
                    "<CODE>" +
                    s.substring(7, s.length() - 1).replace("<", "&lt;").replace(">", "&gt;") +
                    "</CODE>";

                System.out.println(
                    BYELLOW + s.replace("\n", "\\n") +  RESET +
                    BRED + "\n    ===>\n" + RESET +
                    BGREEN + newS + RESET
                );

                if (Q.YN("Replace this one?"))
                {
                    newFileStr = codes.replaceFirst(newS);
                    codes.reset(newFileStr);
                }
            }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Replace the {@link ...}  
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            //
            // **NOTE: The replacements are JUST HELPERS, THEY ARE NOT COMPLETE.
            //         This does about 95% of the typing for you, but it is not 100%
            //         The relative-path string (dot-dots) has not been added.

            Matcher links = LINKS.matcher(newFileStr);

            while (links.find())
            {
                String s = links.group();

                String file = links.group(1);
                String rel = links.group(2);

                String href = 
                    ((file != null) ? (file + ".html") : "") +
                    ((rel != null) ? ("#" + rel) : "");

                String linkText =
                    ((file != null) ? (file) : "") +
                    ((rel != null)
                        ? (((file != null) ? "." : "") + rel)
                        : "");

                String newS =
                    "<B><CODE><A HREF='" + href + "'>" + linkText + "</CODE></B></A>";

                System.out.println(
                    BYELLOW + s.replace("\n", "\\n") +  RESET +
                    BRED + "\n    ===>\n" + RESET +
                    BGREEN + newS + RESET
                );

                if (Q.YN("Replace this one?"))
                {
                    newFileStr = links.replaceFirst("\n\n" + newS + "\n\n");
                    links.reset(newFileStr);
                }
            }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Replace the leading  "     * "
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            newFileStr = JDSTARS.matcher(newFileStr).replaceAll("");


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Save the file
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            System.out.println(
                newFileStr +
                "\n************************************************************\n"
            );

            if (Q.YN("Save this File?"))
            {
                FileRW.writeFile(newFileStr, fileName);
                System.out.println("Saved File: " + BYELLOW + fileName + RESET);
            }           
        }
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // CHECKS FOR '.java' FILES WITH LONG LINE LENGTHS
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * This method will scan an entire directory for {@code '.java'} files, and then report if
     * there are any lines in each of those files whose length is greater than 100.
     * 
     * <BR /><BR />While not exactly a great tool for all developers, during the development of
     * Java HTML, this has been (on occasion) extremely useful.
     * 
     * @param directoryName The name of the directory to be scanned for {@code '.java'} files.
     */
    public static void lineLengthChecker(String directoryName) throws IOException
    {
        Iterator<String> javaFiles = FileNode
            .createRoot(directoryName)
            .loadTree(-1, (File dir, String fileName) -> fileName.endsWith(".java"), null)
            .flattenJustFiles(RTC.FULLPATH_ITERATOR());

        while (javaFiles.hasNext())
        {
            String              fileName    = javaFiles.next();
            Vector<String>      lines       = FileRW.loadFileToVector(fileName, true);
            boolean             hadMatch    = false;
            IntFunction<String> zeroPad     = (lines.size() < 999)
                                                ? StringParse::zeroPad
                                                : StringParse::zeroPad10e4;

            System.out.println("Checking File: " + BYELLOW + fileName + RESET);

            for (int i=0; i < lines.size(); i++)

                if (lines.elementAt(i).length() > 100)
                {
                    String l = lines.elementAt(i);

                    System.out.print(
                        "Line-Number: " +

                        // NOTE: add one to the line number, when printing it.  The lines
                        //       vector index starts at zero, not one.

                        '[' + BGREEN + zeroPad.apply(i + 1) + RESET + ", " +
                        "Has Length: " + BRED + l.length() + RESET + '\n' +

                        // Print the line
                        l
                    );

                    hadMatch = true;
                }

            if (hadMatch) if (! Q.YN("continue?")) System.exit(0);
        }
    }
}