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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::{
    fmt::{Display, Formatter},
    fs::{create_dir_all, rename, File},
    io::{self, Read, Write},
    path::{Path, PathBuf},
};

use directories::ProjectDirs;
use flate2::read::GzDecoder;
use io::ErrorKind;
use mlua::{Lua, LuaSerdeExt, StdLib};
use serde::Deserialize;
use tar::{Archive, EntryType};
use tokio::runtime;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("{0}")]
    Io(#[from] io::Error),
    #[error("{0}")]
    Lua(#[from] mlua::Error),
    #[error("{0}")]
    Http(#[from] reqwest::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone, Deserialize)]
pub enum VarFlavor {
    Recursive,
    Simple,
    Conditional,
    Shell,
    Append,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "t", content = "c")]
pub enum Directive {
    Include(Option<Vec<String>>),
    SInclude(Option<Vec<String>>),
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "t", content = "c")]
pub enum MakefileThing {
    Comment(String),
    Vardef {
        name: String,
        value: String,
        flavor: VarFlavor,
        targets: Option<Vec<String>>,
    },
    Directive(Directive),
    Break,
    ExplicitRule {
        targets: Vec<String>,
        prerequisites: Option<Vec<String>>,
        recipe: Option<Vec<String>>,
    },
    PatternRule {
        patterns: Vec<String>,
        prerequisites: Option<Vec<String>>,
        recipe: Option<Vec<String>>,
    },
    StaticPatternRule {
        targets: Vec<String>,
        target_pattern: String,
        prereq_patterns: Option<Vec<String>>,
        recipe: Option<Vec<String>>,
    },
}

#[derive(Debug, Clone, Deserialize)]
pub struct Makefile {
    things: Vec<MakefileThing>,
}

fn local_require_searcher<'lua>(
    lua: &'lua Lua,
    path: &Path,
    name: String,
) -> Result<(mlua::Function<'lua>, String)> {
    let path = path.join(&name);

    let mut source = String::new();

    let mut actualpath = path.with_extension("lua");

    match File::open(&actualpath) {
        Ok(file) => Ok(file),
        Err(_) => {
            actualpath = path.join("init.lua");
            File::open(&actualpath)
        }
    }?
    .read_to_string(&mut source)?;

    let parent = actualpath
        .canonicalize()?
        .parent()
        .map_or(PathBuf::default(), |p| PathBuf::from(p));
    let actualpath = actualpath.to_str().unwrap_or(&name).to_owned();
    Ok((
        lua.create_function(move |lua, p: mlua::MultiValue| {
            let searchers = lua
                .globals()
                .get::<_, mlua::Table>("package")?
                .get::<_, mlua::Table>("searchers")?;
            let old_dir_searcher = searchers.get::<_, mlua::Value>(1)?;

            searchers.set(1, add_require_search_path(lua, parent.clone())?)?;

            let module = lua
                .load(&source)
                .set_name(&name)?
                .call::<_, mlua::MultiValue>(p)?;

            searchers.set(1, old_dir_searcher)?;

            Ok(module)
        })?,
        actualpath,
    ))
}

fn add_require_search_path<'a>(lua: &'a Lua, path: PathBuf) -> mlua::Result<mlua::Function<'a>> {
    lua.create_function(
        move |lua, name| match local_require_searcher(lua, &path, name) {
            Ok((f, n)) => Ok((Some(f), n)),
            Err(e) => Ok((None, format!("couldn't load the module: {}", e))),
        },
    )
}

