about summary refs log tree commit diff
path: root/tvix/nix-compat/src/derivation/write.rs
blob: 04810e736af60cf4911dc7a8ba855eb754ff6305 (plain) (blame)
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
//! This module implements the serialisation of derivations into the
//! [ATerm][] format used by C++ Nix.
//!
//! [ATerm]: http://program-transformation.org/Tools/ATermFormat.html

use crate::aterm::escape_bytes;
use crate::derivation::{ca_kind_prefix, output::Output};
use crate::nixbase32;
use crate::store_path::{StorePath, StorePathRef, STORE_DIR_WITH_SLASH};
use bstr::BString;
use std::fmt::Display;
use std::{
    collections::{BTreeMap, BTreeSet},
    io,
    io::Error,
    io::Write,
};

use super::NixHash;

pub const DERIVATION_PREFIX: &str = "Derive";
pub const PAREN_OPEN: char = '(';
pub const PAREN_CLOSE: char = ')';
pub const BRACKET_OPEN: char = '[';
pub const BRACKET_CLOSE: char = ']';
pub const COMMA: char = ',';
pub const QUOTE: char = '"';

/// Something that can be written as ATerm.
///
/// Note that we mostly use explicit `write_*` calls
/// instead since the serialization of the items depends on
/// the context a lot.
pub(crate) trait AtermWriteable: Display {
    fn aterm_write(&self, writer: &mut impl Write) -> std::io::Result<()>;

    fn aterm_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();
        self.aterm_write(&mut bytes)
            .expect("unexpected write errors to Vec");
        bytes
    }
}

impl AtermWriteable for StorePathRef<'_> {
    fn aterm_write(&self, writer: &mut impl Write) -> std::io::Result<()> {
        write_char(writer, QUOTE)?;
        writer.write_all(STORE_DIR_WITH_SLASH.as_bytes())?;
        writer.write_all(nixbase32::encode(self.digest()).as_bytes())?;
        write_char(writer, '-')?;
        writer.write_all(self.name().as_bytes())?;
        write_char(writer, QUOTE)?;
        Ok(())
    }
}

impl AtermWriteable for StorePath {
    fn aterm_write(&self, writer: &mut impl Write) -> std::io::Result<()> {
        let r: StorePathRef = self.into();
        r.aterm_write(writer)
    }
}

impl AtermWriteable for String {
    fn aterm_write(&self, writer: &mut impl Write) -> std::io::Result<()> {
        write_field(writer, self, true)
    }
}

impl AtermWriteable for NixHash {
    fn aterm_write(&self, writer: &mut impl Write) -> std::io::Result<()> {
        // When we serialize the placeholder hashes,
        // they need to be SHA256.
        debug_assert!(matches!(self, NixHash::Sha256(_)));
        write_field(writer, self.to_plain_hex_string(), false)
    }
}

// Writes a character to the writer.
pub(crate) fn write_char(writer: &mut impl Write, c: char) -> io::Result<()> {
    let mut buf = [0; 4];
    let b = c.encode_utf8(&mut buf).as_bytes();
    writer.write_all(b)
}

// Write a string `s` as a quoted field to the writer.
// The `escape` argument controls whether escaping will be skipped.
// This is the case if `s` is known to only contain characters that need no
// escaping.
pub(crate) fn write_field<S: AsRef<[u8]>>(
    writer: &mut impl Write,
    s: S,
    escape: bool,
) -> io::Result<()> {
    write_char(writer, QUOTE)?;

    if !escape {
        writer.write_all(s.as_ref())?;
    } else {
        writer.write_all(&escape_bytes(s.as_ref()))?;
    }

    write_char(writer, QUOTE)?;

    Ok(())
}

fn write_array_elements<S: AsRef<[u8]>>(
    writer: &mut impl Write,
    elements: &[S],
) -> Result<(), io::Error> {
    for (index, element) in elements.iter().enumerate() {
        if index > 0 {
            write_char(writer, COMMA)?;
        }

        write_field(writer, element, true)?;
    }

    Ok(())
}

