| 83 | } |
| 84 | |
| 85 | func initProjectConfig(root string) (configInitResult, error) { |
| 86 | cfgPath := config.ConfigPath(root) |
| 87 | result := configInitResult{Path: cfgPath} |
| 88 | |
| 89 | if _, err := os.Stat(cfgPath); err == nil { |
| 90 | return result, errConfigExists |
| 91 | } else if err != nil && !os.IsNotExist(err) { |
| 92 | return result, err |
| 93 | } |
| 94 | |
| 95 | gitCache := scanner.NewGitIgnoreCache(root) |
| 96 | files, err := scanner.ScanFiles(root, gitCache, nil, nil) |
| 97 | if err != nil { |
| 98 | return result, fmt.Errorf("scan files: %w", err) |
| 99 | } |
| 100 | |
| 101 | extCount := make(map[string]int) |
| 102 | for _, f := range files { |
| 103 | ext := strings.TrimPrefix(strings.ToLower(f.Ext), ".") |
| 104 | if ext == "" || nonCodeExtensions[ext] { |
| 105 | continue |
| 106 | } |
| 107 | extCount[ext]++ |
| 108 | } |
| 109 | |
| 110 | type extEntry struct { |
| 111 | Ext string |
| 112 | Count int |
| 113 | } |
| 114 | var entries []extEntry |
| 115 | for ext, count := range extCount { |
| 116 | entries = append(entries, extEntry{Ext: ext, Count: count}) |
| 117 | } |
| 118 | sort.Slice(entries, func(i, j int) bool { |
| 119 | return entries[i].Count > entries[j].Count |
| 120 | }) |
| 121 | |
| 122 | for i, e := range entries { |
| 123 | if i >= 5 { |
| 124 | break |
| 125 | } |
| 126 | result.TopExts = append(result.TopExts, e.Ext) |
| 127 | } |
| 128 | |
| 129 | cfg := config.ProjectConfig{Only: result.TopExts} |
| 130 | |
| 131 | if err := os.MkdirAll(filepath.Dir(cfgPath), 0755); err != nil { |
| 132 | return result, fmt.Errorf("create .codemap directory: %w", err) |
| 133 | } |
| 134 | |
| 135 | data, err := json.MarshalIndent(cfg, "", " ") |
| 136 | if err != nil { |
| 137 | return result, fmt.Errorf("encode config: %w", err) |
| 138 | } |
| 139 | data = append(data, '\n') |
| 140 | |
| 141 | if err := os.WriteFile(cfgPath, data, 0644); err != nil { |
| 142 | return result, fmt.Errorf("write config: %w", err) |