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

 * Copyright (C) 2024-present Puter Technologies Inc.

 * 

 * This file is part of Puter.

 * 

 * Puter is free software: you can redistribute it and/or modify

 * it under the terms of the GNU Affero General Public License as published

 * by the Free Software Foundation, either version 3 of the License, or

 * (at your option) any later version.

 * 

 * This program is distributed in the hope that it will be useful,

 * but WITHOUT ANY WARRANTY; without even the implied warranty of

 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 * GNU Affero General Public License for more details.

 * 

 * You should have received a copy of the GNU Affero General Public License

 * along with this program.  If not, see <https://www.gnu.org/licenses/>.

 */

const levenshtein = require('js-levenshtein');
const DiffMatchPatch = require('diff-match-patch');
const enq = require('enquirer');
const dmp = new DiffMatchPatch();
const dedent = require('dedent');

const { walk, EXCLUDE_LISTS } = require('file-walker');
const { CommentParser } = require('../comment-parser/main');

const fs = require('fs');
const path_ = require('path');


/**

* Compares two license headers and returns their Levenshtein distance and formatted diff

* @param {Object} params - The parameters object

* @param {string} params.header1 - First header text to compare

* @param {string} params.header2 - Second header text to compare  

* @param {boolean} [params.distance_only=false] - If true, only return distance without diff

* @returns {Object} Object containing distance and formatted terminal diff

*/
const CompareFn = ({ header1, header2, distance_only = false }) => {
    
    // Calculate Levenshtein distance
    const distance = levenshtein(header1, header2);
    // console.log(`Levenshtein distance: ${distance}`);
    
    if ( distance_only ) return { distance };

    // Generate diffs using diff-match-patch
    const diffs = dmp.diff_main(header1, header2);
    dmp.diff_cleanupSemantic(diffs);
    
    let term_diff = '';

    // Manually format diffs for terminal display
    diffs.forEach(([type, text]) => {
        switch (type) {
            case DiffMatchPatch.DIFF_INSERT:
            term_diff += `\x1b[32m${text}\x1b[0m`;  // Green for insertions
            break;
            case DiffMatchPatch.DIFF_DELETE:
            term_diff += `\x1b[31m${text}\x1b[0m`;  // Red for deletions
            break;
            case DiffMatchPatch.DIFF_EQUAL:
            term_diff += text;  // No color for equal parts
            break;
        }
    });
    
    return {
        distance,
        term_diff,
    };
}

/**

* Creates a license checker instance that can compare and validate license headers

* @param {Object} params - Configuration parameters

* @param {Object} params.comment_parser - Comment parser instance to use

* @param {string} params.desired_header - The expected license header text

* @returns {Object} License checker instance with compare and supports methods

*/
const LicenseChecker = ({

    comment_parser,

    desired_header,

}) => {
    const supports = ({ filename }) => {
        return comment_parser.supports({ filename });
    };
    const compare = async ({ filename, source }) => {
        const headers = await comment_parser.extract_top_comments(
            { filename, source });
        const headers_lines = headers.map(h => h.lines);
            
        if ( headers.length < 1 ) {
            return {
                has_header: false,
            };
        }
        
        // console.log('headers', headers);

        let top = 0;
        let bottom = 0;
        let current_distance = Number.MAX_SAFE_INTEGER;
        
        // "wah"
        for ( let i=1 ; i <= headers.length ; i++ ) {
            const combined = headers_lines.slice(top, i).flat();
            const combined_txt = combined.join('\n');
            const { distance } =
                CompareFn({
                    header1: desired_header,
                    header2: combined_txt,
                    distance_only: true,
                });
            if ( distance < current_distance ) {
                current_distance = distance;
                bottom = i;
            } else {
                break;
            }
        }
        // "woop"
        for ( let i=1 ; i < headers.length ; i++ ) {
            const combined = headers_lines.slice(i, bottom).flat();
            const combined_txt = combined.join('\n');
            const { distance } =
                CompareFn({
                    header1: desired_header,
                    header2: combined_txt,
                    distance_only: true,
                });
            if ( distance < current_distance ) {
                current_distance = distance;
                top = i;
            } else {
                break;
            }
        }
        
        // console.log('headers', headers);

        const combined = headers_lines.slice(top, bottom).flat();
        const combined_txt = combined.join('\n');
            
        const diff_info = CompareFn({
            header1: desired_header,
            header2: combined_txt,
        })
        
        if ( diff_info.distance > 0.7*desired_header.length ) {
            return {
                has_header: false,
            };
        }
        
        diff_info.range = [
            headers[top].range[0],
            headers[bottom-1].range[1],
        ];
        
        diff_info.has_header = true;
            
        return diff_info;
    };
    return {
        compare,
        supports,
    };
};

