artifact-app 0.6.3

Artifact is a design doc tool made for developers. It allows anyone to easily write and link their design docs both to each other and to source code, making it easy to track how complete their project is. Documents are revision controllable, can be rendered as a static web page and have a full suite of command line tools for searching, formatting and displaying them.
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
/*  artifact: the requirements tracking tool made for developers
 * Copyright (C) 2017  Garrett Berg <@vitiral, vitiral@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Lesser GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the Lesser GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * */

use dev_prefix::*;

use serde_json;
use tabwriter::TabWriter;

use super::types::*;
use super::display;

/// Get the ls subcommand, which is what creates the command
/// for the cmdline
/// see: SPC-cmd-ls
pub fn get_subcommand<'a, 'b>() -> App<'a, 'b> {
    SubCommand::with_name("ls")
        .about("list artifacts according to various parameters")
        .settings(&[AS::DeriveDisplayOrder, COLOR])
        .arg(Arg::with_name("search")
            .help("artifact names given in form `REQ-foo-[bar, baz-[1,2]]` OR pearl regexp \
                   pattern if -p is given")
            .use_delimiter(false))
        .arg(Arg::with_name("pattern")
            .short("p")
            .help("search FIELDS using pearl regexp SEARCH.")
            .value_name("FIELDS")
            .takes_value(true)
            .max_values(1)
            .min_values(0))
        .arg(Arg::with_name("long")
            .short("l")
            .help("print items in the 'long form'"))
        .arg(Arg::with_name("completed")
            .short("c")
            .help("filter by completeness (ie `<45`), < and > are inclusive, '>' == `>100`")
            .takes_value(true))
        .arg(Arg::with_name("tested")
            .short("t")
            .help("give a filter for the testedness in %. see '-c'")
            .takes_value(true))
        .arg(Arg::with_name("all")
            .short("A")
            .help("If set, additional flags will be *deactivated* instead of activated"))
        .arg(Arg::with_name("path")
            .short("D")
            .help("display the path where the artifact is defined"))
        .arg(Arg::with_name("parts")
            .short("P")
            .help("display the parts of the artifact"))
        .arg(Arg::with_name("partof")
            .short("O")
            .help("display the artifacts which this artifact is a partof"))
        .arg(Arg::with_name("loc")
            .short("L")
            .help("display location name"))
        .arg(Arg::with_name("text")
            .short("T")
            .help("display the text description of this artifact (first line only if not -l)"))
        .arg(Arg::with_name("plain")
            .long("plain")
            .help("do not display color in the output"))
        .arg(Arg::with_name("type")
            .long("type")
            .value_name("TYPE")
            .takes_value(true)
            .help("output type, default 'list'. Supported types are: list, json"))
    //.arg(Arg::with_name("file")
    //    .long("file")
    //    .takes_value(true)
    //    .help("output to file instead of stdout"))
}

/// return (lt, percent) returning None when there is no value
pub fn _get_percent(s: &str) -> result::Result<(Option<bool>, Option<i8>), String> {
    let mut s = s;
    let mut lt = None;
    if s.is_empty() {
        return Ok((lt, None));
    }
    let mut had_sign = true;
    match s.chars().next().unwrap() {
        '<' => lt = Some(true),
        '>' => lt = Some(false),
        '0'...'9' => had_sign = false,
        _ => {
            return Err("percent must be of the form: [SIGN]NUM where NUM is between 0 and 100 and \
                        SIGN is an optional < or >"
                .to_string())
        }
    }
    if had_sign {
        // the first char was either < or >
        s = s.split_at(1).1;
        if s.is_empty() {
            return Ok((lt, None));
        }
    }
    if s.is_empty() {
        return Ok((lt, None));
    }
    match s.parse::<i8>() {
        Ok(v) => {
            if v <= 100 && v >= -100 {
                Ok((lt, Some(v)))
            } else {
                Err("NUM must be between -100 and 100".to_string())
            }
        }
        Err(e) => Err(e.to_string()),
    }
}

