elba 0.3.0

elba is a package manager for Idris
Documentation
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Package manifest files.


use super::*;
use crate::{
    remote::resolution::{DirectRes, IndexRes},
    util::{valid_file, SubPath},
};
use failure::{format_err, Error, ResultExt};
use ignore::gitignore::GitignoreBuilder;
use indexmap::IndexMap;
use semver::Version;
use semver_constraints::Constraint;
use serde::Deserialize;
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};
use toml;
use url::Url;
use url_serde;
use walkdir::{DirEntry, WalkDir};

// TODO: Package aliasing. Have dummy alias files in the root target folder.
//
// e.g. to alias `me/lightyear` with default root module `Me.Lightyear` as the module
// `Yeet.Lightyeet`, in the target folder, we make the following file in the proper directory
// (directory won't matter for Blodwen/Idris 2):
//
// ```idris
// module Yeet.Lightyeet
//
// import public Me.Lightyear
// ```
//
// Behind the scenes, we build this as its own package with the package it's aliasing as
// its only dependency, throw it in the global cache, and add this to the import dir of the root
// package instead of the original.
//
// With this in place, we can safely avoid module namespace conflicts.

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Manifest {
    pub package: PackageInfo,
    #[serde(default = "IndexMap::new")]
    pub dependencies: IndexMap<Name, DepReq>,
    #[serde(default = "IndexMap::new")]
    pub dev_dependencies: IndexMap<Name, DepReq>,
    #[serde(default)]
    pub targets: Targets,
    #[serde(default)]
    pub workspace: IndexMap<Name, SubPath>,
    #[serde(default)]
    pub scripts: IndexMap<String, String>,
}

impl Manifest {
    // Returns only the workspace portion of a manifest.
    pub fn workspace(s: &str) -> Option<IndexMap<Name, SubPath>> {
        toml::value::Value::try_from(&s)
            .ok()?
            .get("workspace")?
            .clone()
            .try_into()
            .ok()
    }

    pub fn version(&self) -> &Version {
        &self.package.version
    }

    pub fn name(&self) -> &Name {
        &self.package.name
    }

    pub fn deps(
        &self,
        ixmap: &IndexMap<String, IndexRes>,
        dev_deps: bool,
    ) -> Res<IndexMap<PackageId, Constraint>> {
        let mut deps = IndexMap::new();
        for (n, dep) in &self.dependencies {
            let dep = dep.clone();
            let (pid, c) = dep.into_dep(&ixmap, n.clone())?;
            deps.insert(pid, c);
        }

        if dev_deps {
            for (n, dep) in &self.dev_dependencies {
                let dep = dep.clone();
                let (pid, c) = dep.into_dep(&ixmap, n.clone())?;
                deps.insert(pid, c);
            }
        }

        Ok(deps)
    }

    pub fn list_files<P>(
        &self,
        pkg_root: &Path,
        search_root: &Path,
        mut p: P,
    ) -> Res<impl Iterator<Item = DirEntry>>
    where
        P: FnMut(&DirEntry) -> bool,
    {
        let mut excludes = GitignoreBuilder::new(pkg_root);
        if let Some(rs) = self.package.exclude.as_ref() {
            for r in rs {
                excludes.add_line(None, r)?;
            }
        }
        if pkg_root.join(".gitignore").exists() {
            if let Some(e) = excludes.add(pkg_root.join(".gitignore")) {
                return Err(e)?;
            }
        }
        let excludes = excludes
            .build()
            .with_context(|e| format_err!("invalid excludes: {}", e))?;

        let walker = WalkDir::new(search_root)
            .follow_links(true)
            .into_iter()
            .filter_entry(move |x| {
                !excludes
                    .matched_path_or_any_parents(x.path(), x.file_type().is_dir())
                    .is_ignore()
                    && p(&x)
            })
            .filter_map(|x| {
                x.ok()
                    .and_then(|x| if valid_file(&x) { Some(x) } else { None })
            });

        Ok(walker)
    }
}

impl FromStr for Manifest {
    type Err = Error;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let toml: Manifest = toml::from_str(raw)
            .with_context(|e| format_err!("invalid manifest file: {}", e))
            .map_err(Error::from)?;

        Ok(toml)
    }
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct PackageInfo {
    pub name: Name,
    pub version: Version,
    pub authors: Vec<String>,
    pub build: Option<SubPath>,
    pub description: Option<String>,
    #[serde(default = "Vec::new")]
    pub keywords: Vec<String>,
    pub homepage: Option<String>,
    pub repository: Option<String>,
    pub readme: Option<SubPath>,
    pub license: Option<String>,
    pub exclude: Option<Vec<String>>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(untagged)]
