A migrations hash is a sha256 hash of the contents and names of the migrations sorted by filename.
(migrationsFs embed.FS)
| 31 | // A migrations hash is a sha256 hash of the contents and names |
| 32 | // of the migrations sorted by filename. |
| 33 | func calculateMigrationsHash(migrationsFs embed.FS) (string, error) { |
| 34 | files, err := migrationsFs.ReadDir(".") |
| 35 | if err != nil { |
| 36 | return "", xerrors.Errorf("read migrations directory: %w", err) |
| 37 | } |
| 38 | sortedFiles := make([]fs.DirEntry, len(files)) |
| 39 | copy(sortedFiles, files) |
| 40 | sort.Slice(sortedFiles, func(i, j int) bool { |
| 41 | return sortedFiles[i].Name() < sortedFiles[j].Name() |
| 42 | }) |
| 43 | |
| 44 | var builder strings.Builder |
| 45 | for _, file := range sortedFiles { |
| 46 | if _, err := builder.WriteString(file.Name()); err != nil { |
| 47 | return "", xerrors.Errorf("write migration file name %q: %w", file.Name(), err) |
| 48 | } |
| 49 | content, err := migrationsFs.ReadFile(file.Name()) |
| 50 | if err != nil { |
| 51 | return "", xerrors.Errorf("read migration file %q: %w", file.Name(), err) |
| 52 | } |
| 53 | if _, err := builder.Write(content); err != nil { |
| 54 | return "", xerrors.Errorf("write migration file content %q: %w", file.Name(), err) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | hash := sha256.New() |
| 59 | if _, err := hash.Write([]byte(builder.String())); err != nil { |
| 60 | return "", xerrors.Errorf("write to hash: %w", err) |
| 61 | } |
| 62 | return fmt.Sprintf("%x", hash.Sum(nil)), nil |
| 63 | } |
| 64 | |
| 65 | func GetMigrationsHash() string { |
| 66 | migrationsHashOnce.Do(func() { |
no test coverage detected