terminfokit-cli 0.1.0

Terminfo compiler, decompiler, query, and conversion commands
Documentation
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
// SPDX-FileCopyrightText: 2026 Yasunobu Sakashita
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;

use clap::{ArgAction, Parser};
use terminfokit::caps::{BooleanCap, NumericCap, StringCap};
use terminfokit::database::{DirectoryDatabase, SearchPath, TransportEncoding, encode_transport};
use terminfokit::format::{
    CapabilitySort, FormatOptions, Layout, NameStyle, SourceFormatter, escape,
};
use terminfokit::{CapabilityState, Compiler, Entry};
use terminfokit_cli::{DiagnosticFormat, Reporter};

#[derive(Debug, Parser)]
#[command(
    name = "tik-infocmp",
    version,
    about = "Decompile or compare terminfo entries"
)]
struct Args {
    /// Write termcap instead of terminfo.
    #[arg(short = 'C')]
    termcap: bool,
    /// Use BSD termcap compatibility.
    #[arg(short = 'K')]
    termcap_compatibility: bool,
    /// Disable the termcap size limit.
    #[arg(short = 'T')]
    termcap_unlimited: bool,
    /// Accept -r; compiled entries are already resolved.
    #[arg(short = 'r')]
    resolve: bool,
    /// Write each entry on one line.
    #[arg(short = '0')]
    compact: bool,
    /// Write one capability per line.
    #[arg(short = '1')]
    one_per_line: bool,
    /// Include user-defined capabilities.
    #[arg(short = 'x')]
    extended: bool,
    /// Use terminfo short names.
    #[arg(short = 'I', conflicts_with = "long_names")]
    short_names: bool,
    /// Use long C variable names.
    #[arg(short = 'L')]
    long_names: bool,
    /// Database root for the first terminal.
    #[arg(short = 'A')]
    database_a: Option<PathBuf>,
    /// Database root for the second terminal.
    #[arg(short = 'B')]
    database_b: Option<PathBuf>,
    /// Print database search roots.
    #[arg(short = 'D')]
    directories: bool,
    /// Compare source files by entry aliases.
    #[arg(short = 'F')]
    source_files: bool,
    /// Write the first entry relative to the second.
    #[arg(short = 'u')]
    relative: bool,
    /// Ignore string padding during comparison.
    #[arg(short = 'p')]
    ignore_padding: bool,
    /// Write hex (1), base64 (2), or both (3).
    #[arg(short = 'Q', value_name = "ENCODING")]
    transport: Option<u8>,
    /// Unsupported terminfo subset.
    #[arg(short = 'R', value_name = "SUBSET", hide = true)]
    unsupported_subset: Option<String>,
    /// Unsupported C initializer output.
    #[arg(short = 'e', hide = true)]
    unsupported_c_initializer: bool,
    /// Unsupported extended C initializer output.
    #[arg(short = 'E', hide = true)]
    unsupported_extended_initializer: bool,
    /// Unsupported initialization analysis.
    #[arg(short = 'i', hide = true)]
    unsupported_initialization: bool,
    /// Show differences; default for multiple terminals.
    #[arg(short = 'd')]
    differences: bool,
    /// Show common capabilities.
    #[arg(short = 'c')]
    common: bool,
    /// Show capabilities absent from both entries.
    #[arg(short = 'n')]
    neither: bool,
    /// Suppress the comparison heading.
    #[arg(short = 'q')]
    quiet: bool,
    /// Set the output width.
    #[arg(short = 'w', default_value_t = 60)]
    width: usize,
    /// Sort capabilities by database (d), terminfo (i), long (l), or termcap (c) name.
    #[arg(short = 's', value_parser = ["d", "i", "l", "c"])]
    sort: Option<String>,
    #[arg(action = ArgAction::Append)]
    terminals: Vec<String>,
    #[arg(long, value_enum, default_value_t = DiagnosticFormat::Human)]
    diagnostic_format: DiagnosticFormat,
}

fn main() -> ExitCode {
    main_from(std::env::args().collect())
}

pub fn main_from(arguments: Vec<String>) -> ExitCode {
    let args = Args::parse_from(arguments);
    match run(args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(code) => ExitCode::from(code),
    }
}

