fzf-make 0.7.0

A command line tool that executes make target using fuzzy finder with preview window.
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
use super::target::*;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::{fs::File, io::Read};

/// Makefile represents a Makefile.
#[derive(Clone)]
pub struct Makefile {
    path: PathBuf,
    include_files: Vec<Makefile>,
    targets: Targets,
}

impl Makefile {
    pub fn create_makefile() -> Result<Makefile, &'static str> {
        let Some(makefile_name) = Makefile::specify_makefile_name(".".to_string()) else { return Err("makefile not found\n") };
        Ok(Makefile::new(Path::new(&makefile_name).to_path_buf()))
    }

    pub fn to_include_files_string(&self) -> Vec<String> {
        let mut result: Vec<String> = vec![self.path.to_string_lossy().to_string()];

        for include_file in &self.include_files {
            Vec::append(&mut result, &mut include_file.to_include_files_string());
        }

        result
    }

    pub fn to_targets_string(&self) -> Vec<String> {
        let mut result: Vec<String> = vec![];
        (&mut result).append(&mut self.targets.0.clone());
        for include_file in &self.include_files {
            Vec::append(&mut result, &mut include_file.to_targets_string());
        }

        result
    }

    // I gave up writing tests using temp_dir because it was too difficult (it was necessary to change the implementation to some extent).
    // It is not difficult to ensure that it works with manual tests, so I will not do it for now.
    fn new(path: PathBuf) -> Makefile {
        // If the file path does not exist, the make command cannot be executed in the first place,
        // so it is not handled here.
        let file_content = path_to_content(path.clone());
        let include_files = content_to_include_file_paths(file_content.clone())
            .iter()
            .map(|included_file_path| Makefile::new(included_file_path.clone()))
            .collect();

        Makefile {
            path,
            include_files,
            targets: Targets::new(file_content),
        }
    }

    fn specify_makefile_name(target_path: String) -> Option<String> {
        //  By default, when make looks for the makefile, it tries the following names, in order: GNUmakefile, makefile and Makefile.
        //  https://www.gnu.org/software/make/manual/make.html#Makefile-Names
        // It needs to enumerate `Makefile` too not only `makefile` to make it work on case insensitive file system
        let makefile_name_options = vec!["GNUmakefile", "makefile", "Makefile"];

        for file_name in makefile_name_options {
            let exists = Path::new(&target_path).join(file_name).is_file();
            if exists {
                return Some(file_name.to_string());
            }
        }

        None
    }
}

pub fn path_to_content(path: PathBuf) -> String {
    let mut content = String::new();

    // Not handle cases where files are not found because make command cannot be
    // executed in the first place if Makefile or included files are not found.
    let mut f = File::open(&path).unwrap();
    f.read_to_string(&mut content).unwrap();

    content
}

/// The path should be relative path from current directory where make command is executed.
/// So the path can be treated as it is.
/// NOTE: path include `..` is not supported for now like `include ../c.mk`.
pub fn content_to_include_file_paths(file_content: String) -> Vec<PathBuf> {
    let mut result: Vec<PathBuf> = Vec::new();
    for line in file_content.lines() {
        let Some(include_files) = line_to_including_file_paths(line.to_string()) else { continue };

        result = [result, include_files].concat();
    }

    result
}

