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
package Torello.Java.Build;

import Torello.Java.UnreachableError;

import Torello.Java.ReadOnly.ReadOnlyArrayList;
import Torello.Java.ReadOnly.ReadOnlyList;

import static Torello.Java.C.BRED;
import static Torello.Java.C.RESET;

import Apache.CLI.CommandLine;
import Apache.CLI.Option;

import java.util.ArrayList;
import java.util.stream.Stream;


// This class/method is called on the very last line of 'ProcessMainMenuChoice'
// This class only has a single static method.
// 
// This code does indeed "handle" or "deal with" User-Input.  It deals-with the specifi 
// User-Input that involves providing a list of Package Nick-Names at the Command-Line, so that
// **ONLY** those particular packages (the ones **EXPLICITY** requested) are processed by this
// Build-Tool, during a build.
// 
// Code that involves handling User-Input is always a lot uglier to look at.  It also involves
// lots  of "println" statements that can result from "unacceptable combinations" that may be
// entered at the command line.
// 
// This whole method only has a few lines of actual code, but (obviously) has dozens of lines of
// comments that attempt to explain what is occurring.  This is why this method is in a separate
// method from the class "ProcessMainMenuChoice".  
// 
// All of the input parameters are passed from "ProcessMainMenuChoice".

class ProcessNickNameArgs
{
    static SelectedOptionsRecord process(
            final ReadOnlyList<BuildPackage>    packageList,
            final String                        MENU_CHOICE,
            final Option                        selectedOpt,
            final ReadOnlyList<String>          optionsWhichAcceptPkgNickNames,

            // THIS IS NOT A HACK, IT IS A ALTERNATIVELY PROPOSED WORK-A-ROUND to a PROBLEM THAT
            // I DON'T ACTUALLY HAVE THE TIME TO SOLVE AT THE MOMENT.
            // 
            // This class is now being used in a second CLI Program.  The latest and greatest
            // "Testing.java" needs to **RE-USE** the "ProcessNickNameArgs" class (this class) in
            // its own CLI-Based Application.  In that application, there is no way to generate a 
            // "PrintHelpRecord".
            // 
            // THEREFORE, I HAVE TURNED THIS INTO A FUNCTIONAL INTERFACE, SO THAT THE CLASS
            // "Testing" can re-use this class (the one you are looking at "ProcessNickNameArgs"),
            // without having to create its own "PrintHelpRecord", which it simply CANNOT DO
            // BECAUSE IT IS A MUCH SIMPLER, STRIPPED DOWN, CLI-Program!
            // 
            // OLD PARAMETER: final PrintHelpRecord phr,

            final MainMenuPrinter mainMenuPrinter, 

            final CommandLine commandLine
        )
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // This part can only be done after getting the "MENU_CHOICE"
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // There are only a few menu-options that accept a list of package nick-names...  When a
        // a user specifies which packages he wants compiled or synchronized, he does so due to
        // and because of the value provided "speeding things up" and "making the build run
        // faster".
        // 
        // When specifying an abbreviated list of packages that need to be re-compiled and
        // re-documented, the user gets to avoid sitting in his chair, wasting time, watching and
        // waiting as this Build-Tool re-compiles and re-documents **ALL PACKAGES** - even ones 
        // whose Source-Code and Documentation hasn't been changed, or even touched, in six
        // months...
        // 
        // Here are a few of the Options which allow a User to specify at the Command-Line a list
        // of package nick-names:
        //
        // "javac"  (Option #1) Allows you to compile only the packages listed, if these names
        //          are included.
        //
        // "pb"     (Partial-Build Options) Also allow the ability to specify which User-Listed
        //          Java-Packages will be synchronized to the Cloud.
        // 
        // "jdu"    (Option #3) Skip the Java-Doc Upgrade-Process for all packages, except the one
        //          that you are currently modifying...
        // 
        // NOTE: As is in the previous Line-Of-Code, the ReadOnlyList
        //       'optionsWhichAcceptPkgNickNames' is constructed inside class 'Generate' and / or 
        //       one of its sub-class helpers.

        final boolean pkgNickNamesPossible =
            optionsWhichAcceptPkgNickNames.contains(MENU_CHOICE);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // "Extranneous Arguments" - Arguments which **DID NOT** map to an Apache.CLI.Option
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // I simply cannot get Apache.CLI to allow for an Option that accepts ZERO, ONE or MANY
        // arguments.  The possibilities with Apache.CLI seem to be either "ZERO or ONE" (an
        // optional argument) **OR** "ONE-or-MORE" (multiple, but-not-zero).  Therefore, I sort of
        // have to rely on this "hack-y" thing where I check the "extra non-recognized" switches
        // in order to check for ZERO, ONE or MANY arguments.
        // 
        // This is needed for the options that accept a Package-Nick-Name List, which as of 
        // July 2024 include Menu-Options such as "-1" and "-pb" (explained in a previous comment,
        // a few lines above).

        final String[] nonApacheOption_Args = commandLine.getArgs();


