swiftide_docker_executor/
context_builder.rs

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
use std::{
    os::unix::fs::MetadataExt as _,
    path::{Path, PathBuf},
};

use ignore::gitignore::{Gitignore, GitignoreBuilder};
// use ignore::{overrides::OverrideBuilder, WalkBuilder};
use tokio::io::AsyncReadExt as _;
use tokio_tar::{Builder, EntryType, Header};
use walkdir::{DirEntry, WalkDir};

use crate::ContextError;

type ContextArchive = Vec<u8>;

#[derive(Debug)]
pub struct ContextBuilder {
    context_path: PathBuf,
    ignore: Gitignore,
    global: Option<Gitignore>,
}

impl ContextBuilder {
    pub fn from_path(context_path: impl Into<PathBuf>) -> Result<Self, ContextError> {
        let path = context_path.into();
        let mut gitignore = GitignoreBuilder::new(&path);

        if let Some(err) = gitignore.add(path.join(".gitignore")) {
            tracing::warn!(?err, "Error adding .gitignore");
        }
        if let Some(err) = gitignore.add(path.join(".dockerignore")) {
            tracing::warn!(?err, "Error adding .dockerignore");
        }

        let gitignore = gitignore.build()?;

        let (global_gitignore, maybe_error) = Gitignore::global();
        let maybe_global = if let Some(err) = maybe_error {
            tracing::warn!(?err, "Error adding global gitignore");
            None
        } else {
            Some(global_gitignore)
        };

        Ok(Self {
            context_path: path,
            ignore: gitignore,
            global: maybe_global,
        })
    }

    fn is_ignored(&self, path: impl AsRef<Path>) -> bool {
        let Ok(relative_path) = path.as_ref().strip_prefix(&self.context_path) else {
            tracing::debug!(
                "not ignoring {path} as it seems to be not prefixed by {prefix}",
                path = path.as_ref().display(),
                prefix = self.context_path.to_string_lossy()
            );
            return false;
        };

        if relative_path.starts_with(".git") {
            tracing::debug!(
                "not ignoring {path} as it seems to be a git file",
                path = path.as_ref().display()
            );
            return false;
        }

        if let Some(global) = &self.global {
            if global
                .matched_path_or_any_parents(relative_path, false)
                .is_ignore()
            {
                tracing::debug!(
                    "ignoring {path} as it is ignored by global gitignore",
                    path = path.as_ref().display()
                );
                return true;
            }
        }

        self.ignore
            .matched_path_or_any_parents(relative_path, false)
            .is_ignore()
    }

    fn iter(&self) -> impl Iterator<Item = Result<DirEntry, walkdir::Error>> {
        WalkDir::new(&self.context_path).into_iter()
    }

    pub async fn build_tar(&self) -> Result<ContextArchive, ContextError> {
        let buffer = Vec::new();

        let mut tar = Builder::new(buffer);

        for entry in self.iter() {
            let Ok(entry) = entry else { continue };
            let path = entry.path();

            let Ok(relative_path) = path.strip_prefix(&self.context_path) else {
                continue;
            };

            if path.is_dir() {
                let _ = tar.append_path(relative_path).await;
                continue;
            }

            if self.is_ignored(path) {
                tracing::debug!(path = ?path, "Ignored file");
                continue;
            }

            if path.is_symlink() {
                let Ok(link_target) = tokio::fs::read_link(path).await else {
                    continue;
                }; // The target of the symlink
                let Ok(metadata) = entry.metadata() else {
                    continue;
                };
                let mut header = Header::new_gnu();

                // Indicate it's a symlink
                header.set_entry_type(EntryType::Symlink);
                // The tar specification requires setting the link name for a symlink
                header.set_link_name(link_target)?;

                // Set ownership, permissions, etc.
                header.set_uid(metadata.uid() as u64);
                header.set_gid(metadata.gid() as u64);
                // For a symlink, the "mode" is often ignored by many tools,
                // but we’ll set it anyway to match the source:
                header.set_mode(metadata.mode());
                // Set modification time (use 0 or a real timestamp as you prefer)
                header.set_mtime(metadata.mtime() as u64);
                // Symlinks don’t store file data in the tar, so size is 0
                header.set_size(0);

                tar.append_data(&mut header, path, tokio::io::empty())
                    .await?;
                continue;
            }

            tracing::debug!(path = ?path, "Adding file to tar");
            let mut file = tokio::fs::File::open(path).await?;
            let mut buffer_content = Vec::new();
            file.read_to_end(&mut buffer_content).await?;

            let mut header = Header::new_gnu();
            header.set_size(buffer_content.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();

            let relative_path = path.strip_prefix(&self.context_path)?;
            tar.append_data(&mut header, relative_path, &*buffer_content)
                .await?;
        }

        let result = tar.into_inner().await?;

        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;
    use tempfile::tempdir;

    #[test_log::test(tokio::test)]
    async fn test_is_ignored() {
        let dir = tempdir().unwrap();
        let context_path = dir.path().to_path_buf();

        // Create .gitignore file
        let mut gitignore_file = fs::File::create(context_path.join(".gitignore")).unwrap();
        writeln!(gitignore_file, "*.log").unwrap();

        // Create .dockerignore file
        let mut dockerignore_file = fs::File::create(context_path.join(".dockerignore")).unwrap();
        writeln!(dockerignore_file, "*.tmp").unwrap();

        dbg!(&std::fs::read_to_string(context_path.join(".gitignore")).unwrap());

        let context_builder = ContextBuilder::from_path(&context_path).unwrap();

        // Create test files
        let log_file = context_path.join("test.log");
        let tmp_file = context_path.join("test.tmp");
        let txt_file = context_path.join("test.txt");

        fs::File::create(&log_file).unwrap();
        fs::File::create(&tmp_file).unwrap();
        fs::File::create(&txt_file).unwrap();

        assert!(context_builder.is_ignored(&log_file));
        assert!(context_builder.is_ignored(&tmp_file));
        assert!(!context_builder.is_ignored(&txt_file));
    }

    #[test_log::test(tokio::test)]
    async fn test_adds_git_even_if_in_ignore() {
        let dir = tempdir().unwrap();
        let context_path = dir.path().to_path_buf();

        // Create .gitignore file
        let mut gitignore_file = fs::File::create(context_path.join(".gitignore")).unwrap();
        writeln!(gitignore_file, ".git").unwrap();

        let context_builder = ContextBuilder::from_path(&context_path).unwrap();

        assert!(!context_builder.is_ignored(".git"));
    }

    #[test_log::test(tokio::test)]
    async fn test_works_without_gitignore() {
        let dir = tempdir().unwrap();
        let context_path = dir.path().to_path_buf();

        // Create .gitignore file

        let context_builder = ContextBuilder::from_path(&context_path).unwrap();

        assert!(!context_builder.is_ignored(".git"));
        assert!(!context_builder.is_ignored("Dockerfile"));

        fs::File::create(context_path.join("Dockerfile")).unwrap();

        assert!(!context_builder.is_ignored("Dockerfile"));
    }
}