|
| 1 | +// Copyright 2018 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package internal |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "os" |
| 11 | + "path/filepath" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "golang.org/x/mod/sumdb/dirhash" |
| 15 | +) |
| 16 | + |
| 17 | +// Slightly modified copy of [dirhash.HashDir]. |
| 18 | +// https://github.com/golang/mod/blob/v0.28.0/sumdb/dirhash/hash.go#L67-L79 |
| 19 | +func hashDir(dir, prefix string, hash dirhash.Hash) (string, error) { |
| 20 | + files, err := dirFiles(dir, prefix) |
| 21 | + if err != nil { |
| 22 | + return "", err |
| 23 | + } |
| 24 | + |
| 25 | + osOpen := func(name string) (io.ReadCloser, error) { |
| 26 | + return os.Open(filepath.Join(dir, strings.TrimPrefix(name, prefix))) |
| 27 | + } |
| 28 | + |
| 29 | + return hash(files, osOpen) |
| 30 | +} |
| 31 | + |
| 32 | +// Modified copy of [dirhash.DirFiles]. |
| 33 | +// https://github.com/golang/mod/blob/v0.28.0/sumdb/dirhash/hash.go#L81-L109 |
| 34 | +// And adapted to globally follows the rules from https://github.com/golang/mod/blob/v0.28.0/zip/zip.go |
| 35 | +func dirFiles(dir, prefix string) ([]string, error) { |
| 36 | + var files []string |
| 37 | + |
| 38 | + dir = filepath.Clean(dir) |
| 39 | + |
| 40 | + err := filepath.Walk(dir, func(file string, info os.FileInfo, err error) error { |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + |
| 45 | + if info.IsDir() { |
| 46 | + if dir == file { |
| 47 | + // Don't skip the top-level directory. |
| 48 | + return nil |
| 49 | + } |
| 50 | + |
| 51 | + switch info.Name() { |
| 52 | + // Skip vendor and node directories. |
| 53 | + case "vendor", "node_modules": |
| 54 | + return filepath.SkipDir |
| 55 | + |
| 56 | + // Skip VCS directories. |
| 57 | + case ".bzr", ".git", ".hg", ".svn": |
| 58 | + return filepath.SkipDir |
| 59 | + } |
| 60 | + |
| 61 | + // Skip submodules (directories containing go.mod files). |
| 62 | + if goModInfo, err := os.Lstat(filepath.Join(dir, "go.mod")); err == nil && !goModInfo.IsDir() { |
| 63 | + return filepath.SkipDir |
| 64 | + } |
| 65 | + |
| 66 | + return nil |
| 67 | + } |
| 68 | + |
| 69 | + if file == dir { |
| 70 | + return fmt.Errorf("%s is not a directory", dir) |
| 71 | + } |
| 72 | + |
| 73 | + if !info.Mode().IsRegular() { |
| 74 | + return nil |
| 75 | + } |
| 76 | + |
| 77 | + rel := file |
| 78 | + |
| 79 | + if dir != "." { |
| 80 | + rel = file[len(dir)+1:] |
| 81 | + } |
| 82 | + |
| 83 | + f := filepath.Join(prefix, rel) |
| 84 | + |
| 85 | + files = append(files, filepath.ToSlash(f)) |
| 86 | + |
| 87 | + return nil |
| 88 | + }) |
| 89 | + if err != nil { |
| 90 | + return nil, err |
| 91 | + } |
| 92 | + return files, nil |
| 93 | +} |
0 commit comments