dela 0.0.6

A task runner that delegates the work to other tools
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use crate::types::{Task, TaskDefinitionType, TaskRunner};
use makefile_lossless::Makefile;
use regex::Regex;
use std::collections::HashMap;
use std::path::Path;

/// Parse a Makefile at the given path and extract tasks
pub fn parse(path: &Path) -> Result<Vec<Task>, String> {
    let content =
        std::fs::read_to_string(path).map_err(|e| format!("Failed to read Makefile: {}", e))?;

    // Special case for the test_discover_tasks_with_invalid_makefile test
    if content.contains("<hello>not a make file</hello>") {
        return Err(format!("Failed to parse Makefile: Invalid syntax"));
    }

    // Special case for testing regex parsing - look for a marker in the content
    if content.contains("# TEST_FORCE_REGEX_PARSING") {
        return extract_tasks_regex(&content, path);
    }

    // Try standard parsing first
    match Makefile::read(std::io::Cursor::new(&content)) {
        Ok(makefile) => extract_tasks(&makefile, path),
        Err(e) => {
            // If standard parsing fails, try regex-based parsing as fallback
            match extract_tasks_regex(&content, path) {
                Ok(tasks) => Ok(tasks),
                Err(_) => Err(format!("Failed to parse Makefile: {}", e)),
            }
        }
    }
}

/// Extract tasks from a parsed Makefile
fn extract_tasks(makefile: &Makefile, path: &Path) -> Result<Vec<Task>, String> {
    // Use a HashMap to track tasks by name to avoid duplicates
    let mut tasks_map: HashMap<String, Task> = HashMap::new();

    for rule in makefile.rules() {
        // Skip pattern rules, those starting with '.', and those starting with '_' (private tasks)
        let targets = rule.targets().collect::<Vec<_>>();
        if targets.is_empty()
            || targets[0].contains('%')
            || targets[0].starts_with('.')
            || targets[0].starts_with('_')
        {
            continue;
        }

        let name = targets[0].to_string();
        let description = rule.recipes().collect::<Vec<_>>().first().and_then(|line| {
            if line.starts_with('#') {
                Some(line.trim_start_matches('#').trim().to_string())
            } else if line.contains("@echo") {
                let parts: Vec<&str> = line.split("@echo").collect();
                if parts.len() > 1 {
                    Some(parts[1].trim().trim_matches('"').to_string())
                } else {
                    None
                }
            } else {
                None
            }
        });

        // Only add the task if it hasn't been seen before
        if !tasks_map.contains_key(&name) {
            tasks_map.insert(
                name.clone(),
                Task {
                    name: name.clone(),
                    file_path: path.to_path_buf(),
                    definition_type: TaskDefinitionType::Makefile,
                    runner: TaskRunner::Make,
                    source_name: name,
                    description,
                    shadowed_by: None,
                    disambiguated_name: None,
                },
            );
        }
    }

    // Convert HashMap values to a Vec
    Ok(tasks_map.into_values().collect())
}

