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
|
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
// Site describes a single documentation site to mirror.
type Site struct {
// Name is a short identifier used as a subdirectory name under OutputDir.
Name string `json:"name"`
// URL is the root URL to start mirroring from.
URL string `json:"url"`
// IncludeDirs restricts wget to only follow links within these URL path
// prefixes (passed as --include-directories). If empty, no restriction.
IncludeDirs []string `json:"includeDirs,omitempty"`
// ExcludeDirs are URL path prefixes that wget should not descend into
// (passed as --exclude-directories).
ExcludeDirs []string `json:"excludeDirs,omitempty"`
// Level sets the maximum recursion depth (default: infinite via --mirror).
// 0 means use wget's default (infinite when mirroring).
Level int `json:"level,omitempty"`
// WaitSeconds is the delay between requests in seconds (default: 1).
WaitSeconds float64 `json:"waitSeconds,omitempty"`
// ExtraArgs are passed verbatim to wget after all computed arguments.
ExtraArgs []string `json:"extraArgs,omitempty"`
}
// Config is the top-level structure of sites.json.
type Config struct {
// OutputDir is the base directory for all mirrored sites.
// wget will create hostname/ subdirectories inside it automatically.
// Supports ~ expansion.
OutputDir string `json:"outputDir"`
Sites []Site `json:"sites"`
}
func expandHome(path string) string {
if strings.HasPrefix(path, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return path
}
return filepath.Join(home, path[2:])
}
return path
}
func buildWgetArgs(site Site, outputDir string) []string {
args := []string{
// --mirror = -r -N -l inf
// -N: timestamping (If-Modified-Since on re-runs)
// -r: recursive
// -l inf: infinite depth (overridden by --level if set)
"--mirror",
// Rewrite links so the archive is self-contained locally.
"--convert-links",
// Download CSS, JS, images needed to render each page.
"--page-requisites",
// Save HTML/CSS with proper extensions (avoids bare directories
// with no index.html on some sites).
"--adjust-extension",
// Don't follow links to parent of the start URL.
"--no-parent",
// Respect HTTP cache headers (ETag, Cache-Control etc.).
"--cache",
// Identify ourselves honestly.
"--user-agent=docmirror/1.0 (offline documentation archiver; +https://codeberg.org/Profpatsch)",
// Store everything under outputDir; wget2 creates hostname/ inside automatically.
"--directory-prefix=" + outputDir,
}
if site.WaitSeconds > 0 {
args = append(args, fmt.Sprintf("--wait=%.1f", site.WaitSeconds), "--random-wait")
}
if site.Level > 0 {
args = append(args, fmt.Sprintf("--level=%d", site.Level))
}
if len(site.IncludeDirs) > 0 {
args = append(args, "--include-directories="+strings.Join(site.IncludeDirs, ","))
}
if len(site.ExcludeDirs) > 0 {
args = append(args, "--exclude-directories="+strings.Join(site.ExcludeDirs, ","))
}
args = append(args, site.ExtraArgs...)
args = append(args, site.URL)
return args
}
func mirrorSite(site Site, outputDir string, dryRun bool) error {
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return fmt.Errorf("creating output dir %s: %w", outputDir, err)
}
args := buildWgetArgs(site, outputDir)
fmt.Printf("==> mirroring %s (%s)\n", site.Name, site.URL)
if dryRun {
fmt.Printf(" [dry-run] wget %s\n\n", strings.Join(args, " "))
return nil
}
logPath := filepath.Join(outputDir, site.Name+".wget.log")
fmt.Printf(" log: %s\n", logPath)
// -q suppresses progress; --output-file captures wget's log output.
// These must come before the URL argument (already the case — extraArgs + URL are last).
args = append([]string{"-q", "--output-file=" + logPath}, args...)
cmd := exec.Command("wget", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("wget failed for %s (see %s): %w", site.Name, logPath, err)
}
fmt.Printf("==> done %s\n\n", site.Name)
return nil
}
func main() {
configPath := flag.String("config", "sites.json", "path to sites.json config file")
outputDir := flag.String("output", "", "override outputDir from config")
dryRun := flag.Bool("dry-run", false, "print wget commands without running them")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: docmirror [flags] [site-name...]\n\n")
fmt.Fprintf(os.Stderr, "Mirror documentation sites defined in a JSON config.\n")
fmt.Fprintf(os.Stderr, "If site names are given, only those sites are mirrored.\n\n")
flag.PrintDefaults()
}
flag.Parse()
filter := flag.Args() // optional site name filter
data, err := os.ReadFile(*configPath)
if err != nil {
log.Fatalf("reading config %s: %v", *configPath, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
log.Fatalf("parsing config: %v", err)
}
baseOut := cfg.OutputDir
if *outputDir != "" {
baseOut = *outputDir
}
baseOut = expandHome(baseOut)
if baseOut == "" {
log.Fatal("outputDir must be set in config or via --output flag")
}
// Build a set from the filter list for O(1) lookup.
filterSet := make(map[string]bool, len(filter))
for _, name := range filter {
filterSet[name] = true
}
var errors []string
for _, site := range cfg.Sites {
if len(filterSet) > 0 && !filterSet[site.Name] {
continue
}
if err := mirrorSite(site, baseOut, *dryRun); err != nil {
log.Printf("error: %v", err)
errors = append(errors, site.Name)
}
}
if len(errors) > 0 {
log.Fatalf("failed sites: %s", strings.Join(errors, ", "))
}
}
|