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
use crate::cmd_ctags::CmdCtags;
use crate::cmd_git::CmdGit;
use dirs;
use failure::{Error, ResultExt};
use serde_derive::{Deserialize, Serialize};
use std::fs;
use std::io::BufRead;
use std::io::{stdout, BufWriter, Read, Write};
use std::path::PathBuf;
use std::process::Output;
use std::str;
use structopt::{clap, StructOpt};
use structopt_toml::StructOptToml;
use time::{Duration, PreciseTime};
use toml;

// ---------------------------------------------------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------------------------------------------------

#[derive(Debug, Deserialize, Serialize, StructOpt, StructOptToml)]
#[serde(default)]
#[structopt(name = "ptags")]
#[structopt(raw(
    long_version = "option_env!(\"LONG_VERSION\").unwrap_or(env!(\"CARGO_PKG_VERSION\"))"
))]
#[structopt(raw(setting = "clap::AppSettings::AllowLeadingHyphen"))]
#[structopt(raw(setting = "clap::AppSettings::ColoredHelp"))]
pub struct Opt {
    /// Number of threads
    #[structopt(short = "t", long = "thread", default_value = "8")]
    pub thread: usize,

    /// Output filename ( filename '-' means output to stdout )
    #[structopt(short = "f", long = "file", default_value = "tags", parse(from_os_str))]
    pub output: PathBuf,

    /// Search directory
    #[structopt(name = "DIR", default_value = ".", parse(from_os_str))]
    pub dir: PathBuf,

    /// Show statistics
    #[structopt(short = "s", long = "stat")]
    pub stat: bool,

    /// Filename of input file list
    #[structopt(short = "L", long = "list")]
    pub list: Option<String>,

    /// Path to ctags binary
    #[structopt(long = "bin-ctags", default_value = "ctags", parse(from_os_str))]
    pub bin_ctags: PathBuf,

    /// Path to git binary
    #[structopt(long = "bin-git", default_value = "git", parse(from_os_str))]
    pub bin_git: PathBuf,

    /// Options passed to ctags
    #[structopt(short = "c", long = "opt-ctags", raw(number_of_values = "1"))]
    pub opt_ctags: Vec<String>,

    /// Options passed to git
    #[structopt(short = "g", long = "opt-git", raw(number_of_values = "1"))]
    pub opt_git: Vec<String>,

    /// Options passed to git-lfs
    #[structopt(long = "opt-git-lfs", raw(number_of_values = "1"))]
    pub opt_git_lfs: Vec<String>,

    /// Verbose mode
    #[structopt(short = "v", long = "verbose")]
    pub verbose: bool,

    /// Exclude git-lfs tracked files
    #[structopt(long = "exclude-lfs")]
    pub exclude_lfs: bool,

    /// Include untracked files
    #[structopt(long = "include-untracked")]
    pub include_untracked: bool,

    /// Include ignored files
    #[structopt(long = "include-ignored")]
    pub include_ignored: bool,

    /// Include submodule files
    #[structopt(long = "include-submodule")]
    pub include_submodule: bool,

    /// Validate UTF8 sequence of tag file
    #[structopt(long = "validate-utf8")]
    pub validate_utf8: bool,

    /// Disable tags sort
    #[structopt(long = "unsorted")]
    pub unsorted: bool,

    /// Glob pattern of exclude file ( ex. --exclude '*.rs' )
    #[structopt(short = "e", long = "exclude", raw(number_of_values = "1"))]
    pub exclude: Vec<String>,

    /// Generate shell completion file
    #[structopt(
        long = "completion",
        raw(possible_values = "&[\"bash\", \"fish\", \"zsh\", \"powershell\"]")
    )]
    pub completion: Option<String>,

    /// Generate configuration sample file
    #[structopt(long = "config")]
    pub config: bool,
}

// ---------------------------------------------------------------------------------------------------------------------
// Functions
// ---------------------------------------------------------------------------------------------------------------------

macro_rules! watch_time (
    ( $func:block ) => (
        {
            let beg = PreciseTime::now();
            $func;
            beg.to(PreciseTime::now())
        }
    );
);

pub fn git_files(opt: &Opt) -> Result<Vec<String>, Error> {
    let list = CmdGit::get_files(&opt)?;
    let mut files = vec![String::from(""); opt.thread];

    for (i, f) in list.iter().enumerate() {
        files[i % opt.thread].push_str(f);
        files[i % opt.thread].push_str("\n");
    }

    Ok(files)
}

pub fn input_files(file: &String, opt: &Opt) -> Result<Vec<String>, Error> {
    let mut list = Vec::new();
    if file == &String::from("-") {
        let stdin = std::io::stdin();
        for line in stdin.lock().lines() {
            list.push(String::from(line?));
        }
    } else {
        for line in fs::read_to_string(file)?.lines() {
            list.push(String::from(line));
        }
    }

    let mut files = vec![String::from(""); opt.thread];

    for (i, f) in list.iter().enumerate() {
        files[i % opt.thread].push_str(f);
        files[i % opt.thread].push_str("\n");
    }

    Ok(files)
}

fn call_ctags(opt: &Opt, files: &[String]) -> Result<Vec<Output>, Error> {
    Ok(CmdCtags::call(&opt, &files)?)
}

fn get_tags_header(opt: &Opt) -> Result<String, Error> {
    Ok(CmdCtags::get_tags_header(&opt).context("failed to get ctags header")?)
}