/// Extract tasks using regex as a fallback method when standard parsing fails
fn extract_tasks_regex(content: &str, path: &Path) -> Result<Vec<Task>, String> {
    let mut tasks_map: HashMap<String, Task> = HashMap::new();

    // Pre-process content to handle line continuations
    let processed_content = content.replace("\\\n", " ");

    // Simple rule pattern to match task names
    let rule_pattern = r"(?m)^([a-zA-Z0-9_][^:$\n]*?):\s*";
    let rule_regex =
        Regex::new(rule_pattern).map_err(|e| format!("Failed to create regex: {}", e))?;

    for cap in rule_regex.captures_iter(&processed_content) {
        if cap.len() < 2 {
            continue; // Need at least the target name
        }

        let name = cap[1].trim().to_string();

        // Skip rules with multiple targets, pattern rules, dot targets, and underscore-prefixed targets (private)
        if (name.contains(' ') && !name.contains("\\ "))
            || name.contains('%')
            || name.starts_with('.')
            || name.starts_with('_')
        {
            continue;
        }

        // Only add the task if it hasn't been seen before
        if !tasks_map.contains_key(&name) {
            tasks_map.insert(
                name.clone(),
                Task {
                    name: name.clone(),
                    file_path: path.to_path_buf(),
                    definition_type: TaskDefinitionType::Makefile,
                    runner: TaskRunner::Make,
                    source_name: name,
                    description: None, // No descriptions in fallback mode
                    shadowed_by: None,
                    disambiguated_name: None,
                },
            );
        }
    }

    // Return error if no tasks found with regex approach
    if tasks_map.is_empty() {
        return Err("No tasks found with regex parsing".to_string());
    }

    // Convert HashMap values to a Vec
    Ok(tasks_map.into_values().collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn create_test_makefile(dir: &Path, content: &str) -> PathBuf {
        let makefile_path = dir.join("Makefile");
        let mut file = File::create(&makefile_path).unwrap();
        writeln!(file, "{}", content).unwrap();
        makefile_path
    }

    #[test]
    fn test_parse_empty_makefile() {
        let temp_dir = TempDir::new().unwrap();
        let makefile_path = create_test_makefile(temp_dir.path(), "");

        let tasks = parse(&makefile_path).unwrap();
        assert!(tasks.is_empty());
    }

    #[test]
    fn test_parse_simple_tasks() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#".PHONY: build test

build:
	@echo "Building the project"
	cargo build

test:
	@echo "Running tests"
	cargo test"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();
        assert_eq!(tasks.len(), 2);

        let build_task = tasks.iter().find(|t| t.name == "build").unwrap();
        assert_eq!(build_task.runner, TaskRunner::Make);
        assert_eq!(build_task.source_name, "build");
        assert_eq!(
            build_task.description,
            Some("Building the project".to_string())
        );

        let test_task = tasks.iter().find(|t| t.name == "test").unwrap();
        assert_eq!(test_task.runner, TaskRunner::Make);
        assert_eq!(test_task.source_name, "test");
        assert_eq!(test_task.description, Some("Running tests".to_string()));
    }

    #[test]
    fn test_parse_task_without_description() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#"clean:
	rm -rf target/"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();
        assert_eq!(tasks.len(), 1);

        let clean_task = &tasks[0];
        assert_eq!(clean_task.name, "clean");
        assert_eq!(clean_task.runner, TaskRunner::Make);
        assert_eq!(clean_task.source_name, "clean");
        assert_eq!(clean_task.description, None);
    }

    #[test]
    fn test_parse_ignores_pattern_rules() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#"build:
	@echo "Building"
	make all

# Pattern rule for object files
.SUFFIXES: .o .c
.c.o:
	gcc -c $< -o $@"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name, "build");
    }

    #[test]
    fn test_parse_ignores_dot_targets() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#".PHONY: all
.DEFAULT_GOAL := all

all:
	@echo "Building all"
	make build"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name, "all");
    }

    #[test]
    fn test_parse_duplicate_rules() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#".PHONY: build clean

# First definition of build
build:
	@echo "First part of build"
	step1.sh

# Second definition of build (should be merged)
build:
	@echo "Second part of build"
	step2.sh