const license_check_test = async ({ options }) => {
    const comment_parser = CommentParser();
    const license_checker = LicenseChecker({
        comment_parser,
        desired_header: fs.readFileSync(
            path_.join(__dirname, '../../doc/license_header.txt'),
            'utf-8',
        ),
    });
    
    const walk_iterator = walk({
        excludes: EXCLUDE_LISTS.NOT_AGPL,
    }, path_.join(__dirname, '../..'));
    for await ( const value of walk_iterator ) {
        if ( value.is_dir ) continue;
        if ( options?.filename && value.name !== options.filename ) continue;
        console.log(value.path);
        const source = fs.readFileSync(value.path, 'utf-8');
        const diff_info = await license_checker.compare({
            filename: value.name,
            source,
        })
        if ( diff_info ) {
            process.stdout.write('\x1B[36;1m=======\x1B[0m\n');
            process.stdout.write(diff_info.term_diff);
            process.stdout.write('\n\x1B[36;1m=======\x1B[0m\n');
            // console.log('headers', headers);
        } else {
            console.log('NO COMMENT');
        }
        
        console.log('RANGE', diff_info.range)
        
        const new_comment = comment_parser.output_comment({
            filename: value.name,
            style: 'block',
            text: 'some text\nto display'
        });

        console.log('NEW COMMENT?', new_comment);
    }
};


/**

* Executes the main command line interface for the license header tool.

* Sets up Commander.js program with commands for checking and syncing license headers.

* Handles configuration file loading and command execution.

* 

* @async

* @returns {Promise<void>} Resolves when command execution is complete

*/
const cmd_check_fn = async () => {
    const comment_parser = CommentParser();
    const license_checker = LicenseChecker({
        comment_parser,
        desired_header: fs.readFileSync(
            path_.join(__dirname, '../../doc/license_header.txt'),
            'utf-8',
        ),
    });
    
    const counts = {
        ok: 0,
        missing: 0,
        conflict: 0,
        error: 0,
        unsupported: 0,
    };
    
    const walk_iterator = walk({
        excludes: EXCLUDE_LISTS.NOT_AGPL,
    }, path_.join(__dirname, '../..'));
    for await ( const value of walk_iterator ) {
        if ( value.is_dir ) continue;

        process.stdout.write(value.path + ' ... ');

        if ( ! license_checker.supports({ filename: value.name }) ) {
            process.stdout.write(`\x1B[37;1mUNSUPPORTED\x1B[0m\n`);
            counts.unsupported++;
            continue;
        }

        const source = fs.readFileSync(value.path, 'utf-8');
        const diff_info = await license_checker.compare({
            filename: value.name,
            source,
        })
        if ( ! diff_info ) {
            counts.error++;
            continue;
        }
        if ( ! diff_info.has_header ) {
            counts.missing++;
            process.stdout.write(`\x1B[33;1mMISSING\x1B[0m\n`);
            continue;
        }
        if ( diff_info ) {
            if ( diff_info.distance !== 0 ) {
                counts.conflict++;
                process.stdout.write(`\x1B[31;1mCONFLICT\x1B[0m\n`);
            } else {
                counts.ok++;
                process.stdout.write(`\x1B[32;1mOK\x1B[0m\n`);
            }
        } else {
            console.log('NO COMMENT');
        }
    }
    
    const { Table } = require('console-table-printer');
    const t = new Table({
        columns: [
            {
                title: 'License Header',
                name: 'situation', alignment: 'left', color: 'white_bold' },
            {
                title: 'Number of Files',
                name: 'count', alignment: 'right' },
        ],
        colorMap: {
            green: '\x1B[32;1m',
            yellow: '\x1B[33;1m',
            red: '\x1B[31;1m',
        }
    });
    
    console.log('');
    
    if ( counts.error > 0 ) {
        console.log(`\x1B[31;1mTHERE WERE SOME ERRORS!\x1B[0m`);
        console.log('check the log above for the stack trace');
        console.log('');
        t.addRow({ situation: 'error', count: counts.error },
            { color: 'red' });
    }
    
    console.log(dedent(`

        \x1B[31;1mAny text below is mostly lies!\x1B[0m

        This tool is still being developed and most of what's

        described is "the plan" rather than a thing that will

        actually happen.

        \x1B[31;1m^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\x1B[0m

    `));

    if ( counts.conflict ) {
        console.log(dedent(`

            \x1B[37;1mIt looks like you have some conflicts!\x1B[0m

            Run the following command to update license headers:



               \x1B[36;1maddlicense sync\x1B[0m

               

            This will begin an interactive license update.

            Any time the license doesn't quite match you will

            be given the option to replace it or skip the file.

            \x1B[90mSee \`addlicense help sync\` for other options.\x1B[0m

            

            You will also be able to choose

            "remember for headers matching this one"

            if you know the same issue will come up later.

        `));
    } else if ( counts.missing ) {
        console.log(dedent(`

            \x1B[37;1mSome missing license headers!\x1B[0m

            Run the following command to add the missing license headers:



               \x1B[36;1maddlicense sync\x1B[0m

        `));
    } else {
        console.log(dedent(`

            \x1B[37;1mNo action to perform!\x1B[0m

            Run the following command to do absolutely nothing:



               \x1B[36;1maddlicense sync\x1B[0m

        `));
    }

    console.log('');

    t.addRow({ situation: 'ok', count: counts.ok },
        { color: 'green' });
    t.addRow({ situation: 'missing', count: counts.missing },
        { color: 'yellow' });
    t.addRow({ situation: 'conflict', count: counts.conflict },
        { color: 'red' });
    t.addRow({ situation: 'unsupported', count: counts.unsupported });
    t.printTable();
};


