tag-find: experiment in rust, go and joker languages
[experiments.git] / tag_find / tag_find_go / main.go
1 package main
2
3 /*
4 Using a tag to test this file itself
5 #+tag
6 */
7
8 import (
9 "bufio"
10 "fmt"
11 "io/ioutil"
12 cobra "github.com/spf13/cobra"
13 "log"
14 "os"
15 "strings"
16 )
17
18 func main() {
19 command := &cobra.Command{
20 Use: "tag-find",
21 Short: "Finds the files tagged with the requested tag",
22 SilenceUsage: true,
23 RunE: func(cmd *cobra.Command, args []string) error {
24 tag := args[1]
25 var dirName string
26 if len(args) == 2 {
27 dirName = "."
28 } else {
29 dirName = args[2]
30 }
31 cmd.Println("Trying to search for tag", tag, "in directory:", dirName)
32 searchTag(tag, dirName)
33 return nil
34 },
35 }
36
37 if err := command.Execute(); err != nil {
38 os.Exit(1)
39 }
40
41 }
42
43 func searchTag(tag string, dirName string) {
44 var containedFiles []string
45 files, err := ioutil.ReadDir(dirName)
46 if err != nil {
47 log.Fatal(err)
48 }
49
50 for _, fileInfo := range files {
51 fileName := fileInfo.Name()
52 file, err := os.Open(fileName)
53 if err != nil {
54 log.Fatal(err)
55 }
56 defer file.Close()
57
58 startSequenceEnv := os.Getenv("TAG_FIND_START_SEQUENCE")
59 var startSequence string
60
61 if len(startSequenceEnv) != 0 {
62 startSequence = startSequenceEnv
63 } else {
64 startSequence = "#"
65 }
66
67 scanner := bufio.NewScanner(file)
68 for scanner.Scan() {
69 if strings.HasPrefix(scanner.Text(), startSequence) && strings.Contains(scanner.Text(), tag) {
70 containedFiles = append(containedFiles, fileName)
71 break
72 }
73 }
74
75 if err := scanner.Err(); err != nil {
76 log.Fatal(err)
77 }
78
79 }
80
81 if len(containedFiles) != 0 {
82 for _, fileName := range containedFiles {
83 fmt.Println(fileName)
84 }
85 }
86 }