link-cli 0.2.2

A CLI tool for links manipulation
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
//! LinkStorage - Persistent storage for links
//!
//! This module provides the LinkStorage struct for managing link persistence.

use anyhow::{Context, Result};
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;

use crate::error::LinkError;
use crate::link::Link;

/// LinkStorage provides persistent storage for links
/// Corresponds to the storage functionality in NamedLinksDecorator in C#
pub struct LinkStorage {
    links: HashMap<u32, Link>,
    names: HashMap<u32, String>,
    name_to_id: HashMap<String, u32>,
    next_id: u32,
    db_path: String,
    trace: bool,
}

impl LinkStorage {
    /// Creates a new LinkStorage instance
    pub fn new(db_path: &str, trace: bool) -> Result<Self> {
        let mut storage = Self {
            links: HashMap::new(),
            names: HashMap::new(),
            name_to_id: HashMap::new(),
            next_id: 1,
            db_path: db_path.to_string(),
            trace,
        };

        // Load existing database if it exists
        if Path::new(db_path).exists() {
            storage.load()?;
        }

        Ok(storage)
    }

    /// Loads links from the database file
    fn load(&mut self) -> Result<()> {
        let file = File::open(&self.db_path)
            .with_context(|| format!("Failed to open database: {}", self.db_path))?;

        let reader = BufReader::new(file);

        for line in reader.lines() {
            let line = line?;
            let line = line.trim();

            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse link format: (index source target) or (index source target "name")
            if let Some((link, name)) = self.parse_link_line(line) {
                self.links.insert(link.index, link);
                if link.index >= self.next_id {
                    self.next_id = link.index + 1;
                }
                if let Some(name) = name {
                    self.names.insert(link.index, name.clone());
                    self.name_to_id.insert(name, link.index);
                }
            }
        }

        if self.trace {
            eprintln!(
                "[TRACE] Loaded {} links from {}",
                self.links.len(),
                self.db_path
            );
        }

        Ok(())
    }

    /// Parses a single link line from the database
    fn parse_link_line(&self, line: &str) -> Option<(Link, Option<String>)> {
        // Simple format: (index source target) or (index source target "name")
        let line = line.trim_matches(|c| c == '(' || c == ')');
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() >= 3 {
            let index = parts[0].parse().ok()?;
            let source = parts[1].parse().ok()?;
            let target = parts[2].parse().ok()?;
            let name = if parts.len() > 3 {
                Some(parts[3].trim_matches('"').to_string())
            } else {
                None
            };
            return Some((Link::new(index, source, target), name));
        }

        None
    }

    /// Saves all links to the database file
    pub fn save(&self) -> Result<()> {
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&self.db_path)
            .with_context(|| format!("Failed to create database: {}", self.db_path))?;

        let mut writer = BufWriter::new(file);

        // Sort by index for consistent output
        let mut links: Vec<_> = self.links.values().collect();
        links.sort_by_key(|l| l.index);

        for link in links {
            if let Some(name) = self.names.get(&link.index) {
                writeln!(
                    writer,
                    "({} {} {} \"{}\")",
                    link.index, link.source, link.target, name
                )?;
            } else {
                writeln!(writer, "({} {} {})", link.index, link.source, link.target)?;
            }
        }

        writer.flush()?;

        if self.trace {
            eprintln!(
                "[TRACE] Saved {} links to {}",
                self.links.len(),
                self.db_path
            );
        }