fn run(mut args: Args) -> Result<(), u8> {
    let reporter = Reporter::new("tik-infocmp", args.diagnostic_format);
    if args.unsupported_subset.is_some() {
        reporter.error(
            "TIKC108",
            "-R is unsupported; use -I/-L and filter capabilities",
        );
        return Err(2);
    }
    if args.unsupported_c_initializer || args.unsupported_extended_initializer {
        reporter.error(
            "TIKC109",
            "-e/-E are unsupported; use the Rust API or infocmp -I",
        );
        return Err(2);
    }
    if args.unsupported_initialization {
        reporter.error("TIKC110", "-i is unsupported; query capabilities with tput");
        return Err(2);
    }
    if args.source_files {
        return compare_source_files(&args, reporter);
    }
    if args.directories {
        for root in SearchPath::from_env().roots() {
            println!("{}", root.display());
        }
        if args.terminals.is_empty() {
            return Ok(());
        }
    }
    if args.terminals.is_empty() {
        match std::env::var("TERM") {
            Ok(term) if !term.is_empty() => args.terminals.push(term),
            _ => {
                reporter.error("TIKC101", "terminal required; name one or set TERM");
                return Err(2);
            }
        }
    }
    let mut entries = Vec::new();
    for (index, name) in args.terminals.iter().enumerate() {
        let explicit = if index == 0 {
            args.database_a.as_ref()
        } else {
            args.database_b.as_ref()
        };
        let result = if let Some(root) = explicit {
            DirectoryDatabase::new(root).load(name)
        } else {
            SearchPath::from_env().load(name)
        };
        match result {
            Ok(entry) => entries.push(entry),
            Err(error) => {
                reporter.error("TIKC102", error.to_string());
                return Err(3);
            }
        }
    }
    if let Some(mode) = args.transport {
        if !(1..=3).contains(&mode) {
            reporter.error("TIKC111", "-Q must be 1 (hex), 2 (base64), or 3 (both)");
            return Err(2);
        }
        for entry in &entries {
            if mode != 2 {
                match encode_transport(entry, TransportEncoding::Hex) {
                    Ok(value) => println!("{value}"),
                    Err(error) => {
                        reporter.error("TIKC112", error.to_string());
                        return Err(1);
                    }
                }
            }
            if mode != 1 {
                match encode_transport(entry, TransportEncoding::Base64) {
                    Ok(value) => println!("{value}"),
                    Err(error) => {
                        reporter.error("TIKC112", error.to_string());
                        return Err(1);
                    }
                }
            }
        }
        return Ok(());
    }
    if entries.len() == 1 {
        if args.relative {
            reporter.error("TIKC103", "-u requires exactly two terminal names");
            return Err(2);
        }
        if args.termcap {
            if args.resolve && !args.quiet {
                reporter.info("TIKC104", "entry already resolved");
            }
            let mut options = if args.termcap_compatibility {
                terminfokit::termcap::ConvertOptions::bsd()
            } else {
                terminfokit::termcap::ConvertOptions::ncurses_6_6()
            };
            if args.termcap_unlimited {
                options = options.unlimited();
            }
            match terminfokit::termcap::from_entry(&entries[0], options) {
                Ok(value) => {
                    for warning in value.warnings() {
                        reporter.warning(
                            "TIKC105",
                            format!("{}: {}", warning.capability(), warning.message()),
                        );
                    }
                    print!("{}", value.source());
                    return Ok(());
                }
                Err(error) => {
                    reporter.error("TIKC106", error.to_string());
                    return Err(1);
                }
            }
        }
        let formatter = formatter(&args);
        print!("{}", formatter.format(&entries[0]));
        return Ok(());
    }
    if args.relative {
        if args.termcap {
            reporter.error("TIKC107", "-u cannot be combined with -C");
            return Err(2);
        }
        print!(
            "{}",
            entries[0]
                .relative_to_many(&entries[1..].iter().collect::<Vec<_>>())
                .format(&formatter(&args))
        );
        return Ok(());
    }
    for index in 1..entries.len() {
        compare(
            &args.terminals[0],
            &entries[0],
            &args.terminals[index],
            &entries[index],
            &args,
        );
    }
    Ok(())
}

fn compare_source_files(args: &Args, reporter: Reporter) -> Result<(), u8> {
    if args.terminals.len() != 2 {
        reporter.error("TIKC113", "-F requires exactly two source filenames");
        return Err(2);
    }
    let mut compilations = Vec::new();
    for path in &args.terminals {
        let source = fs::read(path).map_err(|error| {
            reporter.error("TIKC114", format!("{path}: {error}"));
            1u8
        })?;
        let compilation = Compiler::new().compile(&source).map_err(|error| {
            if error.diagnostics().is_empty() {
                reporter.error("TIKC115", format!("{path}: {error}"));
            } else {
                for diagnostic in error.diagnostics() {
                    reporter.diagnostic(diagnostic);
                }
            }
            1u8
        })?;
        compilations.push(compilation);
    }

    let left = compilations[0].entries();
    let right = compilations[1].entries();
    let mut right_matches = vec![0usize; right.len()];
    for left_entry in left {
        let matches: Vec<_> = right
            .iter()
            .enumerate()
            .filter(|(_, right_entry)| entries_share_name(left_entry.entry(), right_entry.entry()))
            .collect();
        match matches.as_slice() {
            [] => println!(
                "{}: no match in {}",
                left_entry.entry().names().primary(),
                args.terminals[1]
            ),
            [(index, right_entry)] => {
                right_matches[*index] += 1;
                compare(
                    left_entry.entry().names().primary(),
                    left_entry.entry(),
                    right_entry.entry().names().primary(),
                    right_entry.entry(),
                    args,
                );
            }
            _ => {
                for (index, _) in &matches {
                    right_matches[*index] += 1;
                }
                println!(
                    "{}: {} matches in {}",
                    left_entry.entry().names().primary(),
                    matches.len(),
                    args.terminals[1]
                );
            }
        }
    }
    for (index, right_entry) in right.iter().enumerate() {
        if right_matches[index] == 0 {
            println!(
                "{}: no match in {}",
                right_entry.entry().names().primary(),
                args.terminals[0]
            );
        }
    }
    Ok(())
}

