summaryrefslogtreecommitdiff
path: root/morphology-img/src/file_gen.rs
blob: edeeeeb954fbf7ecf385425a179fa2c51086bb19 (plain)
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
// .ly file generation and temp directory management

use std::path::{Path, PathBuf};
use std::fs;
use tempfile::TempDir;
use morphology::Sequence;
use crate::error::RenderError;
use crate::template;
use crate::note::{sequence_to_notes, notes_to_markup};

/// Generates a filename for a sequence with proper zero-padding.
///
/// The padding width is determined by the total number of sequences,
/// ensuring that all filenames sort correctly in lexicographic order.
///
/// # Arguments
/// - `index`: The sequence index (0-based)
/// - `total_count`: Total number of sequences (used to determine padding)
///
/// # Examples
/// ```
/// use morphology_img::file_gen::generate_filename;
///
/// assert_eq!(generate_filename(0, 10).to_str().unwrap(), "sequence-00.ly");
/// assert_eq!(generate_filename(5, 10).to_str().unwrap(), "sequence-05.ly");
/// assert_eq!(generate_filename(42, 1000).to_str().unwrap(), "sequence-0042.ly");
/// ```
pub fn generate_filename(index: usize, total_count: usize) -> PathBuf {
    let width = total_count.to_string().len();
    PathBuf::from(format!("sequence-{:0width$}.ly", index, width = width))
}

/// Creates a temporary directory for .ly files.
///
/// The directory will be automatically cleaned up when the TempDir is dropped,
/// unless explicitly persisted using `TempDir::into_path()`.
///
/// # Returns
/// A TempDir handle that manages cleanup
///
/// # Errors
/// Returns `RenderError::FileIO` if the temporary directory cannot be created
pub fn create_temp_dir() -> Result<TempDir, RenderError> {
    TempDir::new().map_err(RenderError::from)
}

/// Writes the .ily support files to the specified directory.
///
/// This function writes the three LilyPond include files that are referenced
/// by the main template:
/// - `format.ily`: Format definitions
/// - `entry.ily`: Entry block definitions
/// - `elements.ily`: Element definitions
///
/// # Arguments
/// - `dir`: The directory to write files to
///
/// # Returns
/// Ok(()) on success
///
/// # Errors
/// Returns `RenderError::FileIO` if any file cannot be written
pub fn write_support_files(dir: &Path) -> Result<(), RenderError> {
    let files = [
        ("format.ily", template::get_format_ily()),
        ("entry.ily", template::get_entry_ily()),
        ("elements.ily", template::get_elements_ily()),
    ];

    for (filename, content) in files {
        let path = dir.join(filename);
        fs::write(&path, content)?;
    }

    Ok(())
}

/// Generates a .ly file for a single sequence.
///
/// This function performs the complete transformation pipeline:
/// 1. Convert sequence to notes
/// 2. Convert notes to markup string
/// 3. Substitute markup into template
/// 4. Write the complete .ly file to the specified path
///
/// # Arguments
/// - `sequence`: The meta-affine sequence to render
/// - `output_path`: Path where the .ly file should be written
///
/// # Returns
/// Ok(()) on success
///
/// # Errors
/// - `RenderError::Template` if template substitution fails
/// - `RenderError::FileIO` if file cannot be written
///
/// # Examples
/// ```no_run
/// use morphology::{Sequence, Value};
/// use morphology_img::file_gen::{generate_ly_file, create_temp_dir};
/// use std::path::Path;
///
/// let seq = Sequence::new(vec![Value::origin()]);
/// let temp_dir = create_temp_dir().unwrap();
/// let output_path = temp_dir.path().join("test.ly");
///
/// generate_ly_file(&seq, &output_path).unwrap();
/// assert!(output_path.exists());
/// ```
pub fn generate_ly_file(
    sequence: &Sequence,
    output_path: &Path,
) -> Result<(), RenderError> {
    // Convert sequence to notes
    let notes = sequence_to_notes(sequence);

    // Convert notes to markup string
    let markup = notes_to_markup(&notes);

    // Substitute into template
    let ly_content = template::substitute_template(&markup)?;

    // Write to file (UTF-8)
    fs::write(output_path, ly_content)?;

    Ok(())
}

/// Generates .ly files for multiple sequences in a specified directory.
///
/// This function generates numbered .ly files for each sequence in the input,
/// with filenames automatically padded based on the total count.
///
/// # Arguments
/// - `sequences`: The sequences to generate files for
/// - `temp_dir`: The directory to write files to
///
/// # Returns
/// A vector of paths to the generated .ly files, in the same order as input
///
/// # Errors
/// - `RenderError::Template` if template substitution fails
/// - `RenderError::FileIO` if any file cannot be written
///
/// # Examples
/// ```no_run
/// use morphology::{Sequence, Value};
/// use morphology_img::file_gen::{generate_ly_files, create_temp_dir};
///
/// let sequences = vec![
///     Sequence::new(vec![Value::origin()]),
///     Sequence::new(vec![Value::new(1, 0)]),
/// ];
///
/// let temp_dir = create_temp_dir().unwrap();
/// let paths = generate_ly_files(&sequences, temp_dir.path()).unwrap();
///
/// assert_eq!(paths.len(), 2);
/// for path in paths {
///     assert!(path.exists());
/// }
/// ```
pub fn generate_ly_files(
    sequences: &[Sequence],
    temp_dir: &Path,
) -> Result<Vec<PathBuf>, RenderError> {
    let total_count = sequences.len();
    let mut paths = Vec::with_capacity(total_count);

    for (index, sequence) in sequences.iter().enumerate() {
        let filename = generate_filename(index, total_count);
        let output_path = temp_dir.join(&filename);

        generate_ly_file(sequence, &output_path)?;

        paths.push(output_path);
    }

    Ok(paths)
}