patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob fa746b39b3cae79580de6a7a1a3656aca7849c0b 5096 bytes (raw)
name: tools/mount-flatpak/src/keyfile.rs 	 # note: path name is non-authoritative(*)

  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
 
// Copyright 2021 System76 <info@system76.com>
// SPDX-FileCopyrightText: 2025 Alyssa Ross <hi@alyssa.is>
// SPDX-License-Identifier: MPL-2.0

// Adapted from freedesktop-desktop-entry 0.7.19.

use std::collections::BTreeMap;
use std::fmt::{self, Display, Formatter};

type Group = BTreeMap<String, String>;

#[derive(Debug)]
pub enum DecodeError {
    KeyValueWithoutAGroup,
    InvalidKey,
    InvalidValue,
}

impl Display for DecodeError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::KeyValueWithoutAGroup => write!(f, "key/value without a group"),
            Self::InvalidKey => write!(f, "invalid key"),
            Self::InvalidValue => write!(f, "invalid value"),
        }
    }
}

pub fn parse(input: &str) -> Result<BTreeMap<String, Group>, DecodeError> {
    let mut groups = BTreeMap::default();
    let mut active_group: Option<ActiveGroup> = None;
    let mut active_keys: Option<ActiveKeys> = None;

    for line in input.lines() {
        process_line(line, &mut groups, &mut active_group, &mut active_keys)?;
    }

    if let Some(active_keys) = active_keys.take() {
        match &mut active_group {
            Some(active_group) => {
                active_group
                    .group
                    .insert(active_keys.key_name, active_keys.value);
            }
            None => return Err(DecodeError::KeyValueWithoutAGroup),
        }
    }

    if let Some(mut group) = active_group.take() {
        groups
            .entry(group.group_name)
            .or_default()
            .append(&mut group.group);
    }

    Ok(groups)
}

struct ActiveGroup {
    group_name: String,
    group: Group,
}

struct ActiveKeys {
    key_name: String,
    value: String,
}

#[inline(never)]
fn process_line(
    line: &str,
    groups: &mut BTreeMap<String, Group>,
    active_group: &mut Option<ActiveGroup>,
    active_keys: &mut Option<ActiveKeys>,
) -> Result<(), DecodeError> {
    if line.trim().is_empty() || line.starts_with('#') {
        return Ok(());
    }

    let line_bytes = line.as_bytes();

    // if group
    if line_bytes[0] == b'[' {
        if let Some(end) = line_bytes[1..].iter().rposition(|&b| b == b']') {
            let group_name = &line[1..end + 1];

            if let Some(active_keys) = active_keys.take() {
                match active_group {
                    Some(active_group) => {
                        active_group
                            .group
                            .insert(active_keys.key_name, active_keys.value);
                    }
                    None => return Err(DecodeError::KeyValueWithoutAGroup),
                }
            }

            if let Some(mut group) = active_group.take() {
                groups
                    .entry(group.group_name)
                    .or_default()
                    .append(&mut group.group);
            }

            active_group.replace(ActiveGroup {
                group_name: group_name.to_string(),
                group: Group::default(),
            });
        }
    }
    // else, if value
    else if let Some(delimiter) = line_bytes.iter().position(|&b| b == b'=') {
        let key = &line[..delimiter];
        let value = format_value(&line[delimiter + 1..])?;

        if key.is_empty() {
            return Err(DecodeError::InvalidKey);
        }

        if let Some(active_keys) = active_keys.take() {
            match active_group {
                Some(active_group) => {
                    active_group
                        .group
                        .insert(active_keys.key_name, active_keys.value);
                }
                None => return Err(DecodeError::KeyValueWithoutAGroup),
            }
        }
        active_keys.replace(ActiveKeys {
            key_name: key.trim().to_string(),
            value,
        });
    }
    Ok(())
}

// https://specifications.freedesktop.org/desktop-entry-spec/latest/value-types.html
#[inline]
fn format_value(input: &str) -> Result<String, DecodeError> {
    let input = if let Some(input) = input.strip_prefix(" ") {
        input
    } else {
        input
    };

    let mut res = String::with_capacity(input.len());

    let mut last: usize = 0;

    for (i, v) in input.as_bytes().iter().enumerate() {
        if *v != b'\\' {
            continue;
        }

        // edge case for //
        if last > i {
            continue;
        }

        // when there is an \ at the end
        if input.len() <= i + 1 {
            return Err(DecodeError::InvalidValue);
        }

        if last < i {
            res.push_str(&input[last..i]);
        }

        last = i + 2;

        match input.as_bytes()[i + 1] {
            b's' => res.push(' '),
            b'n' => res.push('\n'),
            b't' => res.push('\t'),
            b'r' => res.push('\r'),
            b'\\' => res.push('\\'),
            _ => {
                return Err(DecodeError::InvalidValue);
            }
        }
    }

    if last < input.len() {
        res.push_str(&input[last..input.len()]);
    }

    Ok(res)
}

debug log:

solving fa746b3 ...
found fa746b3 in https://inbox.spectrum-os.org/spectrum-devel/20251124194846.16338-1-hi@alyssa.is/ ||
	https://inbox.spectrum-os.org/spectrum-devel/20251127202311.42422-2-hi@alyssa.is/ ||
	https://inbox.spectrum-os.org/spectrum-devel/20251201170458.4186683-7-hi@alyssa.is/ ||
	https://inbox.spectrum-os.org/spectrum-devel/20251201044534.977524-5-hi@alyssa.is/

applying [1/1] https://inbox.spectrum-os.org/spectrum-devel/20251124194846.16338-1-hi@alyssa.is/
diff --git a/tools/mount-flatpak/src/keyfile.rs b/tools/mount-flatpak/src/keyfile.rs
new file mode 100644
index 0000000..fa746b3

Checking patch tools/mount-flatpak/src/keyfile.rs...
Applied patch tools/mount-flatpak/src/keyfile.rs cleanly.

skipping https://inbox.spectrum-os.org/spectrum-devel/20251127202311.42422-2-hi@alyssa.is/ for fa746b3
skipping https://inbox.spectrum-os.org/spectrum-devel/20251201170458.4186683-7-hi@alyssa.is/ for fa746b3
skipping https://inbox.spectrum-os.org/spectrum-devel/20251201044534.977524-5-hi@alyssa.is/ for fa746b3
index at:
100644 fa746b39b3cae79580de6a7a1a3656aca7849c0b	tools/mount-flatpak/src/keyfile.rs

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://spectrum-os.org/git/crosvm
	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/nixpkgs
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock
	https://spectrum-os.org/git/www

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).