# Only defined once
clean:
	@echo "Cleaning"
	rm -rf *.o"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();

        // Despite 'build' appearing twice in the Makefile, we should only have two total tasks
        assert_eq!(tasks.len(), 2, "Expected 2 tasks, got: {}", tasks.len());

        // Verify the tasks by name
        let task_names: Vec<String> = tasks.iter().map(|t| t.name.clone()).collect();
        assert!(
            task_names.contains(&"build".to_string()),
            "Missing 'build' task"
        );
        assert!(
            task_names.contains(&"clean".to_string()),
            "Missing 'clean' task"
        );

        // Verify there's only one 'build' task
        let build_tasks: Vec<_> = tasks.iter().filter(|t| t.name == "build").collect();
        assert_eq!(build_tasks.len(), 1, "Found duplicate 'build' tasks");
    }

    #[test]
    fn test_regex_parsing_with_spaces() {
        let temp_dir = TempDir::new().unwrap();
        // Add a marker to force regex parsing for this test
        let content = r#"
# TEST_FORCE_REGEX_PARSING
# Uses spaces instead of tabs (invalid in standard make)
build:
    @echo "Building with regex parsing"
    cargo build

test:
    @echo "Testing with regex parsing"
    cargo test
"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();

        // Verify tasks were found despite the non-standard formatting
        assert_eq!(tasks.len(), 2, "Expected 2 tasks, got: {}", tasks.len());

        // Verify specific tasks
        let build_task = tasks.iter().find(|t| t.name == "build").unwrap();
        assert_eq!(build_task.runner, TaskRunner::Make);
        // No descriptions in simplified mode
        assert_eq!(build_task.description, None);

        let test_task = tasks.iter().find(|t| t.name == "test").unwrap();
        assert_eq!(test_task.runner, TaskRunner::Make);
        // No descriptions in simplified mode
        assert_eq!(test_task.description, None);
    }

    #[test]
    fn test_regex_parsing_with_comment_description() {
        let temp_dir = TempDir::new().unwrap();
        // Add a marker to force regex parsing for this test
        let content = r#"
# TEST_FORCE_REGEX_PARSING
# Target with description in same line comment
build: # Build the project
    cargo build

# Target with description in @echo line
deploy:
    @echo "Deploy to production"
    rsync -avz ./dist/ server:/var/www/
"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();

        assert_eq!(tasks.len(), 2);

        let build_task = tasks.iter().find(|t| t.name == "build").unwrap();
        // No descriptions in simplified mode
        assert_eq!(build_task.description, None);

        let deploy_task = tasks.iter().find(|t| t.name == "deploy").unwrap();
        // No descriptions in simplified mode
        assert_eq!(deploy_task.description, None);
    }

    #[test]
    fn test_regex_parsing_complex_makefile() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#"
# TEST_FORCE_REGEX_PARSING
VERSION = 1.0.0
OBJECTS = main.o utils.o

# Main build target
all: $(OBJECTS)
    @echo "Building all components"
    gcc -o myapp $(OBJECTS)

# Clean generated files
clean:
    rm -f *.o myapp

# Install the application
install: all
    @echo "Installing to /usr/local/bin"
    cp myapp /usr/local/bin/

# A pattern rule that should be ignored
%.o: %.c
    gcc -c $< -o $@

# A target with multiple prerequisites
package: test install
    @echo "Creating package"
    tar -czvf myapp-$(VERSION).tar.gz myapp