        // I can never tell (anywhere, when I'm coding!) if a list that is returned is going to be
        // null, or a zero-length-array / zero-length-list.  You simply just (eventually) get used
        // to typing things like this:  (someList == null) || (someList.size() == 0)
        // 
        // You just forget whether the code you wrote to initialize your lists with values inside
        // of them, have been designed to assign the lists to 'null' when there is no data
        // available ... or if you have designed them to be assigned to zero-length-lists...
        // 
        // I'm also getting used to typing 'final' everywhere when I know a variable just isn't
        // going to change.  It takes a long while to get excited about using the keyword 'final'

        final boolean contains_NonApacheOption_Args =
            ((nonApacheOption_Args != null) && (nonApacheOption_Args.length > 0));


        if (contains_NonApacheOption_Args)
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // First Error-Scenario: Selected Main-Menu Option doesn't accept Package Nick-Names
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // 
            // Note that at this point in the code, the list of Non-Apache-CLI-Recognized-Switches
            // hasn't even been checked against the list of valid Package Nick-Names.  It is 
            // altogether possible that these are mispellings, types or even erroneous switches
            // that do not even exist.
            //
            // Rather than generate some enormous and comphrensive list of all the things that the
            // user might have meant (or could have meant) with what he has typed at the terminal,
            // INSTEAD, the Main-Menu is printed, and the user is informed that his "Extra
            // Command-Line Switches" are either:
            // 
            //      1) un-recognized
            //      2) (if they are Java-Package Nick-Names), they wouldn't be appropriate
            //          to use, given the Menu-Option which he has entered.
            // 
            // I am not going to worry about telling him which of these two has occurred.
    
            if (! pkgNickNamesPossible)
            {
                mainMenuPrinter.print_MainMenu_Options();

                System.out.println(
                    "You have passed one or more spurious or unrecognized options:\n" +
                    BRED + "Unknown Command-Line Switches Include: " + RESET +
                    '[' + String.join(", ", nonApacheOption_Args) + ']' + '\n' +
                    "Note that if these are Package Nick-Names, the Menu-Option you have " +
                    "selected is not a Menu-Option which accepts Package Nick-Names."
                );

                System.exit(1); throw null;
            }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Error-Check 'nonApacheOption_Args'
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // 
            // "Unrecognized Switches" are switches that were passed by the user, but don't seem to
            // "map" to any of the expressly-written switches created for this class.  A switch
            // will always begin with a dash "-" character.
            // 
            // "Unrecognized Packages" are text-strings that are passed at the command, and do not 
            // begin with a dash, **AND, IN ADDITION** are also **NOT** valid Package Nick-Names
            // either.
            // 
            // NOTE: If either of these two lists are non-empty, it is guaranteed that an error has
            //       occurrred.  Flagging this as an error will happen shortly afterwards.  Because
            //       the complex nature of Apache-CLI, there is one other possible location/source
            //       into which an "extra switch" might have been placed, by Apache-CLI

            // "Switches" begin with the '-' character
            Stream.Builder<String> unrecognizedSwitchListB  = Stream.builder();

            // "Package Nick-Names" start with any other character :)
            Stream.Builder<String> unrecognizedPackageListB = Stream.builder();

            TOP1:
            for (String arg : nonApacheOption_Args)

                // Switches begin with a dash.  If this is a switch, it wasn't consumed by one of
                // the pre-specified Options.  Therefore it must be "un-recognized"

                if (arg.startsWith("-")) unrecognizedSwitchListB.accept(arg);

                else // Else it must be a valid package nick-name.
                {
                    for (BuildPackage bp : packageList) if (bp.nickName.equals(arg)) continue TOP1;
                    unrecognizedPackageListB.accept(arg);
                }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Now, Error-Check Apache.CLI's little "commandLine.getOptionValues(selectedOpt)"
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // 
            // This "Extra For-Loop" is only here to ensure that the error message which is
            // printed, includes all possible mistakes...
            // 
            // this is where the Package-Nick-Names entered by the user were placed into the 
            // an "Option-Value", rather than being sorted into the:
            // 
            // commandLine.getArgs()
            // 
            // This is, sort of, a real nightmare trying to understan where apache is placing
            // my options that were entered by the user.  I have come to understand what has 
            // happened, and I'm trying - desperately - to explain it as clearly as possible!
            // 
            // REMEMBER - If the user has typed:
            // 
            //  1) cloudshell@username$ java MyProject.Build SomePackage
            // 
            //     Then "SomePackage" will be sorted into "commandLine.getArgs()"
            // 
            //     Since he has not made a Menu-Option Choice, this is an error
            // 
            //  2) cloudshell@username$ java MyProject.Build -1 SomeIncorrectPackageName
            // 
            //     Then "SomeIncorrectPackageName" is sorted into
            //     "commandLine.getOptionValues(selectedOpt)"
            // 
            //     This is **ALSO** an error - this time because the package name was invalid 
            //     or misspelled (or something like that)

            TOP2:
            for (String arg : commandLine.getOptionValues(selectedOpt))
            {
                for (BuildPackage bp : packageList) if (bp.nickName.equals(arg)) continue TOP2;
                unrecognizedPackageListB.accept(arg);
            }


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Convert these two error-lists to arrays, and print if non-empty
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // 
            // If either of these two lists that have been generated are NON-EMPTY, a User-Error
            // has occured
            