fn get_percent(s: &str) -> result::Result<PercentSearch, String> {
    Ok(match _get_percent(s) {
        Ok((lt, perc)) => {
            if lt.is_none() && perc.is_none() {
                PercentSearch {
                    lt: false,
                    perc: 100,
                }
            } else if perc.is_none() {
                if lt.unwrap() {
                    PercentSearch {
                        lt: true,
                        perc: 0,
                    }
                } else {
                    PercentSearch {
                        lt: false,
                        perc: 100,
                    }
                }
            } else {
                let lt = match lt {
                    None => false,
                    Some(l) => l,
                };
                let perc = match perc {
                    None => 100,
                    Some(p) => p,
                };
                PercentSearch {
                    lt: lt,
                    perc: perc,
                }
            }
        }
        Err(e) => return Err(e),
    })
}

#[test]
fn test_get_percent() {
    // correct
    assert_eq!(_get_percent(""), Ok((None, None)));
    assert_eq!(_get_percent("<"), Ok((Some(true), None)));
    assert_eq!(_get_percent(">"), Ok((Some(false), None)));
    assert_eq!(_get_percent("<10"), Ok((Some(true), Some(10))));
    assert_eq!(_get_percent(">100"), Ok((Some(false), Some(100))));
    assert_eq!(_get_percent(">-100"), Ok((Some(false), Some(-100))));

    // test full struct
    assert_eq!(get_percent(""),
               Ok(PercentSearch {
                   lt: false,
                   perc: 100,
               }));
    assert_eq!(get_percent("<"),
               Ok(PercentSearch {
                   lt: true,
                   perc: 0,
               }));
    assert_eq!(get_percent(">"),
               Ok(PercentSearch {
                   lt: false,
                   perc: 100,
               }));
    assert_eq!(get_percent("89"),
               Ok(PercentSearch {
                   lt: false,
                   perc: 89,
               }));
    assert_eq!(get_percent(">89"),
               Ok(PercentSearch {
                   lt: false,
                   perc: 89,
               }));
    assert_eq!(get_percent("<89"),
               Ok(PercentSearch {
                   lt: true,
                   perc: 89,
               }));
    assert_eq!(get_percent(">-1"),
               Ok(PercentSearch {
                   lt: false,
                   perc: -1,
               }));

    // invalid
    assert!(get_percent(">101").is_err());
    assert!(get_percent("a").is_err());
    assert!(get_percent("<a").is_err());

}

#[cfg(not(windows))]
fn get_color(matches: &ArgMatches) -> bool {
    !matches.is_present("plain")
}

#[cfg(windows)]
fn get_color(matches: &ArgMatches) -> bool {
    false
}

#[derive(Debug, Eq, PartialEq)]
pub enum OutType {
    List, // default
    Json,
}

#[derive(Debug)]
pub struct Cmd {
    pub pattern: String,
    pub fmt_settings: FmtSettings,
    pub search_settings: SearchSettings,
    pub ty: OutType,
}

/// get all the information from the user input
pub fn get_cmd(matches: &ArgMatches) -> Result<Cmd> {
    let mut fmt_set = FmtSettings::default();
    fmt_set.long = matches.is_present("long");
    // fmt_set.recurse = matches.value_of("recursive").unwrap().parse::<u8>().unwrap();
    fmt_set.path = matches.is_present("path");
    fmt_set.parts = matches.is_present("parts");
    fmt_set.partof = matches.is_present("partof");
    fmt_set.loc_path = matches.is_present("loc");
    fmt_set.text = matches.is_present("text");
    fmt_set.color = get_color(matches);
    // #SPC-cmd-ls-display
    if matches.is_present("all") {
        // reverse everything
        fmt_set.path = !fmt_set.path;
        fmt_set.parts = !fmt_set.parts;
        fmt_set.partof = !fmt_set.partof;
        fmt_set.loc_path = !fmt_set.loc_path;
        fmt_set.text = !fmt_set.text;
    } else if fmt_set.long &&
              !(fmt_set.path || fmt_set.parts || fmt_set.partof || fmt_set.loc_path ||
                fmt_set.text) {
        // if long is specified but no other display attributes are specified
        fmt_set.path = true;
        fmt_set.parts = true;
        fmt_set.partof = true;
        fmt_set.loc_path = true;
        fmt_set.text = true;
    }

    // #SPC-cmd-ls-pattern
    let mut search_set = match (matches.is_present("pattern"), matches.value_of("pattern")) {
        (true, Some(p)) => SearchSettings::from_str(p)?,
        (true, None) => SearchSettings::from_str("N").unwrap(),
        (false, None) => SearchSettings::default(),
        _ => unreachable!(),
    };
    if let Some(c) = matches.value_of("completed") {
        search_set.completed = try!(get_percent(c))
    }
    if let Some(t) = matches.value_of("tested") {
        debug!("got tested: {}", t);
        search_set.tested = try!(get_percent(t));
    }

    let ty = match matches.value_of("type").unwrap_or("list") {
        "list" => OutType::List,
        "json" => OutType::Json,
        t => {
            let msg = format!("invalid type: {}", t);
            return Err(ErrorKind::CmdError(msg).into());
        }
    };

    let cmd = Cmd {
        pattern: matches.value_of("search").unwrap_or("").to_string(),
        fmt_settings: fmt_set,
        search_settings: search_set,
        ty: ty,
    };
    debug!("ls search: {:?}", cmd);
    Ok(cmd)
}