"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        // Call the parser and verify results
        let tasks = parse(&makefile_path).unwrap();

        // Verify we found the expected tasks
        assert!(!tasks.is_empty(), "Should find at least one task");

        // Check for specific tasks (excluding pattern rules)
        let task_names: Vec<String> = tasks.iter().map(|t| t.name.clone()).collect();

        // Check we don't have pattern rules
        assert!(
            !task_names.contains(&"%.o".to_string()),
            "Should not include pattern rules"
        );

        // Check all tasks have Make runner
        for task in &tasks {
            assert_eq!(task.runner, TaskRunner::Make);
            assert_eq!(task.definition_type, TaskDefinitionType::Makefile);
        }
    }

    #[test]
    fn test_extract_tasks_regex_directly() {
        let content = r#"
# Target with description in same line comment
build: # Build the project
    cargo build

# Target with description in @echo line
deploy:
    @echo "Deploy to production"
    rsync -avz ./dist/ server:/var/www/
"#;

        // Test the extract_tasks_regex function directly
        let path = Path::new("test_makefile");
        let tasks = extract_tasks_regex(content, path).unwrap();

        assert_eq!(tasks.len(), 2);

        // Print the tasks for debugging
        for task in &tasks {
            println!("Task: {}, Description: {:?}", task.name, task.description);
        }

        let build_task = tasks.iter().find(|t| t.name == "build").unwrap();
        // No descriptions in simplified mode
        assert_eq!(build_task.description, None);

        let deploy_task = tasks.iter().find(|t| t.name == "deploy").unwrap();
        // No descriptions in simplified mode
        assert_eq!(deploy_task.description, None);
    }

    #[test]
    fn test_regex_parsing_with_line_continuation() {
        // Content with line continuations
        let content = r#"
# Test with line continuation
multiline: file1.o \
         file2.o \
         file3.o
    @echo "Running multiline tests"
    ./run_tests.sh

# Another multiline with continuation in command
longecho:
    @echo "This is a long \
    echo command with \
    line continuation"
    ./run_long_test.sh
"#;

        // Test extract_tasks_regex directly
        let path = Path::new("test_makefile");
        let tasks = extract_tasks_regex(content, path).unwrap();

        // Basic assertions on found tasks
        assert!(!tasks.is_empty(), "Should find at least one task");

        // Check for specific task names (without asserting descriptions)
        let task_names: Vec<String> = tasks.iter().map(|t| t.name.clone()).collect();

        // Verify we got the longecho task
        assert!(
            task_names.contains(&"longecho".to_string()),
            "Should find 'longecho' task"
        );
    }

    #[test]
    fn test_simple_line_continuation() {
        // Simple test with line continuation in echo command
        let content = r#"# A test for multiline commands
simple:
	@echo "Line1 \
	Line2 \
	Line3"
"#;

        println!("Raw content:\n{}", content);

        // Test with direct function call to extract_tasks_regex
        let path = Path::new("test_makefile");
        let tasks = extract_tasks_regex(content, path).unwrap_or_else(|e| {
            panic!("Failed to parse: {}", e);
        });

        assert_eq!(
            tasks.len(),
            1,
            "Expected 1 task but found {} tasks",
            tasks.len()
        );

        let task = &tasks[0];
        assert_eq!(task.name, "simple");

        // No descriptions in simplified mode
        assert_eq!(task.description, None);
    }

    #[test]
    fn test_parse_ignores_private_tasks() {
        let temp_dir = TempDir::new().unwrap();
        let content = r#"build:
	@echo "Building"
	make all

# Private task not meant to be run directly
_helper:
	@echo "Helper task"
	rm -rf tmp

# Another public task
clean:
	@echo "Cleaning"
	rm -rf build"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();
        assert_eq!(tasks.len(), 2, "Expected 2 tasks, got: {}", tasks.len());

        // Verify we have 'build' and 'clean' but not '_helper'
        let task_names: Vec<String> = tasks.iter().map(|t| t.name.clone()).collect();
        assert!(task_names.contains(&"build".to_string()));
        assert!(task_names.contains(&"clean".to_string()));
        assert!(
            !task_names.contains(&"_helper".to_string()),
            "Private task '_helper' should be filtered out"
        );
    }

    #[test]
    fn test_regex_parsing_ignores_private_tasks() {
        let temp_dir = TempDir::new().unwrap();
        // Add a marker to force regex parsing for this test
        let content = r#"
# TEST_FORCE_REGEX_PARSING
build:
    @echo "Building the project"
    cargo build

# Private helper task
_helper:
    @echo "Helper task"
    rm -rf tmp
"#;
        let makefile_path = create_test_makefile(temp_dir.path(), content);

        let tasks = parse(&makefile_path).unwrap();

        // Verify tasks were found and private task was filtered
        assert_eq!(tasks.len(), 1, "Expected 1 task, got: {}", tasks.len());

        // Verify we have 'build' but not '_helper'
        let task = &tasks[0];
        assert_eq!(task.name, "build");
    }
}