Commit 20e1cc33 authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

code comments

parent b648029e
Loading
Loading
Loading
Loading
+6
Changes for archive.go: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -77,6 +77,8 @@ func extractArchive(src, destination string) error {
	return fmt.Errorf(T("err.unsupported_archive"), src)
}

// Archive entries are untrusted paths; keep every resolved target under the
// requested destination even when entries contain "../" segments.
func archiveTarget(destination, entryName string) (string, bool) {
	cleanTarget := filepath.Clean(filepath.Join(destination, entryName))
	cleanDest := filepath.Clean(destination)
@@ -192,6 +194,8 @@ func extractTarGz(src, destination string) error {
	return nil
}

// Some generated archives omit permission bits. Use stable defaults instead of
// creating unreadable files or non-traversable directories.
func effectivePerm(mode os.FileMode, fallback os.FileMode) os.FileMode {
	perm := mode.Perm()
	if perm == 0 {
@@ -200,6 +204,8 @@ func effectivePerm(mode os.FileMode, fallback os.FileMode) os.FileMode {
	return perm
}

// Preserve close errors while still closing the destination when the copy fails;
// this matters for archive extraction where buffered filesystem errors surface late.
func copyAndClose(in io.Reader, out *os.File) error {
	if _, err := io.Copy(out, in); err != nil {
		return errors.Join(err, out.Close())
+6
Changes for commands.go: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -341,6 +341,8 @@ func runFeed(feedPath, directory string, verbose bool, yes bool) error {
	return cmd.Run()
}

// BaseX treats a trailing separator as "load directory contents"; without it,
// a directory feed can be stored under an unexpected path name.
func ensureTrailingPathSeparator(path string) string {
	if strings.HasSuffix(path, string(os.PathSeparator)) {
		return path
@@ -348,6 +350,8 @@ func ensureTrailingPathSeparator(path string) string {
	return path + string(os.PathSeparator)
}

// Verbose mode prints the exact argv passed to Java/BaseX; no shell quoting is
// added because the command is executed without a shell.
func formatCommand(cmd *exec.Cmd) string {
	if cmd == nil || len(cmd.Args) == 0 {
		return ""
@@ -382,6 +386,8 @@ func runBasex(directory string, verbose bool) error {
	return cmd.Run()
}

// Listing commands intentionally output plain relative paths, not tables; tests
// and users rely on piping these paths directly.
func scanDir(startPath, extension string) ([]string, error) {
	var out []string
	err := filepath.WalkDir(startPath, func(p string, d fs.DirEntry, err error) error {
+16
Changes for config.go: 16 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -24,6 +24,8 @@ var (
	releasesErr  error
)

// Missing configs intentionally load the project template; new/init flows edit
// that in-memory default before writing config.xml.
func loadProjectConfig(pathToConfig string) (*projectConfig, error) {
	absPath, err := filepath.Abs(pathToConfig)
	if err != nil {
@@ -119,6 +121,8 @@ func (pc *projectConfig) setMaxVersion(name, url string) {
	pc.Cfg.Version.URL = url
}

// The installed runtime version is read from the copied package metadata, not
// from config.xml, so sync can detect partially updated .max directories.
func (pc *projectConfig) maxVersionFromMaxDir() string {
	expathPkg := filepath.Join(filepath.Dir(pc.Path), ".max", "resources", "expath-pkg.xml")
	if !fileExists(expathPkg) {
@@ -175,6 +179,8 @@ func (pc *projectConfig) availableBundles() (map[string]availableBundle, error)
	return out, nil
}

// Prefer live GitLab metadata when reachable, but keep the CLI usable offline
// through the embedded release snapshot.
func maxReleases() ([]release, error) {
	releasesOnce.Do(func() {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -226,10 +232,14 @@ func maxRelease(name string) (*release, error) {

type maxReleaseLookup func(string) (*release, error)

// Prefer canonical release metadata so stale project configs do not pin downloads
// to a moved GitLab archive. Custom URLs still work for versions unknown to climax.
func maxReleaseZipURL(maxReleaseName, configuredURL string) (string, error) {
	return maxReleaseZipURLWithLookup(maxReleaseName, configuredURL, maxRelease)
}

// Keep lookup injectable so URL selection tests do not mutate the shared release
// cache populated by maxReleases().
func maxReleaseZipURLWithLookup(maxReleaseName, configuredURL string, lookup maxReleaseLookup) (string, error) {
	name := strings.TrimSpace(maxReleaseName)
	if name != "" {
@@ -262,6 +272,8 @@ func latestMaxRelease() (*release, error) {
	return maxRelease(releases[0].Name)
}

// Invalid or pre-semver tags are treated as unsupported rather than newest;
// this keeps fallback snapshots resilient to experimental release names.
func filterSupportedMaxReleases(releases []release) []release {
	filtered := make([]release, 0, len(releases))
	for _, r := range releases {
@@ -276,6 +288,8 @@ func isSupportedMaxVersion(raw string) bool {
	return compareVersion(raw, minSupportedMaxVersion) >= 0
}

// MaX release names are simple semver-like tags; malformed versions sort below
// supported releases so they fail closed.
func compareVersion(left, right string) int {
	lv, okLeft := parseVersion(left)
	rv, okRight := parseVersion(right)
@@ -301,6 +315,8 @@ func compareVersion(left, right string) int {
	return 0
}

// Accept a leading "v" and ignore prerelease/build suffixes, matching the
// release tags already present in the embedded GitLab snapshot.
func parseVersion(raw string) ([]int, bool) {
	trimmed := strings.TrimSpace(raw)
	if trimmed == "" {
+6
Changes for download.go: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -27,6 +27,8 @@ const downloadTLSHandshakeTimeout = 60 * time.Second

var downloadHTTPClient = newDownloadHTTPClient()

// Release archives can be served slowly before bytes start flowing; avoid a
// whole-client timeout so large downloads can finish once the connection opens.
func newDownloadHTTPClient() *http.Client {
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.TLSHandshakeTimeout = downloadTLSHandshakeTimeout
@@ -38,6 +40,8 @@ func sha1Hex(s string) string {
	return hex.EncodeToString(sum[:])
}

// Cache hits stay silent because callers may depend on clean non-interactive
// output; progress is reserved for real network transfers on TTY stderr.
func cachedDownload(source, destination string) error {
	cachePath := filepath.Join(cacheDir, sha1Hex(source))
	if fileExists(cachePath) {
@@ -99,6 +103,8 @@ func newDownloadProgress(label string, totalBytes int64) *downloadProgress {
	}
}

// Allows io.MultiWriter to account for downloaded bytes without buffering any
// response data in memory.
func (p *downloadProgress) Write(b []byte) (int, error) {
	p.written.Add(int64(len(b)))
	return len(b), nil
+16
Changes for freeze.go: 16 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -21,6 +21,8 @@ import (

var cssURLRegexp = regexp.MustCompile(`url\(\s*['"]?([^'")]+)['"]?\s*\)`)

// Freeze runs against an isolated transient server so the crawl observes the
// same BaseX routes as start, without depending on any already running service.
func runFreeze(output, directory string, debug bool) error {
	_ = debug
	if output == "" {
@@ -49,6 +51,8 @@ func runFreeze(output, directory string, debug bool) error {
	return nil
}

// Unlike start, freeze needs the server as a child process so it can always be
// stopped after crawling, even if the crawl itself fails.
func startFreezeServer(httpHost string, httpPort, basexPort, httpStopPort int, directory string) (projectMeta, *exec.Cmd, error) {
	basexPort = closerFreePortTo(basexPort)
	httpPort = closerFreePortTo(httpPort)
@@ -85,6 +89,8 @@ func startFreezeServer(httpHost string, httpPort, basexPort, httpStopPort int, d
	return runtimeMeta, cmd, nil
}

// BaseXHTTP may exit non-zero when interrupted; freeze treats that as shutdown
// bookkeeping and escalates to kill only if the child does not leave promptly.
func stopFreezeServer(cmd *exec.Cmd) error {
	if cmd == nil || cmd.Process == nil {
		return nil
@@ -120,6 +126,8 @@ func waitForPort(host string, port int, timeout time.Duration) error {
	return fmt.Errorf(T("err.server_start_timeout"), host, port)
}

// The crawler is same-host only. It records the first internal processing error
// while still letting Colly finish in-flight visits for deterministic output.
func freezeSite(startURL, output string) error {
	startParsed, err := url.Parse(startURL)
	if err != nil {
@@ -202,6 +210,8 @@ func freezeSite(startURL, output string) error {
	return firstErr
}

// HTML and CSS are rewritten as they are saved so the frozen tree is portable
// and does not point back to the temporary local server.
func saveMirroredResponse(u *url.URL, body []byte, contentType, outputDir string) error {
	localPath, err := mapURLToLocalPath(u, contentType, outputDir)
	if err != nil {
@@ -229,6 +239,8 @@ func saveMirroredResponse(u *url.URL, body []byte, contentType, outputDir string
	return os.WriteFile(localPath, content, 0o644)
}

// Query strings cannot be represented as path separators, so hash them into the
// filename while preserving the extension used by browsers to infer type.
func mapURLToLocalPath(u *url.URL, contentType, outputDir string) (string, error) {
	pathPart := u.EscapedPath()
	if pathPart == "" {
@@ -309,6 +321,8 @@ func rewriteHTMLLinksToRelative(body []byte, currentURL *url.URL, contentType, o
	return []byte(htmlText), nil
}

// This intentionally handles simple url(...) references only; complex CSS
// parsing would be heavier than the static assets MaX bundles currently use.
func rewriteCSSLinksToRelative(body []byte, currentURL *url.URL, contentType, outputDir string) ([]byte, error) {
	cssText := cssURLRegexp.ReplaceAllStringFunc(string(body), func(match string) string {
		sub := cssURLRegexp.FindStringSubmatch(match)
@@ -325,6 +339,8 @@ func rewriteCSSLinksToRelative(body []byte, currentURL *url.URL, contentType, ou
	return []byte(cssText), nil
}

// External links and non-fetching schemes stay untouched; only links that map
// into the mirrored output tree are converted to relative filesystem paths.
func relativeMirroredRef(currentURL *url.URL, currentContentType, rawRef, guessType, outputDir string) (string, error) {
	ref := strings.TrimSpace(rawRef)
	if ref == "" || strings.HasPrefix(ref, "#") {
Loading