summaryrefslogtreecommitdiff
path: root/internal/showcase/images.go
blob: b6fe6d72148262ad246be728f6c010539ab5bc28 (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
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
package showcase

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
)

// extractImagesFromRepo extracts up to 2 images from README.md and copies them to showcase directory
func extractImagesFromRepo(repoPath, repoName, showcaseDir string) ([]string, error) {
	// Look for README files
	readmeFiles := []string{"README.md", "readme.md", "Readme.md", "README.MD"}
	var readmePath string

	for _, filename := range readmeFiles {
		path := filepath.Join(repoPath, filename)
		if _, err := os.Stat(path); err == nil {
			readmePath = path
			break
		}
	}

	if readmePath == "" {
		return nil, nil // No README found, not an error
	}

	// Read README content
	content, err := os.ReadFile(readmePath)
	if err != nil {
		return nil, fmt.Errorf("failed to read README: %w", err)
	}

	fmt.Printf("Found README at: %s\n", readmePath)

	// Extract image references
	images := extractImageReferences(string(content))
	fmt.Printf("Found %d images in README\n", len(images))
	for i, img := range images {
		fmt.Printf("  Image %d: %s\n", i+1, img)
	}

	if len(images) == 0 {
		return nil, nil
	}

	// Limit to first and last image (max 2)
	var selectedImages []string
	if len(images) == 1 {
		selectedImages = images
	} else {
		selectedImages = []string{images[0], images[len(images)-1]}
	}

	// Create showcase subdirectory for this repo
	repoShowcaseDir := filepath.Join(showcaseDir, "showcase", repoName)
	if err := os.MkdirAll(repoShowcaseDir, 0755); err != nil {
		return nil, fmt.Errorf("failed to create showcase directory: %w", err)
	}

	// Copy images and collect relative paths
	var copiedImages []string
	for i, imgPath := range selectedImages {
		var destFilename string
		var err error

		if strings.HasPrefix(imgPath, "http://") || strings.HasPrefix(imgPath, "https://") {
			// Handle URL - download the image
			// Extract extension from URL, handling query parameters
			urlParts := strings.Split(imgPath, "?")
			basePath := urlParts[0]
			ext := filepath.Ext(basePath)
			if ext == "" || len(ext) > 5 { // Likely not a real extension
				ext = ".png" // Default extension
			}
			destFilename = fmt.Sprintf("image-%d%s", i+1, ext)
			destPath := filepath.Join(repoShowcaseDir, destFilename)

			if err = downloadImage(imgPath, destPath); err != nil {
				fmt.Printf("Warning: Failed to download image %s: %v\n", imgPath, err)
				continue
			}
		} else {
			// Handle local file
			srcPath := imgPath
			if !filepath.IsAbs(imgPath) {
				srcPath = filepath.Join(repoPath, imgPath)
			}

			// Check if image exists
			if _, err := os.Stat(srcPath); err != nil {
				fmt.Printf("Warning: Image not found: %s\n", srcPath)
				continue
			}

			// Generate destination filename
			ext := filepath.Ext(srcPath)
			destFilename = fmt.Sprintf("image-%d%s", i+1, ext)
			destPath := filepath.Join(repoShowcaseDir, destFilename)

			// Copy image
			if err := copyFile(srcPath, destPath); err != nil {
				fmt.Printf("Warning: Failed to copy image %s: %v\n", srcPath, err)
				continue
			}
		}

		// Store relative path from showcase directory
		relativePath := filepath.Join("showcase", repoName, destFilename)
		copiedImages = append(copiedImages, relativePath)
		fmt.Printf("Copied/Downloaded image: %s -> %s\n", imgPath, relativePath)
	}

	return copiedImages, nil
}