/// The line that is only include directive is ignored.
/// Pattern like `include foo *.mk $(bar)` is not handled for now.
/// Additional search is not executed if file is not found based on current directory.
fn line_to_including_file_paths(line: String) -> Option<Vec<PathBuf>> {
    // not to allow tab character, ` ` is used instead of `\s`
    let regex = Regex::new(r"^ *(include|-include|sinclude).*$").unwrap();
    regex.find(line.as_str()).and_then(|line| {
        let line_excluding_comment = match line.as_str().to_string().split_once("#") {
            Some((before, _)) => before.to_string(),
            None => line.as_str().to_string(),
        };

        let mut directive_and_file_names: Vec<PathBuf> = line_excluding_comment
            .split_whitespace()
            .map(|e| Path::new(e).to_path_buf())
            .collect();

        // remove directive itself. (include or -include or sinclude)
        directive_and_file_names.remove(0);

        Some(directive_and_file_names)
    })
}

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

    use std::fs::{self, File};
    use uuid::Uuid;

    #[test]
    fn specify_makefile_name_test() {
        struct Case {
            title: &'static str,
            files: Vec<&'static str>,
            expect: Option<String>,
        }
        let cases = vec![
            Case {
                title: "no makefile",
                files: vec!["README.md"],
                expect: None,
            },
            Case {
                title: "GNUmakefile",
                files: vec!["makefile", "GNUmakefile", "README.md", "Makefile"],
                expect: Some("GNUmakefile".to_string()),
            },
            Case {
                title: "makefile",
                files: vec!["makefile", "Makefile", "README.md"],
                expect: Some("makefile".to_string()),
            },
            // NOTE: not use this test case because there is a difference in handling case sensitivity between macOS and linux.
            // to use this test case, you need to determine whether the file system is
            // case-sensitive or not when test execute.
            // Case {
            // title: "Makefile",
            // files: vec!["Makefile", "README.md"],
            // expect: Some("makefile".to_string()),
            // },
        ];

        for case in cases {
            let random_dir_name = Uuid::new_v4().to_string();
            let tmp_dir = std::env::temp_dir().join(random_dir_name);
            match fs::create_dir(tmp_dir.as_path()) {
                Err(e) => panic!("fail to create dir: {:?}", e),
                Ok(_) => {}
            }

            for file in case.files {
                match File::create(tmp_dir.join(file)) {
                    Err(e) => panic!("fail to create file: {:?}", e),
                    Ok(_) => {}
                }
            }

            assert_eq!(
                case.expect,
                Makefile::specify_makefile_name(tmp_dir.to_string_lossy().to_string()),
                "\nFailed: 🚨{:?}🚨\n",
                case.title,
            );
        }
    }

    #[test]
    fn makefile_to_include_files_string_test() {
        struct Case {
            title: &'static str,
            makefile: Makefile,
            expect: Vec<&'static str>,
        }

        let cases = vec![
            Case {
                title: "makefile with no include directive",
                makefile: Makefile {
                    path: Path::new("path").to_path_buf(),
                    include_files: vec![],
                    targets: Targets(vec!["test".to_string(), "run".to_string()]),
                },
                expect: vec!["path"],
            },
            Case {
                title: "makefile with nested include directive",
                makefile: Makefile {
                    path: Path::new("path1").to_path_buf(),
                    include_files: vec![
                        Makefile {
                            path: Path::new("path2").to_path_buf(),
                            include_files: vec![Makefile {
                                path: Path::new("path2-1").to_path_buf(),
                                include_files: vec![],
                                targets: Targets(vec![]),
                            }],
                            targets: Targets(vec![]),
                        },
                        Makefile {
                            path: Path::new("path3").to_path_buf(),
                            include_files: vec![],
                            targets: Targets(vec![]),
                        },
                    ],
                    targets: Targets(vec![]),
                },
                expect: vec!["path1", "path2", "path2-1", "path3"],
            },
        ];

        for case in cases {
            let mut expect_string: Vec<String> =
                case.expect.iter().map(|e| e.to_string()).collect();
            expect_string.sort();
            let sorted_result = case.makefile.to_include_files_string();

            assert_eq!(
                expect_string, sorted_result,
                "\nFailed: 🚨{:?}🚨\n",
                case.title,
            )
        }
    }

    #[test]
    fn makefile_to_targets_string_test() {
        struct Case {
            title: &'static str,
            makefile: Makefile,
            expect: Vec<&'static str>,
        }

        let cases = vec![
            Case {
                title: "makefile with no target",
                makefile: Makefile {
                    path: Path::new("path").to_path_buf(),
                    include_files: vec![],
                    targets: Targets(vec![]),
                },
                expect: vec![],
            },
            Case {
                title: "makefile with no include directive",
                makefile: Makefile {
                    path: Path::new("path").to_path_buf(),
                    include_files: vec![],
                    targets: Targets(vec!["test".to_string(), "run".to_string()]),
                },
                expect: vec!["test", "run"],
            },
            Case {
                title: "makefile with nested include directive",
                makefile: Makefile {
                    path: Path::new("path1").to_path_buf(),
                    include_files: vec![
                        Makefile {
                            path: Path::new("path2").to_path_buf(),
                            include_files: vec![Makefile {
                                path: Path::new("path2-1").to_path_buf(),
                                include_files: vec![],
                                targets: Targets(vec!["test2-1".to_string(), "run2-1".to_string()]),
                            }],
                            targets: Targets(vec!["test2".to_string(), "run2".to_string()]),
                        },
                        Makefile {
                            path: Path::new("path3").to_path_buf(),
                            include_files: vec![],
                            targets: Targets(vec!["test3".to_string(), "run3".to_string()]),
                        },
                    ],
                    targets: Targets(vec!["test1".to_string(), "run1".to_string()]),
                },
                expect: vec![
                    "test1", "run1", "test2", "run2", "test2-1", "run2-1", "test3", "run3",
                ],
            },
        ];

        for case in cases {
            let expect_string: Vec<String> = case.expect.iter().map(|e| e.to_string()).collect();

            assert_eq!(
                expect_string,
                case.makefile.to_targets_string(),
                "\nFailed: 🚨{:?}🚨\n",
                case.title,
            )
        }
    }

    #[test]
    fn extract_including_file_paths_test() {
        struct Case {
            title: &'static str,
            file_content: &'static str,
            expect: Vec<PathBuf>,
        }
        let cases = vec![
            Case {
                title: "has two lines of line includes include directive",
                file_content: "\
    include one.mk two.mk
    .PHONY: echo-test
    echo-test:
    	@echo good

    include three.mk four.mk

    .PHONY: test
    test:
    	cargo nextest run",
                expect: vec![
                    Path::new("one.mk").to_path_buf(),
                    Path::new("two.mk").to_path_buf(),
                    Path::new("three.mk").to_path_buf(),
                    Path::new("four.mk").to_path_buf(),
                ],
            },
            Case {
                title: "has no lines includes include directive",
                file_content: "\
    .PHONY: echo-test test
    echo-test:
    	@echo good

    test:
    	cargo nextest run",
                expect: vec![],
            },
        ];

        for mut case in cases {
            let random_dir_name = Uuid::new_v4().to_string();
            let tmp_dir = std::env::temp_dir().join(random_dir_name);
            match fs::create_dir(tmp_dir.as_path()) {
                Err(e) => panic!("fail to create dir: {:?}", e),
                Ok(_) => {}
            }

            case.expect.sort();
            let mut got = content_to_include_file_paths(case.file_content.to_string());
            got.sort();

            assert_eq!(case.expect, got, "\nFailed: 🚨{:?}🚨\n", case.title,);
        }
    }

    #[test]
    fn line_to_including_file_paths_test() {
        struct Case {
            title: &'static str,
            line: &'static str,
            expect: Option<Vec<PathBuf>>,
        }
        let cases = vec![
            Case {
                title: "include one.mk two.mk",
                line: "include one.mk two.mk",
                expect: Some(vec![
                    Path::new("one.mk").to_path_buf(),
                    Path::new("two.mk").to_path_buf(),
                ]),
            },
            Case {
                title: "-include",
                line: "-include one.mk two.mk",
                expect: Some(vec![
                    Path::new("one.mk").to_path_buf(),
                    Path::new("two.mk").to_path_buf(),
                ]),
            },
            Case {
                title: "sinclude",
                line: "sinclude hoge.mk fuga.mk",
                expect: Some(vec![
                    Path::new("hoge.mk").to_path_buf(),
                    Path::new("fuga.mk").to_path_buf(),
                ]),
            },
            Case {
                title: " include one.mk two.mk",
                line: " include one.mk two.mk",
                expect: Some(vec![
                    Path::new("one.mk").to_path_buf(),
                    Path::new("two.mk").to_path_buf(),
                ]),
            },
            Case {
                title: "include one.mk two.mk(tab is not allowed)",
                line: "	include one.mk two.mk",
                expect: None,
            },
            Case {
                title: "not include directive",
                line: ".PHONY: test",
                expect: None,
            },
            Case {
                title: "include comment",
                line: "include one.mk two.mk # three.mk",
                expect: Some(vec![
                    Path::new("one.mk").to_path_buf(),
                    Path::new("two.mk").to_path_buf(),
                ]),
            },
            Case {
                title: "# include one.mk two.mk # three.mk",
                line: "# include one.mk two.mk # three.mk",
                expect: None,
            },
            Case {
                title: "included",
                line: "included",
                expect: Some(vec![]),
            },
        ];

        for case in cases {
            let random_dir_name = Uuid::new_v4().to_string();
            let tmp_dir = std::env::temp_dir().join(random_dir_name);
            match fs::create_dir(tmp_dir.as_path()) {
                Err(e) => panic!("fail to create dir: {:?}", e),
                Ok(_) => {}
            }

            assert_eq!(
                case.expect,
                line_to_including_file_paths(case.line.to_string()),
                "\nFailed: 🚨{:?}🚨\n",
                case.title,
            );
        }
    }
}