cargo-kconfig 0.0.4

Kconfig macro library and user interface for the Kconfig file format from the Linux Kernel
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
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
/*
 Cargo KConfig - KConfig parser
 Copyright (C) 2022  Sjoerd van Leent

--------------------------------------------------------------------------------

Copyright Notice: Apache

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

--------------------------------------------------------------------------------

Copyright Notice: GPLv2

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

--------------------------------------------------------------------------------

Copyright Notice: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

//! This module contains the controller of the client, allowing requests
//! from the presenter to be fulfilled.

use std::{
    collections::{HashMap, VecDeque},
    fs::{remove_file, OpenOptions},
    io::Read,
    io::{stdin, stdout, Write},
    path::PathBuf,
    process::exit,
    str::Chars,
};

use kconfig_parser::MacroLexer;
use kconfig_represent::{ConfigRegistry, LoadError, Menu, MenuItemDescriptor};

use crate::util;

use super::{CargoKconfigConfig, ConfigGetOpt, ConfigSetOpt};

pub struct ConfigSetController {
    opt: ConfigSetOpt,
}

impl ConfigSetController {
    pub fn run(&self) {
        let mut config = ConfigGetController::load();
        let default_config = CargoKconfigConfig::default();
        match &self.opt {
            ConfigSetOpt::Kconfig(v) => match v.is_empty() {
                true => config.set_kconfig(&default_config.kconfig()),
                false => config.set_kconfig(&PathBuf::from(v)),
            },
            ConfigSetOpt::Dotconfig(v) => match v.is_empty() {
                true => config.set_dotconfig(&default_config.dotconfig()),
                false => config.set_dotconfig(&PathBuf::from(v)),
            },
        }
        Self::write(&config);
    }

    fn write(config: &CargoKconfigConfig) {
        let default_config = CargoKconfigConfig::default();
        let should_delete = match OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(".cargo-kconfig")
        {
            Ok(mut f) => {
                if default_config.kconfig() != config.kconfig() {
                    writeln!(f, "input = {}", Self::pathbuf_tostring(&config.kconfig())).unwrap();
                }
                if default_config.dotconfig() != config.dotconfig() {
                    writeln!(
                        f,
                        "output = {}",
                        Self::pathbuf_tostring(&config.dotconfig())
                    )
                    .unwrap();
                }
                f.flush().unwrap();
                f.metadata().unwrap().len() == 0
            }
            Err(e) => panic!("Could not write to cargo-kconfig configuration file: {e}"),
        };

        if should_delete {
            remove_file(".cargo-kconfig").unwrap();
        }
    }

    fn pathbuf_tostring(b: &PathBuf) -> String {
        b.to_string_lossy()
            .replace("\\", "\\\\")
            .replace("\n", "\\\n")
            .replace("\r", "\\\r")
    }
}

impl From<ConfigSetOpt> for ConfigSetController {
    fn from(opt: ConfigSetOpt) -> Self {
        Self { opt }
    }
}

pub struct ConfigGetController {
    opt: ConfigGetOpt,
}

impl From<ConfigGetOpt> for ConfigGetController {
    fn from(opt: ConfigGetOpt) -> Self {
        Self { opt }
    }
}

impl ConfigGetController {
    pub fn run(&self) {
        let config = Self::load();
        match &self.opt {
            ConfigGetOpt::List => {
                println!("input = {}", config.kconfig().display());
                println!("output = {}", config.dotconfig().display());
            }
            ConfigGetOpt::Kconfig => println!("{}", config.kconfig().display()),
            ConfigGetOpt::Dotconfig => println!("{}", config.dotconfig().display()),
        }
    }

    pub fn load() -> CargoKconfigConfig {
        match OpenOptions::new().read(true).open(".cargo-kconfig") {
            Ok(mut f) => Self::load_from_stream(&mut f),
            Err(_) => CargoKconfigConfig::default(),
        }
    }

    pub fn load_from_stream<R>(r: &mut R) -> CargoKconfigConfig
    where
        R: Read,
    {
        let mut buf = String::new();
        if let Err(e) = r.read_to_string(&mut buf) {
            eprintln!("Can not read found cargo-kconfig configuration: {e}");
            return CargoKconfigConfig::default();
        }

        let mut chars = buf.chars();

        let mut rawentries = HashMap::new();

        loop {
            let rawentry = Self::read_next_entry(&mut chars);
            match rawentry {
                Some((optname, optvalue)) => {
                    rawentries.insert(optname, optvalue);
                }
                None => break,
            }
        }

        CargoKconfigConfig::from(&rawentries)
    }

    pub fn read_next_entry(chars: &mut Chars) -> Option<(String, String)> {
        let mut is_lhs = true;
        let mut is_escape = false;

        let mut lhs = String::new();
        let mut rhs = String::new();

        loop {
            let maybe_c = chars.next();
            match maybe_c {
                Some(c) => {
                    if is_lhs {
                        if c == '\n' || c == '\r' {
                            if lhs.len() != 0 {
                                eprintln!(
                                    "Configuration key contains illegal value: {}, skipped",
                                    c as i32
                                );
                            }
                        } else if c == '=' && !is_escape {
                            is_lhs = false;
                        } else if is_escape {
                            is_escape = false;
                            lhs.push(c);
                        } else if c == '\\' {
                            is_escape = true;
                        } else {
                            lhs.push(c);
                        }
                    } else {
                        if is_escape {
                            is_escape = false;
                            rhs.push(c);
                        } else if c == '\\' {
                            is_escape = true;
                        } else if c == '\r' || c == '\n' {
                            break;
                        } else {
                            rhs.push(c);
                        }
                    }
                }
                None => {
                    if is_lhs {
                        if lhs.len() != 0 {
                            eprintln!("Configuration file ended premature")
                        }
                        return None;
                    }
                    break;
                }
            }
        }

        Some((lhs.trim().to_string(), rhs.trim().to_string()))
    }
}

pub struct ListController {
    vec_deque: VecDeque<String>,
    maxwidth: u16,
}

impl From<&Vec<String>> for ListController {
    fn from(vec: &Vec<String>) -> Self {
        // TODO: Somehow determine terminal width
        Self {
            vec_deque: vec.clone().into_iter().collect::<VecDeque<String>>(),
            maxwidth: 80,
        }
    }
}

impl ListController {
    pub fn run(&self) {
        let registry = load_config_registry();
        let maybe_menu = registry.lookup_menu(&registry.main_menu_name());
        match maybe_menu {
            Some(menu) => {
                if !self.print_maybe_menu(&registry, &menu, &self.vec_deque, 0) {
                    eprintln!("⛔ Menu not found")
                }
            }
            None => eprintln!("⛔ Menu not found"),
        }
    }

    fn print_maybe_menu(
        &self,
        registry: &ConfigRegistry,
        menu: &Box<Menu>,
        vec_deque: &VecDeque<String>,
        offset: u8,
    ) -> bool {
        let mut found = false;
        if vec_deque.len() == 0 {
            for descriptor in menu.sub_descriptors() {
                self.print_value(offset, &Self::format_descriptor(registry, &descriptor));
            }
            found = true;
        } else {
            let mut new_deque = vec_deque.clone();
            let item = new_deque.pop_front().unwrap();
            for descriptor in menu.sub_descriptors() {
                if descriptor.to_string() == item {
                    let maybe_menu = registry.lookup_menu(&item);
                    match maybe_menu {
                        Some(menu) => {
                            self.print_value(
                                offset,
                                &Self::format_descriptor(registry, &descriptor),
                            );
                            if self.print_maybe_menu(registry, menu, &new_deque, offset + 1) {
                                found = true;
                            }
                        }
                        None => (),
                    }
                }
            }
        }
        found
    }

    fn print_value(&self, offset: u8, item: &str) {
        // TODO: Would be nicer on word boundary
        let offset = match offset < (self.maxwidth / 4) as u8 {
            true => offset,
            false => (self.maxwidth / 4) as u8,
        };
        let mut item = item.chars();
        let mut next = item.next();
        let mut new_iteration = false;
        loop {
            if new_iteration {
                println!("");
            }
            if let Some(_) = next {
                for i in 0..offset {
                    match new_iteration {
                        true => {
                            print!("| ")
                        }
                        false => {
                            if i == (offset - 1) {
                                print!("+-")
                            } else {
                                print!("| ")
                            }
                        }
                    }
                }
            }

            if new_iteration {
                print!("    ");
            }

            for _ in (offset as u16)..self.maxwidth {
                match next {
                    Some(c) => print!("{}", c),
                    None => {
                        println!("");
                        return;
                    }
                }
                next = item.next();
            }

            if let None = next {
                break;
            } else {
                new_iteration = true;
            }
        }
    }

    fn format_descriptor(registry: &ConfigRegistry, descriptor: &MenuItemDescriptor) -> String {
        let maybe_menu = registry.lookup_menu(&descriptor.to_string());

        match maybe_menu {
            Some(menu) => format!("{menu} --->"),
            None => {
                let maybe_config_item = registry.lookup_config(&descriptor.to_string());
                match maybe_config_item {
                    Some(item) => {
                        let prefix = match item.value_is_default() {
                            true => "[ ]",
                            false => "[x]",
                        };
                        format!(
                            "{} {} [{}]: {}",
                            prefix,
                            descriptor,
                            item.prompt(),
                            item.to_string_value()
                        )
                    }
                    None => format!(""),
                }
            }
        }
    }
}

pub struct InfoController {
    name: String,
}

impl From<&str> for InfoController {
    fn from(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}

impl InfoController {
    pub fn run(&self) {
        let registry = load_config_registry();
        let maybe_config = registry.lookup_config(&self.name);
        match maybe_config {
            Some(config) => {
                let mut first = true;
                for item in config.info() {
                    if first {
                        first = false;
                    } else {
                        println!("");
                    }
                    println!("{}", item);
                }

                if first {
                    println!("⛔ No information available for entry {}", &self.name);
                }
            }
            None => eprintln!("⛔ Configuration item {} not available", self.name),
        }
    }
}

pub struct UpdateController {
    name: String,
}

impl From<&str> for UpdateController {
    fn from(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}
impl UpdateController {
    pub fn run(&self) {
        let mut registry = load_config_registry();
        let mutation_mode = registry.config_mutation_mode(&self.name);
        let maybe_config = registry.lookup_config_mut(&self.name);
        match maybe_config {
            Some(config) => match mutation_mode {
                kconfig_represent::ConfigMutationMode::ThroughString(mode) => match mode {
                    kconfig_represent::InputMode::String => {
                        println!(
                            "{} [Current value: {}] ",
                            config.prompt(),
                            config.to_string_value()
                        );
                        config.from_string_value(&Self::read_lines());
                    }
                    kconfig_represent::InputMode::Hex => {
                        print!(
                            "{} [Current value: {}]: ",
                            config.prompt(),
                            config.to_string_value()
                        );
                        config.from_string_value(&Self::read_line());
                    }
                    kconfig_represent::InputMode::Int => {
                        print!(
                            "{} [Current value: {}]: ",
                            config.prompt(),
                            config.to_string_value()
                        );
                        config.from_string_value(&Self::read_line());
                    }
                },
                kconfig_represent::ConfigMutationMode::ThroughStep => {
                    if let Err(e) = config.next_step() {
                        panic!("⛔ Could not mutate value: {e}");
                    }
                }
                kconfig_represent::ConfigMutationMode::None => panic!(
                    "⛔ Configuration item {} should be a mutable item",
                    self.name
                ),
            },
            None => eprintln!("⛔ Configuration item {} not available", self.name),
        }

        let config = ConfigGetController::load();
        if let Err(e) = registry.write_dotconfig_file(&config.dotconfig().to_string_lossy()) {
            panic!(
                "⛔ Could not write to {} caused by: {}",
                config.dotconfig().to_string_lossy(),
                e
            )
        }
    }

    fn read_line() -> String {
        if let Err(e) = stdout().flush() {
            panic!("⛔ Could not flush output to terminal: {e}");
        }
        let mut buf = String::new();
        if let Err(e) = stdin().read_line(&mut buf) {
            panic!("⛔ Could not read data from terminal: {e}");
        }
        buf
    }

    fn read_lines() -> String {
        println!("--- Enter two empty newlines to complete the value ----");
        if let Err(e) = stdout().flush() {
            panic!("⛔ Could not flush output to terminal: {e}");
        }
        let mut result = String::new();
        let mut first_empty_newline = false;
        let mut second_empty_newline = false;
        while !(first_empty_newline && second_empty_newline) {
            let mut buf = String::new();
            let has_previous = result.len() > 0;
            if let Err(e) = stdin().read_line(&mut buf) {
                panic!("⛔ Could not read data from terminal: {e}");
            }
            let mut processed_len = 0;
            let len = buf.len();
            let mut new_buf = String::new();
            for c in buf.chars() {
                if processed_len < len - 1 {
                    new_buf.push(c);
                }
                processed_len += 1;
            }
            stdout().flush().unwrap();
            if new_buf.is_empty() {
                second_empty_newline = first_empty_newline;
                first_empty_newline = true;
            } else {
                if first_empty_newline {
                    result.push_str("\n");
                }
                first_empty_newline = false;
                second_empty_newline = false;
                if has_previous {
                    result.push_str("\n");
                }
                result.push_str(&new_buf);
            }
        }
        result
    }
}

fn load_config_registry() -> ConfigRegistry {
    let config = ConfigGetController::load();
    let mut lexer = MacroLexer::new(util::lex_from_file(&config.kconfig().to_string_lossy()));
    let ast = crate::util::parse(&mut lexer);
    let mut registry = match ConfigRegistry::new(&ast, &lexer.symbol_table()) {
        Ok(registry) => registry,
        Err(e) => {
            eprintln!("{}", e);
            exit(1);
        }
    };
    let maybe_load_error: Option<LoadError> =
        util::load_dot_config_into_registry(&config.dotconfig().to_string_lossy(), &mut registry);

    if let Some(load_error) = maybe_load_error {
        eprintln!("{}", load_error.to_string())
    }
    registry
}