        Ok(())
    }

    /// Creates a new link and returns its ID
    pub fn create(&mut self, source: u32, target: u32) -> u32 {
        let id = self.next_id;
        self.next_id += 1;

        let link = Link::new(id, source, target);
        self.links.insert(id, link);

        if self.trace {
            eprintln!("[TRACE] Created link: ({} {} {})", id, source, target);
        }

        id
    }

    /// Creates a link with a specific ID, ensuring all links up to that ID exist
    pub fn ensure_created(&mut self, id: u32) -> u32 {
        if self.links.contains_key(&id) {
            return id;
        }

        if self.next_id > id {
            let link = Link::new(id, 0, 0);
            self.links.insert(id, link);
            if self.trace {
                eprintln!("[TRACE] Ensured link: ({} 0 0)", id);
            }
            return id;
        }

        // Create placeholder links up to the requested ID
        while self.next_id <= id {
            let placeholder_id = self.next_id;
            self.next_id += 1;
            if placeholder_id == id {
                let link = Link::new(id, 0, 0);
                self.links.insert(id, link);
                if self.trace {
                    eprintln!("[TRACE] Ensured link: ({} 0 0)", id);
                }
                return id;
            }
        }

        id
    }

    /// Gets a link by ID
    pub fn get(&self, id: u32) -> Option<&Link> {
        self.links.get(&id)
    }

    /// Checks if a link exists
    pub fn exists(&self, id: u32) -> bool {
        self.links.contains_key(&id)
    }

    /// Updates a link's source and target
    pub fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
        if let Some(link) = self.links.get_mut(&id) {
            let before = *link;
            if self.trace {
                eprintln!(
                    "[TRACE] Updating link {} from ({} {}) to ({} {})",
                    id, link.source, link.target, source, target
                );
            }
            link.source = source;
            link.target = target;
            Ok(before)
        } else {
            Err(LinkError::NotFound(id).into())
        }
    }

    /// Deletes a link by ID
    pub fn delete(&mut self, id: u32) -> Result<Link> {
        // Also remove the name mapping
        if let Some(name) = self.names.remove(&id) {
            self.name_to_id.remove(&name);
        }

        if let Some(link) = self.links.remove(&id) {
            if self.trace {
                eprintln!(
                    "[TRACE] Deleted link: ({} {} {})",
                    link.index, link.source, link.target
                );
            }
            Ok(link)
        } else {
            Err(LinkError::NotFound(id).into())
        }
    }

    /// Returns all links
    pub fn all(&self) -> Vec<&Link> {
        self.links.values().collect()
    }

    /// Returns all links matching a query pattern
    pub fn query(
        &self,
        index: Option<u32>,
        source: Option<u32>,
        target: Option<u32>,
    ) -> Vec<&Link> {
        self.links
            .values()
            .filter(|link| {
                (index.is_none() || index == Some(link.index))
                    && (source.is_none() || source == Some(link.source))
                    && (target.is_none() || target == Some(link.target))
            })
            .collect()
    }

    /// Searches for a link with the given source and target
    pub fn search(&self, source: u32, target: u32) -> Option<u32> {
        for link in self.links.values() {
            if link.source == source && link.target == target {
                return Some(link.index);
            }
        }
        None
    }

    /// Gets or creates a link with the given source and target
    pub fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
        if let Some(id) = self.search(source, target) {
            id
        } else {
            self.create(source, target)
        }
    }

    /// Formats a link for display
    pub fn format(&self, link: &Link) -> String {
        // Use name if available
        let index_str = self
            .names
            .get(&link.index)
            .cloned()
            .unwrap_or_else(|| link.index.to_string());
        let source_str = self
            .names
            .get(&link.source)
            .cloned()
            .unwrap_or_else(|| link.source.to_string());
        let target_str = self
            .names
            .get(&link.target)
            .cloned()
            .unwrap_or_else(|| link.target.to_string());
        format!("({} {} {})", index_str, source_str, target_str)
    }

    /// Formats a link as LiNo suitable for database export.
    pub fn format_lino(&self, link: &Link) -> String {
        format!(
            "({}: {} {})",
            self.format_lino_reference(link.index),
            self.format_lino_reference(link.source),
            self.format_lino_reference(link.target)
        )
    }

    /// Returns all database links as sorted LiNo lines.
    pub fn lino_lines(&self) -> Vec<String> {
        let mut links: Vec<_> = self.all();
        links.sort_by_key(|l| l.index);
        links
            .into_iter()
            .map(|link| self.format_lino(link))
            .collect()
    }

    /// Writes the complete database as LiNo.
    pub fn write_lino_output<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let path = path.as_ref();
        let file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
            .with_context(|| format!("Failed to create LiNo output: {}", path.display()))?;

        let mut writer = BufWriter::new(file);
        for line in self.lino_lines() {
            writeln!(writer, "{line}")?;
        }
        writer.flush()?;
        Ok(())
    }

    /// Formats the structure of a link
    pub fn format_structure(&self, id: u32) -> Result<String> {
        let mut visited = HashSet::new();
        self.format_structure_recursive(id, &mut visited)
    }

    /// Recursively formats a link structure
    fn format_structure_recursive(&self, id: u32, visited: &mut HashSet<u32>) -> Result<String> {
        let link = self.get(id).ok_or(LinkError::NotFound(id))?;
        if !visited.insert(id) {
            return Ok(self.format_lino_reference(id));
        }

        let source = if self.exists(link.source) && !visited.contains(&link.source) {
            self.format_structure_recursive(link.source, visited)?
        } else {
            self.format_lino_reference(link.source)
        };
        let target = self.format_lino_reference(link.target);
        let index = self.format_lino_reference(link.index);
        visited.remove(&id);

        Ok(format!("({index}: {source} {target})"))
    }

    /// Prints all links
    pub fn print_all_links(&self) {
        let mut links: Vec<_> = self.all();
        links.sort_by_key(|l| l.index);
        for link in links {
            println!("{}", self.format(link));
        }
    }

    /// Prints a change (before -> after)
    pub fn print_change(&self, before: &Option<Link>, after: &Option<Link>) {
        let before_text = before.map(|l| self.format(&l)).unwrap_or_default();
        let after_text = after.map(|l| self.format(&l)).unwrap_or_default();
        println!("({}) ({})", before_text, after_text);
    }

    // Named links functionality (corresponds to NamedLinks.cs)

    /// Gets or creates a link with a name
    pub fn get_or_create_named(&mut self, name: &str) -> u32 {
        if let Some(&id) = self.name_to_id.get(name) {
            id
        } else {
            // Create a self-referential link for the name
            let id = self.create(0, 0);
            self.update(id, id, id).ok();
            self.names.insert(id, name.to_string());
            self.name_to_id.insert(name.to_string(), id);
            if self.trace {
                eprintln!("[TRACE] Created named link: {} => {}", name, id);
            }
            id
        }
    }

    /// Sets the name for a link
    pub fn set_name(&mut self, id: u32, name: &str) {
        // Remove old name mapping if exists
        if let Some(old_name) = self.names.remove(&id) {
            self.name_to_id.remove(&old_name);
        }
        self.names.insert(id, name.to_string());
        self.name_to_id.insert(name.to_string(), id);
        if self.trace {
            eprintln!("[TRACE] Set name: {} => {}", id, name);
        }
    }

    /// Gets the name of a link
    pub fn get_name(&self, id: u32) -> Option<&String> {
        self.names.get(&id)
    }

    /// Gets a link ID by name
    pub fn get_by_name(&self, name: &str) -> Option<u32> {
        self.name_to_id.get(name).copied()
    }

    /// Removes the name for a link
    pub fn remove_name(&mut self, id: u32) {
        if let Some(name) = self.names.remove(&id) {
            self.name_to_id.remove(&name);
            if self.trace {
                eprintln!("[TRACE] Removed name: {} => {}", id, name);
            }
        }
    }

    /// Returns true if trace mode is enabled
    pub fn is_trace_enabled(&self) -> bool {
        self.trace
    }

    fn format_lino_reference(&self, id: u32) -> String {
        self.names
            .get(&id)
            .map(|name| escape_lino_reference(name))
            .unwrap_or_else(|| id.to_string())
    }
}

fn escape_lino_reference(reference: &str) -> String {
    if reference.is_empty() || reference.trim().is_empty() {
        return String::new();
    }

    let has_single_quote = reference.contains('\'');
    let has_double_quote = reference.contains('"');
    let needs_quoting = reference.contains(':')
        || reference.contains('(')
        || reference.contains(')')
        || reference.contains(' ')
        || reference.contains('\t')
        || reference.contains('\n')
        || reference.contains('\r')
        || has_single_quote
        || has_double_quote;

    if has_single_quote && has_double_quote {
        return format!("'{}'", reference.replace('\'', "\\'"));
    }

    if has_double_quote {
        return format!("'{reference}'");
    }

    if has_single_quote {
        return format!("\"{reference}\"");
    }

    if needs_quoting {
        return format!("'{reference}'");
    }

    reference.to_string()
}