/**

* Synchronizes license headers in source files by adding missing headers and handling conflicts

* 

* Walks through files, checks for license headers, and:

* - Adds headers to files missing them

* - Prompts user to resolve conflicts when headers don't match

* - Handles duplicate headers by allowing removal

* - Tracks counts of different header statuses (ok, missing, conflict, etc)

* 

* @returns {Promise<void>} Resolves when synchronization is complete

*/
const cmd_sync_fn = async () => {
    const comment_parser = CommentParser();
    const desired_header = fs.readFileSync(
        path_.join(__dirname, '../../doc/license_header.txt'),
        'utf-8',
    );
    const license_checker = LicenseChecker({
        comment_parser,
        desired_header,
    });

    const counts = {
        ok: 0,
        missing: 0,
        conflict: 0,
        error: 0,
        unsupported: 0,
    };
    
    const walk_iterator = walk({
        excludes: EXCLUDE_LISTS.NOT_AGPL,
    }, '.');
    for await ( const value of walk_iterator ) {
        if ( value.is_dir ) continue;

        process.stdout.write(value.path + ' ... ');

        if ( ! license_checker.supports({ filename: value.name }) ) {
            process.stdout.write(`\x1B[37;1mUNSUPPORTED\x1B[0m\n`);
            counts.unsupported++;
            continue;
        }

        const source = fs.readFileSync(value.path, 'utf-8');
        const diff_info = await license_checker.compare({
            filename: value.name,
            source,
        })
        if ( ! diff_info ) {
            counts.error++;
            continue;
        }
        if ( ! diff_info.has_header ) {
            fs.writeFileSync(
                value.path,
                comment_parser.output_comment({
                    style: 'block',
                    filename: value.name,
                    text: desired_header,
                }) +
                '\n' +
                source
            );
            continue;
        }
        if ( diff_info ) {
            if ( diff_info.distance !== 0 ) {
                counts.conflict++;
                process.stdout.write(`\x1B[31;1mCONFLICT\x1B[0m\n`);
                process.stdout.write('\x1B[36;1m=======\x1B[0m\n');
                process.stdout.write(diff_info.term_diff);
                process.stdout.write('\n\x1B[36;1m=======\x1B[0m\n');
                const prompt = new enq.Select({
                    message: 'Select Action',
                    choices: [
                        { name: 'skip', message: 'Skip' },
                        { name: 'replace', message: 'Replace' },
                    ]
                })
                const action = await prompt.run();
                if ( action === 'skip' ) continue;
                const before = source.slice(0, diff_info.range[0]);
                const after = source.slice(diff_info.range[1]);
                const new_source = before +
                    comment_parser.output_comment({
                        style: 'block',
                        filename: value.name,
                        text: desired_header,
                    }) +
                    after;
                fs.writeFileSync(value.path, new_source);
            } else {
                let cut_diff_info = diff_info;
                let cut_source = source;
                const cut_header = async () => {
                    cut_source = cut_source.slice(cut_diff_info.range[1]);
                    cut_diff_info = await license_checker.compare({
                        filename: value.name,
                        source: cut_source,
                    });
                };
                await cut_header();
                const cut_range = [
                    diff_info.range[1],
                    diff_info.range[1],
                ];
                const cut_diff_infos = [];
                while ( cut_diff_info.has_header ) {
                    cut_diff_infos.push(cut_diff_info);
                    cut_range[1] += cut_diff_info.range[1];
                    await cut_header();
                }
                if ( cut_range[0] !== cut_range[1] ) {
                    process.stdout.write(`\x1B[31;1mDUPLICATE\x1B[0m\n`);
                    process.stdout.write('\x1B[36;1m==== KEEP ====\x1B[0m\n');
                    process.stdout.write(diff_info.term_diff + '\n');
                    process.stdout.write('\x1B[36;1m==== REMOVE ====\x1B[0m\n');
                    for ( const diff_info of cut_diff_infos ) {
                        process.stdout.write(diff_info.term_diff);
                    }
                    process.stdout.write('\n\x1B[36;1m=======\x1B[0m\n');
                    const prompt = new enq.Select({
                        message: 'Select Action',
                        choices: [
                            { name: 'skip', message: 'Skip' },
                            { name: 'remove', message: 'Remove' },
                        ]
                    })
                    const action = await prompt.run();
                    if ( action === 'skip' ) continue;
                    const new_source =
                        source.slice(0, cut_range[0]) +
                        source.slice(cut_range[1]);
                    fs.writeFileSync(value.path, new_source);
                }
                counts.ok++;
                process.stdout.write(`\x1B[32;1mOK\x1B[0m\n`);
            }
        } else {
            console.log('NO COMMENT');
        }
    }
    
    const { Table } = require('console-table-printer');
    const t = new Table({
        columns: [
            {
                title: 'License Header',
                name: 'situation', alignment: 'left', color: 'white_bold' },
            {
                title: 'Number of Files',
                name: 'count', alignment: 'right' },
        ],
        colorMap: {
            green: '\x1B[32;1m',
            yellow: '\x1B[33;1m',
            red: '\x1B[31;1m',
        }
    });
    
    console.log('');
    
    if ( counts.error > 0 ) {
        console.log(`\x1B[31;1mTHERE WERE SOME ERRORS!\x1B[0m`);
        console.log('check the log above for the stack trace');
        console.log('');
        t.addRow({ situation: 'error', count: counts.error },
            { color: 'red' });
    }
    
    console.log(dedent(`

        \x1B[31;1mAny text below is mostly lies!\x1B[0m

        This tool is still being developed and most of what's

        described is "the plan" rather than a thing that will

        actually happen.

        \x1B[31;1m^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\x1B[0m

    `));

    if ( counts.conflict ) {
        console.log(dedent(`

            \x1B[37;1mIt looks like you have some conflicts!\x1B[0m

            Run the following command to update license headers:



               \x1B[36;1maddlicense sync\x1B[0m

               

            This will begin an interactive license update.

            Any time the license doesn't quite match you will

            be given the option to replace it or skip the file.

            \x1B[90mSee \`addlicense help sync\` for other options.\x1B[0m

            

            You will also be able to choose

            "remember for headers matching this one"

            if you know the same issue will come up later.

        `));
    } else if ( counts.missing ) {
        console.log(dedent(`

            \x1B[37;1mSome missing license headers!\x1B[0m

            Run the following command to add the missing license headers:



               \x1B[36;1maddlicense sync\x1B[0m

        `));
    } else {
        console.log(dedent(`

            \x1B[37;1mNo action to perform!\x1B[0m

            Run the following command to do absolutely nothing:



               \x1B[36;1maddlicense sync\x1B[0m

        `));
    }

    console.log('');

    t.addRow({ situation: 'ok', count: counts.ok },
        { color: 'green' });
    t.addRow({ situation: 'missing', count: counts.missing },
        { color: 'yellow' });
    t.addRow({ situation: 'conflict', count: counts.conflict },
        { color: 'red' });
    t.addRow({ situation: 'unsupported', count: counts.unsupported });
    t.printTable();
};