// extractImageReferences extracts image references from markdown content
func extractImageReferences(content string) []string {
	var images []string
	seen := make(map[string]bool)

	// Regex patterns for markdown images
	patterns := []string{
		`!\[([^\]]*)\]\(([^)]+)\)`,                 // ![alt](url)
		`<img[^>]+src=["']([^"']+)["'][^>]*>`,      // <img src="url"> with quotes
		`<img[^>]+src=([^\s>]+)[^>]*>`,             // <img src=url> without quotes
		`!\[([^\]]*)\]\[([^\]]+)\]`,                // ![alt][ref]
		`\[([^\]]+)\]:\s*(.+?)(?:\s+"[^"]+")?\s*$`, // [ref]: url "title"
	}

	fmt.Printf("DEBUG: Content length: %d bytes\n", len(content))

	// Extract from markdown image syntax
	for i, pattern := range patterns[:3] { // First three patterns have URLs in different positions
		re := regexp.MustCompile(pattern)
		matches := re.FindAllStringSubmatch(content, -1)
		fmt.Printf("DEBUG: Pattern %d (%s) found %d matches\n", i, pattern, len(matches))

		for _, match := range matches {
			var url string
			if pattern == patterns[0] {
				url = match[2] // For ![alt](url)
			} else {
				url = match[1] // For <img src="url"> (both with and without quotes)
			}

			// Clean and validate URL
			url = strings.TrimSpace(url)

			// Handle markdown image titles - remove anything after a space or quote
			if idx := strings.IndexAny(url, " \"'"); idx != -1 {
				url = url[:idx]
			}
			url = strings.TrimSpace(url)

			fmt.Printf("DEBUG: Found potential image URL: %s\n", url)

			if isImageFile(url) {
				fmt.Printf("DEBUG: URL is image file\n")
				if !seen[url] {
					// Handle different types of URLs
					if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
						// Local file
						fmt.Printf("DEBUG: Adding local image: %s\n", url)
						images = append(images, url)
						seen[url] = true
					} else if isGitHostedImage(url) {
						// GitHub/Codeberg hosted images - we can download these
						fmt.Printf("DEBUG: Found git-hosted image: %s\n", url)
						images = append(images, url)
						seen[url] = true
					} else {
						fmt.Printf("DEBUG: Skipping external URL: %s\n", url)
					}
				}
			} else {
				fmt.Printf("DEBUG: Not recognized as image file: %s\n", url)
			}
		}
	}

	// Handle reference-style images
	refPattern := regexp.MustCompile(patterns[4])
	refMatches := refPattern.FindAllStringSubmatch(content, -1)
	refs := make(map[string]string)
	for _, match := range refMatches {
		refs[match[1]] = strings.TrimSpace(match[2])
	}

	// Find reference-style image uses
	refUsePattern := regexp.MustCompile(patterns[3])
	refUseMatches := refUsePattern.FindAllStringSubmatch(content, -1)
	for _, match := range refUseMatches {
		ref := match[2]
		if url, ok := refs[ref]; ok && isImageFile(url) && !seen[url] {
			if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
				images = append(images, url)
				seen[url] = true
			}
		}
	}

	return images
}

// isImageFile checks if a URL points to an image file
func isImageFile(url string) bool {
	url = strings.ToLower(url)
	extensions := []string{".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".ico"}
	for _, ext := range extensions {
		if strings.HasSuffix(url, ext) {
			return true
		}
	}
	return false
}

// isGitHostedImage checks if URL is from GitHub/Codeberg
func isGitHostedImage(url string) bool {
	return strings.Contains(url, "github.com") ||
		strings.Contains(url, "githubusercontent.com") ||
		strings.Contains(url, "codeberg.org") ||
		strings.Contains(url, "codeberg.page")
}

// copyFile copies a file from src to dst
func copyFile(src, dst string) error {
	sourceFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sourceFile.Close()

	destFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, sourceFile)
	if err != nil {
		return err
	}

	return destFile.Sync()
}

// downloadImage downloads an image from URL to dst
func downloadImage(url, dst string) error {
	// Use curl to download the image
	cmd := exec.Command("curl", "-L", "-o", dst, url)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("curl failed: %v, output: %s", err, string(output))
	}

	// Verify the file was created
	if _, err := os.Stat(dst); err != nil {
		return fmt.Errorf("downloaded file not found: %v", err)
	}

	return nil
}