fn write_tags(opt: &Opt, outputs: &[Output]) -> Result<(), Error> {
    let mut iters = Vec::new();
    let mut lines = Vec::new();
    for o in outputs {
        let mut iter = if opt.validate_utf8 {
            str::from_utf8(&o.stdout)?.lines()
        } else {
            unsafe { str::from_utf8_unchecked(&o.stdout).lines() }
        };
        lines.push(iter.next());
        iters.push(iter);
    }

    let mut f = if opt.output.to_str().unwrap_or("") == "-" {
        BufWriter::new(Box::new(stdout()) as Box<dyn Write>)
    } else {
        let f = fs::File::create(&opt.output)?;
        BufWriter::new(Box::new(f) as Box<dyn Write>)
    };

    f.write(get_tags_header(&opt)?.as_bytes())?;

    while lines.iter().any(|x| x.is_some()) {
        let mut min = 0;
        for i in 1..lines.len() {
            if opt.unsorted {
                if !lines[i].is_none() && lines[min].is_none() {
                    min = i;
                }
            } else {
                if !lines[i].is_none()
                    && (lines[min].is_none() || lines[i].unwrap() < lines[min].unwrap())
                {
                    min = i;
                }
            }
        }
        f.write(lines[min].unwrap().as_bytes())?;
        f.write("\n".as_bytes())?;
        lines[min] = iters[min].next();
    }

    Ok(())
}

// ---------------------------------------------------------------------------------------------------------------------
// Run
// ---------------------------------------------------------------------------------------------------------------------

pub fn run_opt(opt: &Opt) -> Result<(), Error> {
    if opt.config {
        let toml = toml::to_string(&opt)?;
        println!("{}", toml);
        return Ok(());
    }

    match opt.completion {
        Some(ref x) => {
            let shell = match x.as_str() {
                "bash" => clap::Shell::Bash,
                "fish" => clap::Shell::Fish,
                "zsh" => clap::Shell::Zsh,
                "powershell" => clap::Shell::PowerShell,
                _ => clap::Shell::Bash,
            };
            Opt::clap().gen_completions("ptags", shell, "./");
            return Ok(());
        }
        None => {}
    }

    let files;
    let time_git_files;
    if let Some(ref list) = opt.list {
        files = input_files(list, &opt).context("failed to get file list")?;
        time_git_files = Duration::seconds(0);
    } else {
        time_git_files = watch_time!({
            files = git_files(&opt).context("failed to get file list")?;
        });
    }

    let outputs;
    let time_call_ctags = watch_time!({
        outputs = call_ctags(&opt, &files).context("failed to call ctags")?;
    });

    let time_write_tags = watch_time!({
        let _ = write_tags(&opt, &outputs)
            .context(format!("failed to write file ({:?})", &opt.output))?;
    });

    if opt.stat {
        let sum: usize = files.iter().map(|x| x.lines().count()).sum();

        eprintln!("\nStatistics");
        eprintln!("- Options");
        eprintln!("    thread    : {}\n", opt.thread);

        eprintln!("- Searched files");
        eprintln!("    total     : {}\n", sum);

        eprintln!("- Elapsed time[ms]");
        eprintln!("    git_files : {}", time_git_files.num_milliseconds());
        eprintln!("    call_ctags: {}", time_call_ctags.num_milliseconds());
        eprintln!("    write_tags: {}", time_write_tags.num_milliseconds());
    }

    Ok(())
}

#[cfg_attr(tarpaulin, skip)]
pub fn run() -> Result<(), Error> {
    let cfg_path = match dirs::home_dir() {
        Some(mut path) => {
            path.push(".ptags.toml");
            if path.exists() {
                Some(path)
            } else {
                None
            }
        }
        None => None,
    };

    let opt = match cfg_path {
        Some(path) => {
            let mut f =
                fs::File::open(&path).context(format!("failed to open file ({:?})", path))?;
            let mut s = String::new();
            let _ = f.read_to_string(&mut s);
            Opt::from_args_with_toml(&s).context(format!("failed to parse toml ({:?})", path))?
        }
        None => Opt::from_args(),
    };
    run_opt(&opt)
}

// ---------------------------------------------------------------------------------------------------------------------
// Test
// ---------------------------------------------------------------------------------------------------------------------

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

    #[test]
    fn test_run() {
        let args = vec!["ptags"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
    }

    #[test]
    fn test_run_opt() {
        let args = vec!["ptags", "-s", "-v", "--validate-utf8", "--unsorted"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
    }

    #[test]
    fn test_run_fail() {
        let args = vec!["ptags", "--bin-git", "aaa"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert_eq!(
            &format!("{:?}", ret)[0..42],
            "Err(Os { code: 2, kind: NotFound, message:"
        );
    }

    #[test]
    fn test_run_completion() {
        let args = vec!["ptags", "--completion", "bash"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
        let args = vec!["ptags", "--completion", "fish"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
        let args = vec!["ptags", "--completion", "zsh"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
        let args = vec!["ptags", "--completion", "powershell"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());

        assert!(Path::new("ptags.bash").exists());
        assert!(Path::new("ptags.fish").exists());
        assert!(Path::new("_ptags").exists());
        assert!(Path::new("_ptags.ps1").exists());
        let _ = fs::remove_file("ptags.bash");
        let _ = fs::remove_file("ptags.fish");
        let _ = fs::remove_file("_ptags");
        let _ = fs::remove_file("_ptags.ps1");
    }

    #[test]
    fn test_run_config() {
        let args = vec!["ptags", "--config"];
        let opt = Opt::from_iter(args.iter());
        let ret = run_opt(&opt);
        assert!(ret.is_ok());
    }
}