/**

* Main entry point for the license header tool.

* Sets up command line interface using Commander and processes commands.

* Handles 'check' and 'sync' commands for managing license headers in files.

* 

* @returns {Promise<void>} Resolves when command processing is complete

*/
const main = async () => {
    const { program } = require('commander');
    const helptext = dedent(`

        Usage: usage text

    `);
    
    const run_command = async ({ cmd, cmd_fn }) => {
        const options = {
            program: program.opts(),
            command: cmd.opts(),
        };
        console.log('options', options);
        
        if ( ! fs.existsSync(options.program.config) ) {
            // TODO: configuration wizard
            fs.writeFileSync(options.program.config, '');
        }
        
        await cmd_fn({ options });
    };
    
    program
        .name('addlicense')
        .option('-c, --config', 'configuration file', 'addlicense.yml')
        .addHelpText('before', helptext)
        ;
    const cmd_check = program.command('check')
        .description('check license headers')
        .option('-n, --non-interactive', 'disable prompting')
        .action(() => {
            run_command({ cmd: cmd_check, cmd_fn: cmd_check_fn });
        })
    const cmd_sync = program.command('sync')
        .description('synchronize files with license header rules')
        .option('-n, --non-interactive', 'disable prompting')
        .action(() => {
            run_command({ cmd: cmd_sync, cmd_fn: cmd_sync_fn })
        })
    program.parse(process.argv);
        
};

if ( require.main === module ) {
    main();
}