aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/build_rules/go/tools/filter_tags/filter_tags_test.go
blob: 652d3af1d586d0d435243a42bdcdf6fbf061bd2f (plain)
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
package main

import (
	"go/build"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"testing"
)

var testFileCGO = `
// This file is not intended to actually build.

package cgo

/*
#include <stdio.h>
#include <stdlib.h>

void myprint(char* s) {
		printf("%s", s);
}
*/

import "C"

func main() {
	C.myprint("hello")
}
`

var testFileFILENAMETAG = `
// This file is not intended to actually compile.

package filenametag_darwin
`

var testFileIGNORE = `
// This file is not intended to actually build.

//+build ignore

package ignore
`

var testFileTAGS = `
// This file is not intended to actually build.

//+build arm,darwin linux,mips

package tags
`

func TestTags(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "goruletest")
	if err != nil {
		t.Fatalf("Error creating temporary directory: %v", err)
	}
	defer os.RemoveAll(tempdir)

	for k, v := range map[string]string{
		"cgo.go":    testFileCGO,
		"darwin.go": testFileFILENAMETAG,
		"ignore.go": testFileIGNORE,
		"tags.go":   testFileTAGS,
	} {
		p := filepath.Join(tempdir, k)
		if err := ioutil.WriteFile(p, []byte(v), 0644); err != nil {
			t.Fatalf("WriteFile(%s): %v", p, err)
		}
	}

	testContext := build.Default
	wd, err := os.Getwd()
	if err != nil {
		t.Fatalf("Getwd: %v", err)
	}

	err = os.Chdir(tempdir)
	if err != nil {
		t.Fatalf("Chdir(%s): %v", tempdir, err)
	}
	defer os.Chdir(wd)

	// Test tags.go (tags in +build comments)
	testContext.BuildTags = []string{"arm", "darwin"}
	inputs := []string{"tags.go"}
	outputs, err := filterFilenames(testContext, inputs)
	if err != nil {
		t.Errorf("filterFilenames(%s): %v", inputs, err)
	}

	if !reflect.DeepEqual(inputs, outputs) {
		t.Error("Output missing an expected file: tags.go")
	}

	testContext.BuildTags = []string{"arm, linux"}
	outputs, err = filterFilenames(testContext, inputs)
	if err != nil {
		t.Errorf("filterFilenames(%s): %v", inputs, err)
	}

	if !reflect.DeepEqual([]string{}, outputs) {
		t.Error("Output contains an unexpected file: tags.go")
	}

	// Test ignore.go (should not build a file with +ignore comment)
	testContext.BuildTags = []string{}
	inputs = []string{"ignore.go"}
	outputs, err = filterFilenames(testContext, inputs)
	if err != nil {
		t.Errorf("filterFilenames(%s): %v", inputs, err)
	}

	if !reflect.DeepEqual([]string{}, outputs) {
		t.Error("Output contains an unexpected file: ignore.go")
	}
}