pub(crate) fn write_outputs(
    writer: &mut impl Write,
    outputs: &BTreeMap<String, Output>,
) -> Result<(), io::Error> {
    write_char(writer, BRACKET_OPEN)?;
    for (ii, (output_name, output)) in outputs.iter().enumerate() {
        if ii > 0 {
            write_char(writer, COMMA)?;
        }

        write_char(writer, PAREN_OPEN)?;

        let mut elements: Vec<&str> = vec![output_name, &output.path];

        let (mode_and_algo, digest) = match &output.ca_hash {
            Some(ca_hash) => (
                format!("{}{}", ca_kind_prefix(ca_hash), ca_hash.digest().algo()),
                data_encoding::HEXLOWER.encode(ca_hash.digest().digest_as_bytes()),
            ),
            None => ("".to_string(), "".to_string()),
        };

        elements.push(&mode_and_algo);
        elements.push(&digest);

        write_array_elements(writer, &elements)?;

        write_char(writer, PAREN_CLOSE)?;
    }
    write_char(writer, BRACKET_CLOSE)?;

    Ok(())
}

pub(crate) fn write_input_derivations(
    writer: &mut impl Write,
    input_derivations: &BTreeMap<impl AtermWriteable, BTreeSet<String>>,
) -> Result<(), io::Error> {
    write_char(writer, BRACKET_OPEN)?;

    for (ii, (input_derivation_aterm, output_names)) in input_derivations.iter().enumerate() {
        if ii > 0 {
            write_char(writer, COMMA)?;
        }

        write_char(writer, PAREN_OPEN)?;
        input_derivation_aterm.aterm_write(writer)?;
        write_char(writer, COMMA)?;

        write_char(writer, BRACKET_OPEN)?;
        write_array_elements(
            writer,
            &output_names
                .iter()
                .map(String::as_bytes)
                .collect::<Vec<_>>(),
        )?;
        write_char(writer, BRACKET_CLOSE)?;

        write_char(writer, PAREN_CLOSE)?;
    }

    write_char(writer, BRACKET_CLOSE)?;

    Ok(())
}

pub(crate) fn write_input_sources(
    writer: &mut impl Write,
    input_sources: &BTreeSet<StorePath>,
) -> Result<(), io::Error> {
    write_char(writer, BRACKET_OPEN)?;
    write_array_elements(
        writer,
        &input_sources
            .iter()
            .map(StorePath::to_absolute_path)
            .collect::<Vec<_>>(),
    )?;
    write_char(writer, BRACKET_CLOSE)?;

    Ok(())
}

pub(crate) fn write_system(writer: &mut impl Write, platform: &str) -> Result<(), Error> {
    write_field(writer, platform, true)?;
    Ok(())
}

pub(crate) fn write_builder(writer: &mut impl Write, builder: &str) -> Result<(), Error> {
    write_field(writer, builder, true)?;
    Ok(())
}

pub(crate) fn write_arguments(
    writer: &mut impl Write,
    arguments: &[String],
) -> Result<(), io::Error> {
    write_char(writer, BRACKET_OPEN)?;
    write_array_elements(
        writer,
        &arguments
            .iter()
            .map(|s| s.as_bytes().to_vec().into())
            .collect::<Vec<BString>>(),
    )?;
    write_char(writer, BRACKET_CLOSE)?;

    Ok(())
}

pub(crate) fn write_environment<E, K, V>(
    writer: &mut impl Write,
    environment: E,
) -> Result<(), io::Error>
where
    E: IntoIterator<Item = (K, V)>,
    K: AsRef<[u8]>,
    V: AsRef<[u8]>,
{
    write_char(writer, BRACKET_OPEN)?;

    for (i, (k, v)) in environment.into_iter().enumerate() {
        if i > 0 {
            write_char(writer, COMMA)?;
        }

        write_char(writer, PAREN_OPEN)?;
        write_field(writer, k, false)?;
        write_char(writer, COMMA)?;
        write_field(writer, v, true)?;
        write_char(writer, PAREN_CLOSE)?;
    }

    write_char(writer, BRACKET_CLOSE)?;

    Ok(())
}