            final String[] unrecognizedSwitches =
                unrecognizedSwitchListB.build().toArray(String[]::new);

            final String[] unrecognizedPackages =
                unrecognizedPackageListB.build().toArray(String[]::new);

            // Print an error message and exit if either of these lists are non-empty
            if ((unrecognizedSwitches.length + unrecognizedPackages.length) > 0)
            {
                mainMenuPrinter.print_MainMenu_Options();

                if (unrecognizedSwitches.length > 0) System.out.println(
                    "You have passed one or more spurious or unrecognized options:\n" +
                    BRED + "Unknown Command-Line Switches: " + RESET +
                    '[' + String.join(", ", unrecognizedSwitches) + ']' + '\n'
                );

                if (unrecognizedPackages.length > 0) System.out.println(
                    "You have passed one or more unrecognized Package Nick-Names:\n" +
                    BRED + "Unknown Package Nick-Names: " + RESET +
                    '[' + String.join(", ", unrecognizedPackages) + ']' + '\n'
                );

                System.exit(1); throw null;
            }
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Handle Package-NickNames / User-Specified Package-List
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // If the Main-Menu Option is followed by a list of String-Tokens, the only possible 
        // presumption is that they are a list of package nick-names.
        //
        // Remember, this is not the final / complete list of Nick-Names.
        // 
        // This is, literally, part of the "hell" I have been through with this. 
        // This String[]-Array will soon be merged with another String[]-Array before this method
        // exits.

        final String[]  nickNames           = commandLine.getOptionValues(selectedOpt);
        final boolean   nickNamesProvided   = (nickNames != null) && (nickNames.length > 0);


        // This error would (should !) automatically caught by Apache, and wouldnever reach this
        // point.  This is just a variant of 'assert', and it's staying here for now.

        if (nickNamesProvided && (! pkgNickNamesPossible)) throw new UnreachableError();


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Merge: commandLine.getOptionValues(selectedOpt)  **AND** contains_NonApacheOption_Args
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // If you are wondering what "contains_NonApacheOption_Args", and how it was obtained, this
        // variable is initialized (and used) in the first few lines - at the top of this method!
        // It's value is (using Control-C and Control-V from the lines at the top of this method):
        // 
        // final String[] nonApacheOption_Args = commandLine.getArgs();
        // 
        // Here we successfully merge:
        //      1) commandLine.getArgs();
        //      2) commandLine.getOptionValues(selectedOpt) 
        // 
        // After **MUCH** arduous playing with all of this, I realized that the Apache-CLI was
        // actually sorting my arguments into two separate lists!!!
        // 
        // *****************************
        // OLD-COMMENTING FOR THIS CODE:
        // *****************************
        //
        // A temporary list that is needed to merge the two different sources of Package Nick-Name
        // arguments.  Since I simply cannot get Apache's Option-Argument thing to work with a
        // configuration of ZERO, ONE or MANY Option-Arguments, I have to presume that it isn't
        // possible.  As such, the source of Package Nick-Names are the "getOptionValues" **AND**
        // **ALSO** the Extraneous-Options too!
        //
        // Merge those two lists, and then use that merged list as the package nick-names list.
        // Remember that only options "1" (javac) and "pb2" (partial-build 2) even accept package
        // nick-names lists.  All of the others do not accept any arguments at all.

        final ArrayList<String> MERGED = new ArrayList<>();

        if (nickNamesProvided)
            for (String pkgNickName : nickNames) MERGED.add(pkgNickName);

        if (contains_NonApacheOption_Args)
            for (String pkgNickName : nonApacheOption_Args) MERGED.add(pkgNickName);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Now we finally have the list of Package Nick-Names that was provided by the user!!!
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // This whole thing is Super Complicated, rather than a few lines, because of some quirks 
        // in Apache's Interpretation of how to control CLI Processing, versus how I would have
        // done things.
        // 
        // Breath-Easy, it is all over!

        final ReadOnlyList<String> userProvidedNickNames = nickNamesProvided
            ? new ReadOnlyArrayList<String>(MERGED)
            : null;

        final ReadOnlyList<BuildPackage> userSpecifiedPackages = nickNamesProvided
            ? BuildPackage.nickNameArgVPackages(packageList, userProvidedNickNames)
            : null;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Oh, and one more thing - this is the list of "-OPT" needed to process Auxiliary-Options
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // This list is used next.  This list is returned / bubbled-up right here, to the method
        // and class which invoked this one - namely class 'CLI'.
        // 
        // Class 'CLI' will pass this to constructor for 'AuxiliaryOptRecord'

        final ReadOnlyList<Option> optList = new ReadOnlyArrayList<>(commandLine.getOptions());


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Return everything...
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return new SelectedOptionsRecord
        (
            MENU_CHOICE,            // final String
            userProvidedNickNames,  // final ReadOnlyList<String>
            userSpecifiedPackages,  // final ReadOnlyList<BuildPackage>
            optList                 // final ReadOnlyList<Option>
        );
    }
}