fn try_module_download(path: &Path, ident: &str) -> Option<PathBuf> {
    let (org, repo, tag) = {
        let repo: Vec<_> = ident.split('/').collect();

        if repo.len() != 3 {
            return None;
        }

        (repo[0], repo[1], repo[2])
    };

    let target = format!("https://github.com/{}/{}/tarball/{}", org, repo, tag);
    let tmp_dir = tempfile::Builder::new().prefix("epine").tempdir().ok()?;
    let rt = runtime::Builder::new_current_thread()
        .enable_io()
        .build()
        .unwrap();
    print!("getting {}/{} ({})... ", org, repo, tag);
    std::io::stdout().flush().ok()?;
    let response = rt.block_on(reqwest::get(&target)).ok()?;
    println!("{}", response.status());

    let dlpath = {
        let fname = format!("{}.{}.{}.tar.gz", org, repo, tag);

        let fname = tmp_dir.path().join(fname);
        fname
    };

    // download
    {
        let mut dest = File::create(&dlpath).ok()?;
        let content = rt.block_on(response.bytes()).ok()?;
        std::io::copy(&mut content.as_ref(), &mut dest).ok()?;
    }

    // extract
    {
        let tar_gz = File::open(&dlpath).ok()?;
        let tar = GzDecoder::new(tar_gz);
        let mut archive = Archive::new(tar);
        archive.unpack(&path).ok()?;
    }

    // rename (the archive has a single folder inside with some random name)
    // there is probably a better way to do this
    let root = {
        let tar_gz = File::open(&dlpath).ok()?;

        // find the name of the root folder
        let archive_root_name = {
            let tar = GzDecoder::new(tar_gz);
            let mut archive = Archive::new(tar);
            let root = archive
                .entries()
                .ok()?
                .find(|file| match file {
                    Ok(file) => file.header().entry_type() == EntryType::Directory,
                    _ => false,
                })
                .ok_or(std::io::Error::new(ErrorKind::NotFound, "empty archive"))
                .ok()?
                .ok()?;
            root.path().ok()?.into_owned()
        };

        let dest = path.join(format!("@{}", org)).join(repo);
        create_dir_all(&dest).ok()?;
        let dest_module_root = dest.join(tag);
        rename(path.join(archive_root_name), &dest_module_root).ok()?;
        dest_module_root
    };

    Some(root)
}

fn add_require_github_importer(
    lua: &Lua,
    searchers: &mlua::Table,
    ghfolder: PathBuf,
) -> Result<()> {
    searchers.set(
        searchers.len()? + 1,
        lua.create_function(move |lua, name: String| {
            if !name.starts_with("@") {
                return Ok((None, String::from("not a remote module")));
            }

            if let Some(path) = try_module_download(&ghfolder, &name[1..]) {
                match local_require_searcher(lua, &path, String::from("init")) {
                    Ok((f, n)) => Ok((Some(f), n)),
                    Err(e) => Ok((None, format!("couldn't load the module: {}", e))),
                }
            } else {
                return Ok((None, String::from("couldn't fetch remote module")));
            }
        })?,
    )?;

    Ok(())
}

impl Makefile {
    pub fn from_lua_source(src: &str, name: &str, dir: Option<&Path>) -> Result<Self> {
        let lua = Lua::new_with(
            StdLib::TABLE | StdLib::MATH | StdLib::OS | StdLib::STRING | StdLib::PACKAGE,
        )?;

        let package = lua.globals().get::<_, mlua::Table>("package")?;
        let searchers = lua.create_table()?;

        // if a "working directory" is specified (usually the folder in which Epine.lua is located)
        // epine will look for modules in the current working directory
        if let Some(dir) = dir {
            searchers.set(
                searchers.len()? + 1,
                add_require_search_path(&lua, dir.to_owned())?,
            )?;
        }

        // github modules are downloaded in a global directory to avoid downloading them many times
        // also fixes issues where the module contains examples that can get caught by a "find"
        if let Some(proj_dirs) = ProjectDirs::from("", "", "epine") {
            let dir = proj_dirs.cache_dir();

            // searcher that finds previously downloaded modules
            searchers.set(
                searchers.len()? + 1,
                add_require_search_path(&lua, dir.join("github"))?,
            )?;
            // the importer is the one that downloads new modules
            add_require_github_importer(&lua, &searchers, dir.join("github"))?;
        }

        package.set("searchers", searchers)?;

        lua.load(include_str!("./api.lua"))
            .set_name("api")?
            .exec()?;

        let makefile_def = lua.load(src).set_name(name)?.call(())?;

        let makefile_def = lua
            .load(include_str!("./normalize.lua"))
            .set_name("normalize")?
            .eval::<mlua::Function>()?
            .call::<mlua::Value, _>(makefile_def)?;

        Ok(Self {
            things: lua.from_value(makefile_def)?,
        })
    }