#[allow(trivial_regex)]
/// perform the ls command given the inputs
pub fn run_cmd<W: Write>(mut w: &mut W, cwd: &Path, cmd: &Cmd, project: &Project) -> Result<()> {
    let mut dne: Vec<ArtNameRc> = Vec::new();
    let artifacts = &project.artifacts;
    let mut fmt_set = cmd.fmt_settings.clone();

    // no color when exporting
    if cmd.ty != OutType::List {
        fmt_set.color = false;
    }

    // get the names -- they will be filtered next
    let mut names: Vec<_> = if cmd.search_settings.use_regex || cmd.pattern.is_empty() {
        let mut names: Vec<_> = artifacts.keys().cloned().collect();
        names.sort();
        names
    } else {
        // names are exactly specified according to the partof syntax
        let want_names = match ArtNames::from_str(&cmd.pattern) {
            Ok(n) => n,
            Err(e) => {
                error!("{}", e);
                return Err(ErrorKind::CmdError(format!("{}", e)).into());
            }
        };
        let mut names = Vec::new();
        for n in want_names {
            if artifacts.contains_key(n.as_ref()) {
                names.push(n);
            } else {
                dne.push(n)
            }
        }
        dne.sort();
        names.sort();
        names
    };

    // filter by various settings (not just pattern, also test/completeness %, etc)
    let names: Vec<_> = {
        let pat = if cmd.search_settings.use_regex {
            let p = RegexBuilder::new(&cmd.pattern)
                .case_insensitive(true)
                .build();
            match p {
                Ok(p) => p,
                Err(e) => {
                    return Err(ErrorKind::CmdError(format!("Invalid pattern: {}", e)).into());
                }
            }
        } else {
            Regex::new("").unwrap()
        };
        names.drain(0..)
            .filter(|n| {
                let a = artifacts.get(n).unwrap(); // we are guaranteed the name exists
                ui::show_artifact(n, a, &pat, &cmd.search_settings)
            })
            .collect()
    };
    debug!("artifact names selected: {:?}", names);
    if fmt_set.is_empty() {
        fmt_set.parts = true;
    }

    let mut displayed = ArtNames::new();
    // #SPC-cmd-ls-type
    match cmd.ty {
        OutType::List => {
            let mut tw = TabWriter::new(w);
            if !names.is_empty() && !fmt_set.long {
                display::write_table_header(&mut tw, &fmt_set);
            }
            for name in names {
                let f =
                    ui::fmt_artifact(&name, artifacts, &fmt_set, fmt_set.recurse, &mut displayed);
                f.write(&mut tw, cwd, artifacts, fmt_set.color, 0)?;
            }
            tw.flush()?; // this is necessary for actually writing the output
        }
        OutType::Json => {
            let out_arts: Vec<_> = names.iter()
                .map(|n| artifacts.get(n).unwrap().to_data(n))
                .collect();
            let value = serde_json::to_value(out_arts).unwrap();
            w.write_all(serde_json::to_string(&value).unwrap().as_bytes())?;
        }
    }
    if !dne.is_empty() {
        return Err(ErrorKind::NameNotFound(format!("The following artifacts do not exist: {:?}",
                                                   dne))
            .into());
    }
    Ok(())
}