1// Copyright © 2016 Couchbase, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// 		http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cmd
16
17import (
18	"encoding/json"
19	"fmt"
20	"io/ioutil"
21	"log"
22	"os"
23	"path/filepath"
24
25	"github.com/spf13/cobra"
26)
27
28var keepDir, keepExt, parseJSON bool
29
30// indexCmd represents the index command
31var indexCmd = &cobra.Command{
32	Use:   "index [index path] [data paths ...]",
33	Short: "adds the files to the index",
34	Long:  `The index command adds the specified files to the index.`,
35	Annotations: map[string]string{
36		canMutateBleveIndex: "true",
37	},
38	RunE: func(cmd *cobra.Command, args []string) error {
39		if len(args) < 2 {
40			return fmt.Errorf("must specify at least one path")
41		}
42		for file := range handleArgs(args[1:]) {
43			var doc interface{}
44			// index the files
45			docID := file.filename
46			if !keepDir {
47				_, docID = filepath.Split(docID)
48			}
49			if !keepExt {
50				ext := filepath.Ext(docID)
51				docID = docID[0 : len(docID)-len(ext)]
52			}
53			doc = file.contents
54			var err error
55			if parseJSON {
56				err = json.Unmarshal(file.contents, &doc)
57				if err != nil {
58					return fmt.Errorf("error parsing JSON: %v", err)
59				}
60			}
61			fmt.Printf("Indexing: %s\n", docID)
62			err = idx.Index(docID, doc)
63			if err != nil {
64				return fmt.Errorf("error indexing: %v", err)
65			}
66		}
67		return nil
68	},
69}
70
71type file struct {
72	filename string
73	contents []byte
74}
75
76func handleArgs(args []string) chan file {
77	rv := make(chan file)
78	go getAllFiles(args, rv)
79	return rv
80}
81
82func getAllFiles(args []string, rv chan file) {
83	for _, arg := range args {
84		arg = filepath.Clean(arg)
85		err := filepath.Walk(arg, func(path string, finfo os.FileInfo, err error) error {
86			if err != nil {
87				log.Print(err)
88				return err
89			}
90			if finfo.IsDir() {
91				return nil
92			}
93
94			bytes, err := ioutil.ReadFile(path)
95			if err != nil {
96				log.Fatal(err)
97			}
98			rv <- file{
99				filename: filepath.Base(path),
100				contents: bytes,
101			}
102			return nil
103		})
104		if err != nil {
105			log.Fatal(err)
106		}
107	}
108	close(rv)
109}
110
111func init() {
112	RootCmd.AddCommand(indexCmd)
113
114	indexCmd.Flags().BoolVarP(&keepDir, "keepDir", "d", false, "Keep the directory in the document id, defaults false.")
115	indexCmd.Flags().BoolVarP(&keepExt, "keepExt", "x", false, "Keep the extension in the document id, defaults false.")
116	indexCmd.Flags().BoolVarP(&parseJSON, "json", "j", true, "Parse the contents as JSON, defaults true.")
117}
118