fn entries_share_name(left: &Entry, right: &Entry) -> bool {
    core::iter::once(left.names().primary())
        .chain(left.names().aliases().iter().map(String::as_str))
        .any(|name| {
            name == right.names().primary()
                || right.names().aliases().iter().any(|alias| alias == name)
        })
}

fn formatter(args: &Args) -> SourceFormatter {
    let layout = if args.compact {
        Layout::Compact
    } else if args.one_per_line {
        Layout::OnePerLine
    } else {
        Layout::Wrapped { width: args.width }
    };
    let names = if args.long_names {
        NameStyle::Long
    } else {
        NameStyle::Short
    };
    let sort = match args.sort.as_deref() {
        Some("d") => CapabilitySort::Storage,
        Some("l") => CapabilitySort::Long,
        Some("c") => CapabilitySort::Termcap,
        Some("i") => CapabilitySort::Short,
        _ if args.long_names => CapabilitySort::Long,
        _ => CapabilitySort::Short,
    };
    SourceFormatter::new(
        FormatOptions::new()
            .with_names(names)
            .with_layout(layout)
            .with_sort(sort)
            .with_extended(args.extended),
    )
}

fn compare(left_name: &str, left: &Entry, right_name: &str, right: &Entry, args: &Args) {
    let normalized_left;
    let normalized_right;
    let (left, right) = if args.ignore_padding {
        normalized_left = without_padding(left);
        normalized_right = without_padding(right);
        (&normalized_left, &normalized_right)
    } else {
        (left, right)
    };
    let diff = left.diff(right);
    if !args.quiet {
        println!("{left_name} vs {right_name}");
    }
    let left_states = states(left);
    let right_states = states(right);
    if args.common {
        for (name, value, absent) in &left_states {
            if !absent
                && right_states
                    .iter()
                    .any(|(other_name, other_value, _)| other_name == name && other_value == value)
            {
                println!("    {name}: {value}");
            }
        }
    }
    if args.neither {
        for (name, _, absent) in &left_states {
            if *absent
                && right_states
                    .iter()
                    .any(|(other_name, _, other_absent)| other_name == name && *other_absent)
            {
                println!("    {name}: absent");
            }
        }
    }
    if args.differences || (!args.common && !args.neither) {
        for item in diff.differences() {
            println!("    {}: {} != {}", item.name(), item.left(), item.right());
        }
    }
}

fn without_padding(entry: &Entry) -> Entry {
    let mut normalized = entry.clone();
    for cap in StringCap::ALL {
        if let CapabilityState::Value(value) = entry.string(*cap) {
            let mut bytes = Vec::new();
            for event in terminfokit::expand::parse_padding(value) {
                if let terminfokit::expand::OutputEvent::Bytes(value) = event {
                    bytes.extend_from_slice(value);
                }
            }
            let _ = normalized.set_string(*cap, bytes);
        }
    }
    for capability in entry.extended() {
        if let CapabilityState::Value(terminfokit::ExtendedValue::String(value)) =
            capability.state()
        {
            let mut bytes = Vec::new();
            for event in terminfokit::expand::parse_padding(value) {
                if let terminfokit::expand::OutputEvent::Bytes(value) = event {
                    bytes.extend_from_slice(value);
                }
            }
            let _ = normalized
                .set_extended(capability.name(), terminfokit::ExtendedValue::String(bytes));
        }
    }
    normalized
}

fn states(entry: &Entry) -> Vec<(String, String, bool)> {
    let mut values = Vec::with_capacity(BooleanCap::COUNT + NumericCap::COUNT + StringCap::COUNT);
    for cap in BooleanCap::ALL {
        let state = entry.boolean(*cap);
        values.push((
            cap.short_name().into(),
            format!("{state:?}"),
            state.is_absent(),
        ));
    }
    for cap in NumericCap::ALL {
        let state = entry.number(*cap);
        values.push((
            cap.short_name().into(),
            format!("{state:?}"),
            state.is_absent(),
        ));
    }
    for cap in StringCap::ALL {
        let state = entry.string(*cap);
        let text = match state {
            CapabilityState::Absent => "Absent".into(),
            CapabilityState::Cancelled => "Cancelled".into(),
            CapabilityState::Value(value) => escape(value),
        };
        values.push((cap.short_name().into(), text, state.is_absent()));
    }
    values
}