    pub fn from_lua_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let mut file = File::open(&path)?;
        let mut source = String::new();

        file.read_to_string(&mut source)?;

        Makefile::from_lua_source(
            &source[..],
            &path.as_ref().to_string_lossy(),
            path.as_ref().parent(),
        )
    }

    pub fn generate(&self) -> Result<String> {
        Ok(String::new())
    }
}

impl Display for Makefile {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for thing in self.things.iter() {
            write!(f, "{}", thing)?;
        }

        Ok(())
    }
}

impl Display for MakefileThing {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            MakefileThing::Comment(line) => writeln!(f, "#{}", line),
            MakefileThing::Vardef {
                name,
                value,
                flavor,
                targets,
            } => {
                if let Some(targets) = targets {
                    write!(f, "{}: ", targets.join(" "))?;
                }

                write!(f, "{} ", name)?;

                match flavor {
                    VarFlavor::Recursive => write!(f, "=")?,
                    VarFlavor::Simple => write!(f, ":=")?,
                    VarFlavor::Conditional => write!(f, "?=")?,
                    VarFlavor::Shell => write!(f, "!=")?,
                    VarFlavor::Append => write!(f, "+=")?,
                }

                if value == "" {
                    writeln!(f)
                } else {
                    writeln!(f, " {}", value)
                }
            }
            MakefileThing::Directive(Directive::Include(fnames)) => {
                write!(f, "include")?;

                if let Some(fnames) = fnames {
                    for fname in fnames.iter() {
                        write!(f, " {}", fname)?;
                    }
                }

                writeln!(f)
            }
            MakefileThing::Directive(Directive::SInclude(fnames)) => {
                write!(f, "-include")?;

                if let Some(fnames) = fnames {
                    for fname in fnames.iter() {
                        write!(f, " {}", fname)?;
                    }
                }

                writeln!(f)
            }
            MakefileThing::Break => {
                writeln!(f)
            }
            MakefileThing::ExplicitRule {
                targets,
                prerequisites,
                recipe,
            } => {
                write!(f, "{}:", targets.join(" "))?;

                if let Some(prereqs) = prerequisites {
                    for pre in prereqs.iter() {
                        write!(f, " {}", pre)?;
                    }
                }

                writeln!(f)?;

                if let Some(steps) = recipe {
                    for step in steps {
                        writeln!(f, "\t{}", step)?;
                    }
                }

                Ok(())
            }
            MakefileThing::PatternRule {
                patterns,
                prerequisites,
                recipe,
            } => {
                write!(f, "{}:", patterns.join(" "))?;

                if let Some(prereqs) = prerequisites {
                    for pre in prereqs.iter() {
                        write!(f, " {}", pre)?;
                    }
                }

                writeln!(f)?;

                if let Some(steps) = recipe {
                    for step in steps {
                        writeln!(f, "\t{}", step)?;
                    }
                }

                Ok(())
            }
            MakefileThing::StaticPatternRule {
                targets,
                target_pattern,
                prereq_patterns,
                recipe,
            } => {
                write!(f, "{}: {}", targets.join(" "), target_pattern)?;

                if let Some(prereq_pats) = prereq_patterns {
                    write!(f, ":")?;

                    for pp in prereq_pats.iter() {
                        write!(f, " {}", pp)?;
                    }
                }

                writeln!(f)?;

                if let Some(steps) = recipe {
                    for step in steps {
                        writeln!(f, "\t{}", step)?;
                    }
                }

                Ok(())
            }
        }
    }
}