<commit_before><commit_msg>archive.ApplyLayer(): parse a tar archive as a standard aufs-compatible diff, and apply it on a directory<commit_after>package archive

import (
	"path/filepath"
	"log"
	"os"
	"strings"
)

// ApplyLayer parses a diff in the standard layer format from `layer`, and
// applies it to the directory `dest`.
func ApplyLayer(dest string, layer Archive) error {
	// Poor man's diff applyer in 2 steps:

	// Step 1: untar everything in place
	if err := Untar(layer, dest); err != nil {
		return err
	}

	// Step 2: walk for whiteouts and apply them, removing them in the process
	err := filepath.Walk(dest, func(fullPath string, f os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// Rebase path
		path, err := filepath.Rel(dest, fullPath)
		if err != nil {
			return err
		}
		path = filepath.Join("/", path)

		// Skip AUFS metadata
		if matched, err := filepath.Match("/.wh..wh.*", path); err != nil {
			return err
		} else if matched {
			log.Printf("Removing aufs metadata %s", fullPath)
			_ = os.Remove(fullPath)
		}

		filename := filepath.Base(path)
		if strings.HasPrefix(filename, ".wh.") {
			rmTargetName := filename[len(".wh."):]
			rmTargetPath := filepath.Join(filepath.Dir(fullPath), rmTargetName)
			// Remove the file targeted by the whiteout
			log.Printf("Removing whiteout target %s", rmTargetPath)
			_ = os.Remove(rmTargetPath)
			// Remove the whiteout itself
			log.Printf("Removing whiteout %s", fullPath)
			_ = os.Remove(fullPath)
		}
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}

{'fraction_non_alphanumeric': 0.12555768005098789, 'fraction_numerical': 0.0019120458891013384, 'mean_word_length': 3.361111111111111, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3166590', 'n_tokens_mistral': 564, 'n_tokens_neox': 512, 'n_words': 170}