Skip to main content

exiftool_rs/
config.rs

1//! ExifTool configuration file parser (.ExifTool_config).
2//!
3//! Supports user-defined tags and shortcuts in a simplified format.
4//! The Perl ExifTool uses Perl code in the config; we support a subset:
5//!
6//! ```text
7//! # Comment
8//! %Image::ExifTool::UserDefined = (
9//!     'Image::ExifTool::Exif::Main' => {
10//!         0xd000 => { Name => 'MyCustomTag', Writable => 'string' },
11//!     },
12//! );
13//!
14//! %Image::ExifTool::UserDefined::Shortcuts = (
15//!     MyShortcut => ['Artist', 'Copyright', 'Title'],
16//! );
17//! ```
18
19use std::path::Path;
20
21/// A user-defined tag from the config file.
22#[derive(Debug, Clone)]
23pub struct UserTag {
24    pub tag_id: u16,
25    pub name: String,
26    pub writable: Option<String>,
27    pub group: String,
28}
29
30/// A tag shortcut (group of tag names).
31#[derive(Debug, Clone)]
32pub struct Shortcut {
33    pub name: String,
34    pub tags: Vec<String>,
35}
36
37/// Parsed configuration.
38#[derive(Debug, Default)]
39pub struct Config {
40    pub user_tags: Vec<UserTag>,
41    pub shortcuts: Vec<Shortcut>,
42}
43
44impl Config {
45    /// Load configuration from the default location.
46    pub fn load_default() -> Self {
47        // Try ~/.ExifTool_config, then ./.ExifTool_config
48        let candidates = [
49            dirs_home().map(|h| h.join(".ExifTool_config")),
50            Some(std::path::PathBuf::from(".ExifTool_config")),
51        ];
52
53        for candidate in candidates.iter().flatten() {
54            if candidate.exists() {
55                if let Some(config) = Self::load(candidate) {
56                    return config;
57                }
58            }
59        }
60
61        Self::default()
62    }
63
64    /// Load and parse a config file.
65    pub fn load<P: AsRef<Path>>(path: P) -> Option<Self> {
66        let content = std::fs::read_to_string(path).ok()?;
67        Some(Self::parse(&content))
68    }
69
70    /// Parse config file content.
71    fn parse(content: &str) -> Self {
72        let mut config = Config::default();
73
74        // Remove comments
75        let lines: Vec<&str> = content.lines()
76            .map(|l| l.split('#').next().unwrap_or("").trim())
77            .collect();
78        let text = lines.join("\n");
79
80        // Parse UserDefined tags
81        if let Some(start) = text.find("%Image::ExifTool::UserDefined") {
82            if let Some(paren_start) = text[start..].find('(') {
83                let block_start = start + paren_start + 1;
84                if let Some(block_end) = find_matching_paren(&text, block_start) {
85                    let block = &text[block_start..block_end];
86                    parse_user_tags(block, &mut config.user_tags);
87                }
88            }
89        }
90
91        // Parse Shortcuts
92        if let Some(start) = text.find("Shortcuts") {
93            if let Some(paren_start) = text[start..].find('(') {
94                let block_start = start + paren_start + 1;
95                if let Some(block_end) = find_matching_paren(&text, block_start) {
96                    let block = &text[block_start..block_end];
97                    parse_shortcuts(block, &mut config.shortcuts);
98                }
99            }
100        }
101
102        config
103    }
104}
105
106fn parse_user_tags(block: &str, tags: &mut Vec<UserTag>) {
107    // Look for: 0xNNNN => { Name => 'XXX' }
108    let mut pos = 0;
109    while let Some(hex_pos) = block[pos..].find("0x") {
110        let abs_pos = pos + hex_pos;
111        let rest = &block[abs_pos + 2..];
112
113        // Read hex number
114        let hex_end = rest.find(|c: char| !c.is_ascii_hexdigit()).unwrap_or(rest.len());
115        if let Ok(tag_id) = u16::from_str_radix(&rest[..hex_end], 16) {
116            // Find Name
117            if let Some(name_pos) = rest.find("Name") {
118                let after_name = &rest[name_pos..];
119                if let Some(name) = extract_perl_string(after_name) {
120                    tags.push(UserTag {
121                        tag_id,
122                        name: name.clone(),
123                        writable: extract_after_key(after_name, "Writable"),
124                        group: "UserDefined".to_string(),
125                    });
126                }
127            }
128        }
129
130        pos = abs_pos + hex_end + 2;
131    }
132}
133
134fn parse_shortcuts(block: &str, shortcuts: &mut Vec<Shortcut>) {
135    // Look for: ShortcutName => ['Tag1', 'Tag2', ...]
136    for line in block.lines() {
137        let line = line.trim();
138        if let Some(arrow) = line.find("=>") {
139            let name = line[..arrow].trim().trim_matches('\'').trim_matches('"').to_string();
140            let rest = &line[arrow + 2..];
141
142            // Parse array ['Tag1', 'Tag2']
143            if let Some(bracket_start) = rest.find('[') {
144                if let Some(bracket_end) = rest.find(']') {
145                    let array_content = &rest[bracket_start + 1..bracket_end];
146                    let tags: Vec<String> = array_content
147                        .split(',')
148                        .map(|s| s.trim().trim_matches('\'').trim_matches('"').to_string())
149                        .filter(|s| !s.is_empty())
150                        .collect();
151
152                    if !name.is_empty() && !tags.is_empty() {
153                        shortcuts.push(Shortcut { name, tags });
154                    }
155                }
156            }
157        }
158    }
159}
160
161fn extract_perl_string(text: &str) -> Option<String> {
162    // Find first quoted string after =>
163    let arrow = text.find("=>")?;
164    let rest = &text[arrow + 2..];
165    let rest = rest.trim();
166
167    if rest.starts_with('\'') {
168        let end = rest[1..].find('\'')?;
169        Some(rest[1..1 + end].to_string())
170    } else if rest.starts_with('"') {
171        let end = rest[1..].find('"')?;
172        Some(rest[1..1 + end].to_string())
173    } else {
174        None
175    }
176}
177
178fn extract_after_key(text: &str, key: &str) -> Option<String> {
179    let pos = text.find(key)?;
180    extract_perl_string(&text[pos..])
181}
182
183fn find_matching_paren(text: &str, start: usize) -> Option<usize> {
184    let mut depth = 1;
185    let bytes = text.as_bytes();
186    let mut i = start;
187    while i < bytes.len() && depth > 0 {
188        match bytes[i] {
189            b'(' => depth += 1,
190            b')' => {
191                depth -= 1;
192                if depth == 0 {
193                    return Some(i);
194                }
195            }
196            _ => {}
197        }
198        i += 1;
199    }
200    None
201}
202
203fn dirs_home() -> Option<std::path::PathBuf> {
204    std::env::var("HOME").ok().map(std::path::PathBuf::from)
205}