pub enum DepReq {
    Registry(Constraint),
    RegLong {
        version: Constraint,
        index: String,
    },
    Local {
        path: PathBuf,
    },
    Git {
        #[serde(with = "url_serde")]
        git: Url,
        #[serde(default = "default_tag")]
        tag: String,
    },
}

fn default_tag() -> String {
    "master".to_owned()
}

impl DepReq {
    pub fn into_dep(
        self,
        ixmap: &IndexMap<String, IndexRes>,
        n: Name,
    ) -> Res<(PackageId, Constraint)> {
        match self {
            DepReq::Registry(c) => {
                let def_index = ixmap
                    .get_index(0)
                    .ok_or_else(|| format_err!("no default index"))?;
                let pi = PackageId::new(n, def_index.1.clone().into());
                Ok((pi, c))
            }
            DepReq::RegLong { version, index } => {
                if let Some(mapped) = ixmap.get(&index) {
                    let pi = PackageId::new(n, mapped.clone().into());
                    Ok((pi, version))
                } else {
                    let ix = IndexRes::from_str(&index)?;
                    let pi = PackageId::new(n, ix.into());
                    Ok((pi, version))
                }
            }
            DepReq::Local { path } => {
                let res = DirectRes::Dir { path };
                let pi = PackageId::new(n, res.into());
                Ok((pi, Constraint::any()))
            }
            DepReq::Git { git, tag } => {
                let res = DirectRes::Git { repo: git, tag };
                let pi = PackageId::new(n, res.into());
                Ok((pi, Constraint::any()))
            }
        }
    }
}

