flatten scrape config to 'sites:'. Update unit tests and readme.

This commit is contained in:
Arik Jones
2024-10-12 13:47:21 -05:00
parent 333b9a366c
commit da92da21dc
8 changed files with 245 additions and 157 deletions

View File

@@ -15,7 +15,7 @@ Rollup aggregates the contents of text-based files and webpages into a markdown
- Flexible configuration file support (YAML) - Flexible configuration file support (YAML)
- Automatic generation of default configuration file - Automatic generation of default configuration file
- Custom output file naming - Custom output file naming
- Concurrent processing for improved performance - Rate limiting for web scraping to respect server resources
## Installation ## Installation
@@ -66,16 +66,15 @@ Rollup can be configured using a YAML file. By default, it looks for `rollup.yml
Example `rollup.yml`: Example `rollup.yml`:
```yaml ```yaml
file_types: file_extensions:
- go - go
- md - md
ignore: ignore_paths:
- node_modules/** - node_modules/**
- vendor/** - vendor/**
- .git/** - .git/**
code_generated: code_generated_paths:
- **/generated/** - **/generated/**
scrape:
sites: sites:
- base_url: https://example.com - base_url: https://example.com
css_locator: .content css_locator: .content
@@ -107,10 +106,10 @@ scrape:
rollup files rollup files
``` ```
2. Web scraping with multiple URLs and increased concurrency: 2. Web scraping with multiple URLs:
```bash ```bash
rollup web --urls=https://example.com,https://another-example.com --concurrent=8 rollup web --urls=https://example.com,https://another-example.com
``` ```
3. Generate a default configuration file: 3. Generate a default configuration file:
@@ -119,20 +118,22 @@ scrape:
rollup generate rollup generate
``` ```
4. Use a custom configuration file and specify output: 4. Use a custom configuration file:
```bash ```bash
rollup files --config=my-config.yml --output=project_summary.md rollup files --config=my-config.yml
``` ```
5. Web scraping with separate output files and custom timeout: 5. Web scraping with separate output files:
```bash ```bash
rollup web --urls=https://example.com,https://another-example.com --output=separate --timeout=60 rollup web --urls=https://example.com,https://another-example.com --output=separate
``` ```
6. Rollup files with specific types and ignore patterns: 6. Rollup files with specific types and ignore patterns:
```bash ```bash
rollup files --types=.go,.md --ignore=vendor/**,*_test.go rollup files --types=go,md --ignore=vendor/**,*_test.go
``` ```
7. Web scraping with depth and CSS selector: 7. Web scraping with depth and CSS selector:

View File

@@ -108,19 +108,20 @@ func isIgnored(filePath string, patterns []string) bool {
func runRollup(cfg *config.Config) error { func runRollup(cfg *config.Config) error {
// Use config if available, otherwise use command-line flags // Use config if available, otherwise use command-line flags
var types, codeGenList, ignoreList []string var types []string
if cfg != nil && len(cfg.FileTypes) > 0 { var codeGenList, ignoreList []string
types = cfg.FileTypes if cfg != nil && len(cfg.FileExtensions) > 0 {
types = cfg.FileExtensions
} else { } else {
types = strings.Split(fileTypes, ",") types = strings.Split(fileTypes, ",")
} }
if cfg != nil && len(cfg.CodeGenerated) > 0 { if cfg != nil && len(cfg.CodeGeneratedPaths) > 0 {
codeGenList = cfg.CodeGenerated codeGenList = cfg.CodeGeneratedPaths
} else { } else {
codeGenList = strings.Split(codeGenPatterns, ",") codeGenList = strings.Split(codeGenPatterns, ",")
} }
if cfg != nil && cfg.Ignore != nil && len(cfg.Ignore) > 0 { if cfg != nil && len(cfg.IgnorePaths) > 0 {
ignoreList = cfg.Ignore ignoreList = cfg.IgnorePaths
} else { } else {
ignoreList = strings.Split(ignorePatterns, ",") ignoreList = strings.Split(ignorePatterns, ",")
} }

View File

@@ -112,9 +112,9 @@ func TestRunRollup(t *testing.T) {
// Set up test configuration // Set up test configuration
cfg = &config.Config{ cfg = &config.Config{
FileTypes: []string{"go", "txt", "md"}, FileExtensions: []string{"go", "txt", "md"},
Ignore: []string{"*.json", ".git/**", "vendor/**"}, IgnorePaths: []string{"*.json", ".git/**", "vendor/**"},
CodeGenerated: []string{"generated_*.go"}, CodeGeneratedPaths: []string{"generated_*.go"},
} }
// Change working directory to the temp directory // Change working directory to the temp directory

View File

@@ -38,23 +38,23 @@ func runGenerate(cmd *cobra.Command, args []string) error {
} }
cfg := config.Config{ cfg := config.Config{
FileTypes: make([]string, 0, len(fileTypes)), FileExtensions: make([]string, 0, len(fileTypes)),
Ignore: []string{"node_modules/**", "vendor/**", ".git/**"}, IgnorePaths: []string{"node_modules/**", "vendor/**", ".git/**"},
} }
for ext := range fileTypes { for ext := range fileTypes {
cfg.FileTypes = append(cfg.FileTypes, ext) cfg.FileExtensions = append(cfg.FileExtensions, ext)
} }
// Sort file types for consistency // Sort file types for consistency
sort.Strings(cfg.FileTypes) sort.Strings(cfg.FileExtensions)
yamlData, err := yaml.Marshal(&cfg) yamlData, err := yaml.Marshal(&cfg)
if err != nil { if err != nil {
return fmt.Errorf("error marshaling config: %v", err) return fmt.Errorf("error marshaling config: %v", err)
} }
outputPath := config.DefaultConfigPath() outputPath := "rollup.yml"
err = os.WriteFile(outputPath, yamlData, 0644) err = os.WriteFile(outputPath, yamlData, 0644)
if err != nil { if err != nil {
return fmt.Errorf("error writing config file: %v", err) return fmt.Errorf("error writing config file: %v", err)

View File

@@ -50,10 +50,10 @@ func runWeb(cmd *cobra.Command, args []string) error {
scraperConfig.Verbose = verbose scraperConfig.Verbose = verbose
var siteConfigs []scraper.SiteConfig var siteConfigs []scraper.SiteConfig
if len(cfg.Scrape.Sites) > 0 { if len(cfg.Sites) > 0 {
logger.Printf("Using configuration from rollup.yml for %d sites", len(cfg.Scrape.Sites)) logger.Printf("Using configuration from rollup.yml for %d sites", len(cfg.Sites))
siteConfigs = make([]scraper.SiteConfig, len(cfg.Scrape.Sites)) siteConfigs = make([]scraper.SiteConfig, len(cfg.Sites))
for i, site := range cfg.Scrape.Sites { for i, site := range cfg.Sites {
siteConfigs[i] = scraper.SiteConfig{ siteConfigs[i] = scraper.SiteConfig{
BaseURL: site.BaseURL, BaseURL: site.BaseURL,
CSSLocator: site.CSSLocator, CSSLocator: site.CSSLocator,
@@ -92,13 +92,13 @@ func runWeb(cmd *cobra.Command, args []string) error {
defaultBurstLimit := 3 defaultBurstLimit := 3
// Use default values if not set in the configuration // Use default values if not set in the configuration
requestsPerSecond := cfg.Scrape.RequestsPerSecond requestsPerSecond := defaultRequestsPerSecond
if requestsPerSecond == 0 { if cfg.RequestsPerSecond != nil {
requestsPerSecond = defaultRequestsPerSecond requestsPerSecond = *cfg.RequestsPerSecond
} }
burstLimit := cfg.Scrape.BurstLimit burstLimit := defaultBurstLimit
if burstLimit == 0 { if cfg.BurstLimit != nil {
burstLimit = defaultBurstLimit burstLimit = *cfg.BurstLimit
} }
scraperConfig := scraper.Config{ scraperConfig := scraper.Config{

View File

@@ -8,33 +8,62 @@ import (
) )
type Config struct { type Config struct {
FileTypes []string `yaml:"file_types"` // FileExtensions is a list of file extensions to include in the rollup
Ignore []string `yaml:"ignore"` FileExtensions []string `yaml:"file_extensions"`
CodeGenerated []string `yaml:"code_generated"`
Scrape ScrapeConfig `yaml:"scrape"`
}
type ScrapeConfig struct { // IgnorePaths is a list of glob patterns for paths to ignore
IgnorePaths []string `yaml:"ignore_paths"`
// CodeGeneratedPaths is a list of glob patterns for code-generated files
CodeGeneratedPaths []string `yaml:"code_generated_paths"`
// Sites is a list of site configurations for web scraping
Sites []SiteConfig `yaml:"sites"` Sites []SiteConfig `yaml:"sites"`
// OutputType specifies how the output should be generated
OutputType string `yaml:"output_type"` OutputType string `yaml:"output_type"`
RequestsPerSecond float64 `yaml:"requests_per_second"`
BurstLimit int `yaml:"burst_limit"` // RequestsPerSecond limits the rate of web requests
RequestsPerSecond *float64 `yaml:"requests_per_second,omitempty"`
// BurstLimit sets the maximum burst size for rate limiting
BurstLimit *int `yaml:"burst_limit,omitempty"`
} }
type SiteConfig struct { type SiteConfig struct {
// BaseURL is the starting point for scraping this site
BaseURL string `yaml:"base_url"` BaseURL string `yaml:"base_url"`
// CSSLocator is used to extract specific content
CSSLocator string `yaml:"css_locator"` CSSLocator string `yaml:"css_locator"`
// ExcludeSelectors lists CSS selectors for content to exclude
ExcludeSelectors []string `yaml:"exclude_selectors"` ExcludeSelectors []string `yaml:"exclude_selectors"`
// MaxDepth sets the maximum depth for link traversal
MaxDepth int `yaml:"max_depth"` MaxDepth int `yaml:"max_depth"`
// AllowedPaths lists paths that are allowed to be scraped
AllowedPaths []string `yaml:"allowed_paths"` AllowedPaths []string `yaml:"allowed_paths"`
// ExcludePaths lists paths that should not be scraped
ExcludePaths []string `yaml:"exclude_paths"` ExcludePaths []string `yaml:"exclude_paths"`
// OutputAlias provides an alternative name for output files
OutputAlias string `yaml:"output_alias"` OutputAlias string `yaml:"output_alias"`
// PathOverrides allows for path-specific configurations
PathOverrides []PathOverride `yaml:"path_overrides"` PathOverrides []PathOverride `yaml:"path_overrides"`
} }
type PathOverride struct { type PathOverride struct {
// Path is the URL path this override applies to
Path string `yaml:"path"` Path string `yaml:"path"`
// CSSLocator overrides the site-wide CSS locator for this path
CSSLocator string `yaml:"css_locator"` CSSLocator string `yaml:"css_locator"`
// ExcludeSelectors overrides the site-wide exclude selectors for this path
ExcludeSelectors []string `yaml:"exclude_selectors"` ExcludeSelectors []string `yaml:"exclude_selectors"`
} }
@@ -50,15 +79,34 @@ func Load(configPath string) (*Config, error) {
return nil, fmt.Errorf("error parsing config file: %v", err) return nil, fmt.Errorf("error parsing config file: %v", err)
} }
if err := config.Validate(); err != nil {
return nil, fmt.Errorf("invalid configuration: %v", err)
}
return &config, nil return &config, nil
} }
func DefaultConfigPath() string { func (c *Config) Validate() error {
return "rollup.yml" if len(c.FileExtensions) == 0 {
return fmt.Errorf("at least one file extension must be specified")
} }
func FileExists(filename string) bool { if c.RequestsPerSecond != nil && *c.RequestsPerSecond <= 0 {
_, err := os.Stat(filename) return fmt.Errorf("requests_per_second must be positive")
return err == nil
} }
if c.BurstLimit != nil && *c.BurstLimit <= 0 {
return fmt.Errorf("burst_limit must be positive")
}
for _, site := range c.Sites {
if site.BaseURL == "" {
return fmt.Errorf("base_url must be specified for each site")
}
if site.MaxDepth < 0 {
return fmt.Errorf("max_depth must be non-negative")
}
}
return nil
}

View File

@@ -9,15 +9,14 @@ import (
func TestLoad(t *testing.T) { func TestLoad(t *testing.T) {
// Create a temporary config file // Create a temporary config file
content := []byte(` content := []byte(`
file_types: file_extensions:
- go - .go
- md - .md
ignore: ignore_paths:
- "*.tmp" - "*.tmp"
- "**/*.log" - "**/*.log"
code_generated: code_generated_paths:
- "generated_*.go" - "generated_*.go"
scrape:
sites: sites:
- base_url: "https://example.com" - base_url: "https://example.com"
css_locator: "main" css_locator: "main"
@@ -59,11 +58,12 @@ scrape:
} }
// Check if the loaded config matches the expected values // Check if the loaded config matches the expected values
rps := 1.0
bl := 5
expectedConfig := &Config{ expectedConfig := &Config{
FileTypes: []string{"go", "md"}, FileExtensions: []string{".go", ".md"},
Ignore: []string{"*.tmp", "**/*.log"}, IgnorePaths: []string{"*.tmp", "**/*.log"},
CodeGenerated: []string{"generated_*.go"}, CodeGeneratedPaths: []string{"generated_*.go"},
Scrape: ScrapeConfig{
Sites: []SiteConfig{ Sites: []SiteConfig{
{ {
BaseURL: "https://example.com", BaseURL: "https://example.com",
@@ -83,9 +83,8 @@ scrape:
}, },
}, },
OutputType: "single", OutputType: "single",
RequestsPerSecond: 1.0, RequestsPerSecond: &rps,
BurstLimit: 5, BurstLimit: &bl,
},
} }
if !reflect.DeepEqual(config, expectedConfig) { if !reflect.DeepEqual(config, expectedConfig) {
@@ -93,28 +92,67 @@ scrape:
} }
} }
func TestDefaultConfigPath(t *testing.T) { func TestValidate(t *testing.T) {
expected := "rollup.yml" tests := []struct {
result := DefaultConfigPath() name string
if result != expected { config Config
t.Errorf("DefaultConfigPath() = %q, want %q", result, expected) wantErr bool
} }{
{
name: "Valid config",
config: Config{
FileExtensions: []string{".go"},
Sites: []SiteConfig{
{BaseURL: "https://example.com", MaxDepth: 2},
},
},
wantErr: false,
},
{
name: "No file extensions",
config: Config{},
wantErr: true,
},
{
name: "Invalid requests per second",
config: Config{
FileExtensions: []string{".go"},
RequestsPerSecond: func() *float64 { f := -1.0; return &f }(),
},
wantErr: true,
},
{
name: "Invalid burst limit",
config: Config{
FileExtensions: []string{".go"},
BurstLimit: func() *int { i := -1; return &i }(),
},
wantErr: true,
},
{
name: "Site without base URL",
config: Config{
FileExtensions: []string{".go"},
Sites: []SiteConfig{{}},
},
wantErr: true,
},
{
name: "Negative max depth",
config: Config{
FileExtensions: []string{".go"},
Sites: []SiteConfig{{BaseURL: "https://example.com", MaxDepth: -1}},
},
wantErr: true,
},
} }
func TestFileExists(t *testing.T) { for _, tt := range tests {
// Test with an existing file t.Run(tt.name, func(t *testing.T) {
tmpfile, err := os.CreateTemp("", "testfile") err := tt.config.Validate()
if err != nil { if (err != nil) != tt.wantErr {
t.Fatalf("Failed to create temp file: %v", err) t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr)
} }
defer os.Remove(tmpfile.Name()) })
if !FileExists(tmpfile.Name()) {
t.Errorf("FileExists(%q) = false, want true", tmpfile.Name())
}
// Test with a non-existing file
if FileExists("non_existing_file.txt") {
t.Errorf("FileExists(\"non_existing_file.txt\") = true, want false")
} }
} }

View File

@@ -20,7 +20,7 @@ func main() {
var err error var err error
if !isHelpCommand { if !isHelpCommand {
configPath := config.DefaultConfigPath() configPath := "rollup.yml"
cfg, err = config.Load(configPath) cfg, err = config.Load(configPath)
if err != nil { if err != nil {
log.Printf("Warning: Failed to load configuration: %v", err) log.Printf("Warning: Failed to load configuration: %v", err)