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
// (C) Copyright 2019 Hewlett Packard Enterprise Development LP

use std::fmt;

use crate::error::*;
use crate::parser::*;
use crate::splicer::Span;

use enquote::unquote;
use snafu::ResultExt;

/// Given a node ostensibly containing a string array, returns an unescaped
/// array of strings
pub(crate) fn parse_string_array(array: Pair) -> Result<StringArray> {
  let span = Span::from_pair(&array);
  let mut elements = Vec::new();

  for field in array.into_inner() {
    match field.as_rule() {
      Rule::string => {
        elements.push(parse_string(&field)?);
      },
      Rule::comment => continue,
      _ => return Err(unexpected_token(field))
    }
  }

  Ok(StringArray {
    span,
    elements,
  })
}

pub(crate) fn parse_string(field: &Pair) -> Result<SpannedString> {
  let str_span = Span::from_pair(field);
  let field_str = field.as_str();
  let content = if matches!(field_str.chars().next(), Some('"' | '\'' | '`')) {
    unquote(field_str).context(UnescapeError)?
  } else {
    field_str.to_string()
  };

  Ok(SpannedString {
    span: str_span,
    content,
  })
}

/// Removes escaped line breaks (\\\n) from a string
///
/// This should be used to clean any input from the any_breakable rule
pub(crate) fn clean_escaped_breaks(s: &str) -> String {
  s.replace("\\\n", "")
}

/// A string that may be broken across many lines or an array of strings.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ShellOrExecExpr {
  Shell(BreakableString),
  Exec(StringArray),
}

impl ShellOrExecExpr {
  /// Unpacks this expression into its inner value if it is a Shell-form
  /// instruction, otherwise returns None.
  pub fn into_shell(self) -> Option<BreakableString> {
    if let ShellOrExecExpr::Shell(s) = self {
      Some(s)
    } else {
      None
    }
  }

  /// Unpacks this expression into its inner value if it is a Shell-form
  /// instruction, otherwise returns None.
  pub fn as_shell(&self) -> Option<&BreakableString> {
    if let ShellOrExecExpr::Shell(s) = self {
      Some(s)
    } else {
      None
    }
  }

  /// Unpacks this expression into its inner value if it is an Exec-form
  /// instruction, otherwise returns None.
  pub fn into_exec(self) -> Option<StringArray> {
    if let ShellOrExecExpr::Exec(s) = self {
      Some(s)
    } else {
      None
    }
  }

  /// Unpacks this expression into its inner value if it is an Exec-form
  /// instruction, otherwise returns None.
  pub fn as_exec(&self) -> Option<&StringArray> {
    if let ShellOrExecExpr::Exec(s) = self {
      Some(s)
    } else {
      None
    }
  }
}

/// A string array (ex. ["executable", "param1", "param2"])
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct StringArray {
  pub span: Span,
  pub elements: Vec<SpannedString>,
}

impl StringArray {
  pub fn as_str_vec(&self) -> Vec<&str> {
    self.elements.iter().map(|c| c.as_ref()).collect()
  }
}

/// A comment with a character span.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct SpannedComment {
  pub span: Span,
  pub content: String,
}

/// A string with a character span.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct SpannedString {
  pub span: Span,
  pub content: String,
}

impl AsRef<str> for SpannedString {
  fn as_ref(&self) -> &str {
    &self.content
  }
}

impl fmt::Display for SpannedString {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.content.fmt(f)
  }
}

/// A component of a breakable string.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub enum BreakableStringComponent {
  String(SpannedString),
  Comment(SpannedComment),
}

impl From<SpannedString> for BreakableStringComponent {
  fn from(s: SpannedString) -> Self {
    BreakableStringComponent::String(s)
  }
}

impl From<((usize, usize), &str)> for BreakableStringComponent {
  fn from(s: ((usize, usize), &str)) -> Self {
    let ((start, end), content) = s;

    BreakableStringComponent::String(SpannedString {
      span: (start, end).into(),
      content: content.to_string(),
    })
  }
}

impl From<SpannedComment> for BreakableStringComponent {
  fn from(c: SpannedComment) -> Self {
    BreakableStringComponent::Comment(c)
  }
}

/// A Docker string that may be broken across several lines, separated by line
/// continuations (`\\\n`), and possibly intermixed with comments.
///
/// These strings have several potentially valid interpretations. As these line
/// continuations match those natively supported by bash, a given multiline
/// `RUN` block can be pasted into a bash shell unaltered and with line
/// continuations included. However, at "runtime" line continuations and
/// comments (*) are stripped from the string handed to the shell.
///
/// To ensure output is correct in all cases, `BreakableString` preserves the
/// user's original AST, including comments, and implements Docker's
/// continuation-stripping behavior in the `Display` implementation.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub struct BreakableString {
  pub span: Span,
  pub components: Vec<BreakableStringComponent>,
}

/// Formats this breakable string as it will be interpreted by the underlying
/// Docker engine, i.e. on a single line with line continuations removed
impl fmt::Display for BreakableString {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    for component in &self.components {
      if let BreakableStringComponent::String(s) = &component {
        write!(f, "{}", s.content)?;
      }
    }

    Ok(())
  }
}

impl BreakableString {
  pub fn new(span: impl Into<Span>) -> Self {
    BreakableString {
      span: span.into(),
      components: Vec::new(),
    }
  }

  pub fn add(mut self, c: impl Into<BreakableStringComponent>) -> Self {
    self.components.push(c.into());

    self
  }

  pub fn add_string(mut self, s: impl Into<Span>, c: impl Into<String>) -> Self {
    self.components.push(SpannedString {
      span: s.into(),
      content: c.into(),
    }.into());

    self
  }

  pub fn add_comment(mut self, s: impl Into<Span>, c: impl Into<String>) -> Self {
    self.components.push(SpannedComment {
      span: s.into(),
      content: c.into(),
    }.into());

    self
  }

  pub fn iter_components(&self) -> impl Iterator<Item = &BreakableStringComponent> {
    self.components.iter()
  }
}

impl From<((usize, usize), &str)> for BreakableString {
  fn from(s: ((usize, usize), &str)) -> Self {
    let ((start, end), content) = s;

    BreakableString::new((start, end))
      .add_string((start, end), content)
  }
}

fn parse_any_breakable_inner(pair: Pair) -> Result<Vec<BreakableStringComponent>> {
  let mut components = Vec::new();

  for field in pair.into_inner() {
    match field.as_rule() {
      Rule::any_breakable => components.extend(parse_any_breakable_inner(field)?),
      Rule::comment => components.push(SpannedComment {
        span: (&field).into(),
        content: field.as_str().to_string(),
      }.into()),
      Rule::any_content => components.push(SpannedString {
        span: (&field).into(),
        content: field.as_str().to_string(),
      }.into()),
      _ => return Err(unexpected_token(field))
    }
  }

  Ok(components)
}

pub(crate) fn parse_any_breakable(pair: Pair) -> Result<BreakableString> {
  Ok(BreakableString {
    span: (&pair).into(),
    components: parse_any_breakable_inner(pair)?,
  })
}