#[derive(Deserialize, Serialize, Default, Debug, Clone)]
pub struct Targets {
    pub lib: Option<LibTarget>,
    #[serde(default = "Vec::new")]
    pub bin: Vec<BinTarget>,
    #[serde(default = "Vec::new")]
    pub test: Vec<TestTarget>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct LibTarget {
    #[serde(default = "default_lib_subpath")]
    pub path: SubPath,
    pub mods: Vec<String>,
    #[serde(default)]
    pub idris_opts: Vec<String>,
}

fn default_lib_subpath() -> SubPath {
    SubPath::from_path(Path::new("src")).unwrap()
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct BinTarget {
    pub name: String,
    #[serde(default = "default_bin_subpath")]
    pub path: SubPath,
    pub main: String,
    #[serde(default)]
    pub idris_opts: Vec<String>,
}

fn default_bin_subpath() -> SubPath {
    SubPath::from_path(Path::new("src")).unwrap()
}

/// A TestTarget is literally exactly the same as a BinTarget, with the only difference being
/// the difference in default path.
///
/// I know, code duplication sucks and is stupid, but what can ya do :v
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct TestTarget {
    pub name: Option<String>,
    #[serde(default = "default_test_subpath")]
    pub path: SubPath,
    pub main: String,
    #[serde(default)]
    pub idris_opts: Vec<String>,
}

fn default_test_subpath() -> SubPath {
    SubPath::from_path(Path::new("tests")).unwrap()
}

impl From<TestTarget> for BinTarget {
    fn from(t: TestTarget) -> Self {
        let default_name = format!("test-{}", &t.main)
            .trim_end_matches(".idr")
            .trim_end_matches(".lidr")
            .replace("/", "_")
            .replace(".", "_");

        BinTarget {
            name: t.name.unwrap_or(default_name),
            path: t.path,
            main: t.main,
            idris_opts: t.idris_opts,
        }
    }
}

impl BinTarget {
    // A note on extensions:
    // - If the extension of the target_path is idr or empty, it will be treated as a Main file.
    // - If the extension of the target_path is anything else, that extension will be the function
    //   of the preceding part's module which will be treated as the main function.
    pub fn resolve_bin(&self, parent: &Path) -> Option<(PathBuf, PathBuf)> {
        let main_path: PathBuf = self.main.clone().into();
        // If the main path is a valid SubPath, we just use that.
        if let Ok(s) = SubPath::from_path(&main_path) {
            if parent.join(&s.0).with_extension("idr").exists() {
                let target_path = if s.0.extension().is_none() {
                    parent.join(&s.0).with_extension("idr")
                } else {
                    parent.join(&s.0)
                };
                let src_path = target_path.parent().unwrap();
                // This is the relative target path
                let target_path: PathBuf = target_path.file_name().unwrap().to_os_string().into();
                return Some((src_path.to_path_buf(), target_path));
            } else if parent.join(&s.0).with_extension("lidr").exists() {
                let target_path = if s.0.extension().is_none() {
                    parent.join(&s.0).with_extension("lidr")
                } else {
                    parent.join(&s.0)
                };
                let src_path = target_path.parent().unwrap();
                // This is the relative target path
                let target_path: PathBuf = target_path.file_name().unwrap().to_os_string().into();
                return Some((src_path.to_path_buf(), target_path));
            }
        }

        // Otherwise, we have to do more complicated logic.
        let src_path = parent.join(&self.path.0);
        let mut split = self.main.trim_matches('.').rsplitn(2, '.');
        let after = split.next().unwrap();
        let (after, before) = if after == "lidr" || after == "idr" {
            if let Some(before) = split.next() {
                let mut new_split = before.rsplitn(2, '.');
                let fpart = new_split.next().unwrap();
                (format!("{}.{}", fpart, after), new_split.next())
            } else {
                (after.to_owned(), None)
            }
        } else {
            (after.to_owned(), split.next())
        };

        if let Some(before) = before {
            let target_path: PathBuf = before.replace(".", "/").into();
            // If there is at least one dot in the name:
            if src_path
                .join(&target_path)
                .join(&after)
                .with_extension("idr")
                .exists()
            {
                // If a file corresponding to the whole module name exists, we use that.
                Some((src_path, target_path.join(after).with_extension("idr")))
            } else if src_path
                .join(&target_path)
                .join(&after)
                .with_extension("lidr")
                .exists()
            {
                // If a literate file corresponding to the whole module name exists, we use that.
                Some((src_path, target_path.join(after).with_extension("lidr")))
            } else if src_path.join(&target_path).with_extension("idr").exists() {
                // Otherwise, if a file corresponding to the module name minus the last
                // part exists, we assume that the last part refers to a function which
                // should be treated as the main function.
                Some((src_path, target_path.with_extension(after)))
            } else if src_path.join(&target_path).with_extension("lidr").exists() {
                // Same, but for literate file
                Some((src_path, target_path.with_extension(after)))
            } else {
                None
            }
        } else {
            let target_path: PathBuf = after.into();
            // Otherwise, if the name has no dots:
            if src_path.join(&target_path).with_extension("idr").exists() {
                Some((src_path, target_path.with_extension("idr")))
            } else if src_path.join(&target_path).with_extension("lidr").exists() {
                Some((src_path, target_path.with_extension("lidr")))
            } else {
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn manifest_valid() {
        let manifest = r#"
[package]
name = 'ring_ding/test'
version = '1.0.0'
authors = ['me']
license = 'MIT'
description = "The best package ever released"
homepage = "https://github.com/elba/elba"
repository = "https://github.com/elba/elba"
readme = "README.md"
keywords = ["package-manager", "packaging"]
exclude = ["*.blah"]

[dependencies]
'awesome/a' = '>= 1.0.0 < 2.0.0'
'cool/b' = { git = 'https://github.com/super/cool', tag = "v1.0.0" }
'great/c' = { path = 'here/right/now' }

[dev_dependencies]
'ayy/x' = '2.0'

[[targets.bin]]
name = 'bin1'
main = 'src/bin/Here'

[targets.lib]
path = "src/lib/"
mods = [
    "Control.Monad.Wow",
    "Control.Monad.Yeet",
    "RingDing.Test"
]
idris_opts = ["--warnpartial", "--warnreach"]
"#;

        assert!(Manifest::from_str(manifest).is_ok());
    }

    #[test]
    fn manifest_valid_no_targets() {
        let manifest = r#"
[package]
name = 'ring_ding/test'
version = '1.0.0'
authors = ['Me <y@boi.me>']
license = 'MIT'

[dependencies]
'awesome/a' = '>= 1.0.0 < 2.0.0'
'cool/b' = { git = 'https://github.com/super/cool', tag = "v1.0.0" }
'great/c' = { path = 'here/right/now' }

[dev_dependencies]
'ayy/x' = '2.0'
"#;

        assert!(Manifest::from_str(manifest).is_ok());
    }

    #[test]
    fn manifest_invalid_target_path() {
        let manifest = r#"
[package]
name = 'ring_ding/test'
version = '1.0.0'
description = "a cool package"
authors = ['me']
license = 'MIT'

[dependencies]
'awesome/a' = '>= 1.0.0 < 2.0.0'
'cool/b' = { git = 'https://github.com/super/cool', tag = "v1.0.0" }
'great/c' = { path = 'here/right/now' }

[dev_dependencies]
'ayy/x' = '2.0'

[targets.lib]
path = "../oops"
mods = [
    "Right.Here"
]
"#;

        assert!(Manifest::from_str(manifest).is_err());
    }
}