598 lines
21 KiB
Go
598 lines
21 KiB
Go
package stage
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/audio"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
|
)
|
|
|
|
type prepareStage struct{}
|
|
|
|
func (prepareStage) Name() string { return "prepare" }
|
|
|
|
func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*StageResult, error) {
|
|
return prepareInputs(ctx, env, m, prepareNeedsAudio(env, m))
|
|
}
|
|
|
|
// PrepareReferences materializes session references and history without acquiring audio.
|
|
func PrepareReferences(ctx context.Context, env *Env, m *manifest.Manifest) (*StageResult, error) {
|
|
return prepareInputs(ctx, env, m, false)
|
|
}
|
|
|
|
func prepareNeedsAudio(env *Env, m *manifest.Manifest) bool {
|
|
if env != nil && env.ReferenceOnly {
|
|
return false
|
|
}
|
|
if env == nil || env.Config == nil || env.Config.Session == nil || env.ArtifactStore == nil || m == nil || env.Force {
|
|
return true
|
|
}
|
|
paths := sessionPathsForEnv(env, m.SessionID)
|
|
return !artifacts.SuppliedTranscriptCoverage(paths, m.SuppliedProducts)["transcribe"]
|
|
}
|
|
|
|
func prepareInputs(ctx context.Context, env *Env, m *manifest.Manifest, acquireAudio bool) (*StageResult, error) {
|
|
if env == nil || env.Config == nil {
|
|
return nil, fmt.Errorf("prepare: stage environment config is required")
|
|
}
|
|
if env.ArtifactStore == nil {
|
|
return nil, fmt.Errorf("prepare: artifact store is required")
|
|
}
|
|
if env.Config.Session == nil || env.Config.Pipeline == nil {
|
|
return nil, fmt.Errorf("prepare: resolved config must include pipeline and session")
|
|
}
|
|
|
|
sessionID := strings.TrimSpace(m.SessionID)
|
|
if sessionID == "" {
|
|
sessionID = strings.TrimSpace(env.Config.Session.SessionID)
|
|
}
|
|
if sessionID == "" {
|
|
return nil, fmt.Errorf("prepare: session id is required")
|
|
}
|
|
|
|
glossaryDocuments, err := config.ResolveGlossaries(env.Config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: resolve glossaries: %w", err)
|
|
}
|
|
|
|
paths, err := ensureLayoutForEnv(env, sessionID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: ensure workdir layout: %w", err)
|
|
}
|
|
|
|
sessionSrc := env.Config.SessionPath
|
|
sessionDir := filepath.Dir(sessionSrc)
|
|
|
|
speakersInput := stableInputSource(env.Config.StableInputs.SpeakersFile, env.Config.Session.Inputs.SpeakersFile, sessionSrc)
|
|
|
|
speakersSrc, err := resolveConfigRelativePath(speakersInput)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: speakers path: %w", err)
|
|
}
|
|
|
|
for _, required := range []struct {
|
|
path string
|
|
name string
|
|
}{
|
|
{path: speakersSrc, name: "speakers.yml"},
|
|
} {
|
|
if err := requireFile(required.path, required.name); err != nil {
|
|
return nil, fmt.Errorf("prepare: %w", err)
|
|
}
|
|
}
|
|
|
|
var resolvedLocalAudio []audio.Source
|
|
var useS3Audio bool
|
|
if acquireAudio {
|
|
resolvedLocalAudio, useS3Audio, err = resolveAudioInputs(sessionDir, env.Config.Session.Inputs)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: resolve audio inputs: %w", err)
|
|
}
|
|
if !useS3Audio && len(resolvedLocalAudio) == 0 {
|
|
return nil, fmt.Errorf("prepare: audio input is required for transcription")
|
|
}
|
|
}
|
|
|
|
inputs := make([]manifest.InputRecord, 0, 9+len(resolvedLocalAudio))
|
|
if !acquireAudio {
|
|
for _, input := range m.Inputs {
|
|
if input.Kind == "audio" {
|
|
inputs = append(inputs, input)
|
|
}
|
|
}
|
|
}
|
|
registerInput := func(kind, path, checksum string) {
|
|
inputs = append(inputs, manifest.InputRecord{Kind: kind, Path: path, Checksum: checksum})
|
|
}
|
|
registerConfigInput := func(kind, path, checksum, source string) {
|
|
inputs = append(inputs, manifest.InputRecord{Kind: kind, Path: path, Checksum: checksum, Source: source})
|
|
}
|
|
registerSessionConfigInput := func(path, checksum string) {
|
|
source := env.Config.SessionSource
|
|
if strings.TrimSpace(source.Source) == "" {
|
|
source.Source = "session_config"
|
|
}
|
|
inputs = append(inputs, manifest.InputRecord{
|
|
Kind: "session_config",
|
|
Path: path,
|
|
Checksum: checksum,
|
|
Source: source.Source,
|
|
S3Bucket: source.S3Bucket,
|
|
S3Key: source.S3Key,
|
|
S3Size: source.S3Size,
|
|
S3ETag: source.S3ETag,
|
|
})
|
|
}
|
|
|
|
campaignDst := filepath.Join(paths.InputsDir, "campaign.yml")
|
|
campaignBytes, err := config.RenderCampaignDocument(env.Config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: render campaign.yml: %w", err)
|
|
}
|
|
campaignChecksum, err := writeBytesIfChanged(env.ArtifactStore, campaignDst, campaignBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize campaign.yml: %w", err)
|
|
}
|
|
registerConfigInput("campaign_config", campaignDst, campaignChecksum, "campaign_config")
|
|
|
|
sessionDst := filepath.Join(paths.InputsDir, "session.yml")
|
|
sessionBytes, err := config.RenderSessionDocument(env.Config, sessionID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: render session.yml: %w", err)
|
|
}
|
|
sessionChecksum, err := writeBytesIfChanged(env.ArtifactStore, sessionDst, sessionBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize session.yml: %w", err)
|
|
}
|
|
registerSessionConfigInput(sessionDst, sessionChecksum)
|
|
|
|
pipelineResolvedBytes, err := renderResolvedPipeline(env.Config.Pipeline)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: render pipeline.resolved.yml: %w", err)
|
|
}
|
|
pipelineDst := filepath.Join(paths.InputsDir, "pipeline.resolved.yml")
|
|
pipelineChecksum, err := writeBytesIfChanged(env.ArtifactStore, pipelineDst, pipelineResolvedBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize pipeline.resolved.yml: %w", err)
|
|
}
|
|
registerInput("pipeline_resolved", pipelineDst, pipelineChecksum)
|
|
|
|
type preparedConfigFile struct {
|
|
kind string
|
|
src string
|
|
dst string
|
|
source string
|
|
}
|
|
preparedConfigFiles := []preparedConfigFile{
|
|
{kind: "speakers", src: speakersSrc, dst: filepath.Join(paths.InputsDir, "speakers.yml"), source: speakersInput.Source},
|
|
}
|
|
|
|
for _, cfgFile := range preparedConfigFiles {
|
|
checksum, err := copyFileIfChanged(env.ArtifactStore, cfgFile.src, cfgFile.dst)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize %s: %w", cfgFile.kind, err)
|
|
}
|
|
registerConfigInput(cfgFile.kind, cfgFile.dst, checksum, cfgFile.source)
|
|
}
|
|
autocorrectBytes, err := config.RenderAutocorrection(env.Config.Session.Inputs.Autocorrect)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: render autocorrection: %w", err)
|
|
}
|
|
autocorrectDst := filepath.Join(paths.InputsDir, "autocorrect.yml")
|
|
autocorrectChecksum, err := writeBytesIfChanged(env.ArtifactStore, autocorrectDst, autocorrectBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize autocorrection: %w", err)
|
|
}
|
|
inputs = append(inputs, manifest.InputRecord{Kind: "autocorrect", Path: autocorrectDst, Checksum: autocorrectChecksum, Size: int64(len(autocorrectBytes)), Source: config.AutocorrectionSource(env.Config)})
|
|
for _, item := range []struct{ name, source string }{
|
|
{"party", artifactpolicy.SourceInputGlossaryParty},
|
|
{"campaign", artifactpolicy.SourceInputGlossaryCampaign},
|
|
{"setting", artifactpolicy.SourceInputGlossarySetting},
|
|
{"spells", artifactpolicy.SourceInputGlossarySpells},
|
|
{"combined", artifactpolicy.SourceInputGlossaryCombined},
|
|
} {
|
|
descriptor, ok := artifactpolicy.DescribePreparedInputSource(item.source)
|
|
if !ok {
|
|
return nil, fmt.Errorf("prepare: missing descriptor %q", item.source)
|
|
}
|
|
dst := filepath.Join(paths.InputsDir, descriptor.Filename)
|
|
if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(dst)); err != nil {
|
|
return nil, fmt.Errorf("prepare: create glossary directory: %w", err)
|
|
}
|
|
data := glossaryDocuments[item.name]
|
|
checksum, err := writeBytesIfChanged(env.ArtifactStore, dst, data)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize %s: %w", descriptor.ManifestKind, err)
|
|
}
|
|
record := manifest.InputRecord{Kind: descriptor.ManifestKind, Path: dst, Checksum: checksum, Size: int64(len(data)), Source: "derived_from_configuration"}
|
|
if item.source == artifactpolicy.SourceInputGlossaryCombined {
|
|
for _, dependency := range artifactpolicy.GlossaryInputSources() {
|
|
record.Dependencies = append(record.Dependencies, dependency.SourceID)
|
|
}
|
|
}
|
|
inputs = append(inputs, record)
|
|
}
|
|
partyInputs, err := materializePreparedPartyInputs(env.ArtifactStore, env.Config, paths.InputsDir)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: %w", err)
|
|
}
|
|
inputs = append(inputs, partyInputs...)
|
|
|
|
var audioStats s3AudioMaterializationStats
|
|
if useS3Audio {
|
|
stats, err := materializeS3AudioInputs(ctx, env, m, sessionID, &inputs)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: materialize s3 audio: %w", err)
|
|
}
|
|
audioStats = stats
|
|
} else if acquireAudio {
|
|
if err := materializeLocalAudioInputs(env, paths, resolvedLocalAudio, registerInput); err != nil {
|
|
return nil, fmt.Errorf("prepare: %w", err)
|
|
}
|
|
}
|
|
|
|
previousRequirements, err := preparePreviousRequirements(env)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: resolve previous artifact requirements: %w", err)
|
|
}
|
|
var previousHydration *previousSessionHydrationResult
|
|
if err := clearManagedPreviousState(paths); err != nil {
|
|
return nil, fmt.Errorf("prepare: clear previous-session cache: %w", err)
|
|
}
|
|
if len(previousRequirements) > 0 {
|
|
hydration, err := hydratePreviousSessionArtifacts(ctx, env, paths, previousRequirements)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("prepare: hydrate previous-session artifacts: %w", err)
|
|
}
|
|
previousHydration = hydration
|
|
inputs = append(inputs, hydration.Inputs...)
|
|
}
|
|
|
|
sort.Slice(inputs, func(i, j int) bool {
|
|
if inputs[i].Kind != inputs[j].Kind {
|
|
return inputs[i].Kind < inputs[j].Kind
|
|
}
|
|
return inputs[i].Path < inputs[j].Path
|
|
})
|
|
m.Inputs = inputs
|
|
|
|
metadata := map[string]any{
|
|
"prepared": true,
|
|
"stage": "prepare",
|
|
"inputs_count": len(inputs),
|
|
"audio_files_resolved": countAudioInputs(inputs),
|
|
"audio_prepared": acquireAudio,
|
|
}
|
|
if useS3Audio {
|
|
metadata["audio_reused"] = audioStats.Reused
|
|
metadata["audio_s3_downloads"] = audioStats.Downloads
|
|
}
|
|
if len(previousRequirements) > 0 {
|
|
metadata["previous_requirements_count"] = len(previousRequirements)
|
|
if previousHydration != nil {
|
|
metadata["previous_artifacts_hydrated"] = append([]string(nil), previousHydration.Hydrated...)
|
|
metadata["previous_artifacts_hydrated_count"] = len(previousHydration.Hydrated)
|
|
metadata["previous_artifacts_missing_optional"] = append([]string(nil), previousHydration.SkippedMissing...)
|
|
metadata["previous_artifacts_missing_optional_count"] = len(previousHydration.SkippedMissing)
|
|
if strings.TrimSpace(previousHydration.PreviousRunID) != "" {
|
|
metadata["previous_session_run_id"] = strings.TrimSpace(previousHydration.PreviousRunID)
|
|
}
|
|
}
|
|
}
|
|
|
|
return &StageResult{
|
|
Metadata: metadata,
|
|
}, nil
|
|
}
|
|
|
|
func renderResolvedPipeline(cfg *config.PipelineConfig) ([]byte, error) {
|
|
return config.MarshalEffectivePipeline(cfg)
|
|
}
|
|
|
|
func stableInputSource(resolved config.ResolvedInputFile, fallbackPath, fallbackConfigPath string) config.ResolvedInputFile {
|
|
if strings.TrimSpace(resolved.Path) != "" || strings.TrimSpace(resolved.ConfigPath) != "" || strings.TrimSpace(resolved.Source) != "" {
|
|
if strings.TrimSpace(resolved.ConfigPath) == "" {
|
|
resolved.ConfigPath = fallbackConfigPath
|
|
}
|
|
if strings.TrimSpace(resolved.Source) == "" {
|
|
resolved.Source = "session_config"
|
|
}
|
|
return resolved
|
|
}
|
|
return config.ResolvedInputFile{
|
|
Path: fallbackPath,
|
|
ConfigPath: fallbackConfigPath,
|
|
Source: "session_config",
|
|
}
|
|
}
|
|
|
|
func resolveConfigRelativePath(input config.ResolvedInputFile) (string, error) {
|
|
basePath := strings.TrimSpace(input.ConfigPath)
|
|
if basePath == "" {
|
|
return "", fmt.Errorf("source config path is required")
|
|
}
|
|
return resolvePath(filepath.Dir(basePath), input.Path)
|
|
}
|
|
|
|
func resolveAudioInputs(sessionDir string, inputs config.SessionInputsConfig) ([]audio.Source, bool, error) {
|
|
hasLocal := strings.TrimSpace(inputs.AudioDir) != "" || len(inputs.AudioFiles) > 0
|
|
if inputs.AudioS3 != nil {
|
|
if hasLocal {
|
|
return nil, false, fmt.Errorf("audio_dir/audio_files and audio_s3 are mutually exclusive")
|
|
}
|
|
return nil, true, nil
|
|
}
|
|
|
|
local, err := audio.DiscoverLocal(sessionDir, inputs.AudioFiles, inputs.AudioDir)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
return local, false, nil
|
|
}
|
|
|
|
func materializeLocalAudioInputs(env *Env, paths artifacts.SessionPaths, resolvedAudio []audio.Source, registerInput func(kind, path, checksum string)) error {
|
|
for _, src := range resolvedAudio {
|
|
dst := filepath.Join(paths.AudioDir, src.PreparedName)
|
|
checksum, err := copyFileIfChanged(env.ArtifactStore, src.Path, dst)
|
|
if err != nil {
|
|
return fmt.Errorf("materialize audio %q: %w", src.Path, err)
|
|
}
|
|
registerInput("audio", dst, checksum)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type s3AudioMaterializationStats struct {
|
|
Reused int
|
|
Downloads int
|
|
}
|
|
|
|
func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifest, sessionID string, inputs *[]manifest.InputRecord) (s3AudioMaterializationStats, error) {
|
|
if env.ObjectStore == nil {
|
|
return s3AudioMaterializationStats{}, fmt.Errorf("s3 audio input requires object store backend")
|
|
}
|
|
if env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil || env.Config.Pipeline.Storage.S3 == nil || env.Config.Session.Inputs.AudioS3 == nil {
|
|
return s3AudioMaterializationStats{}, fmt.Errorf("s3 audio input requires pipeline.storage.s3 and session.inputs.audio_s3 configuration")
|
|
}
|
|
|
|
campaign := strings.TrimSpace(env.Config.Session.Campaign)
|
|
if campaign == "" {
|
|
return s3AudioMaterializationStats{}, fmt.Errorf("session campaign is required for s3 audio input")
|
|
}
|
|
runID := strings.TrimSpace(m.RunID)
|
|
if runID == "" {
|
|
return s3AudioMaterializationStats{}, fmt.Errorf("run id is required for s3 audio input")
|
|
}
|
|
|
|
audioObjects, err := listS3AudioObjects(ctx, env, campaign, sessionID)
|
|
if err != nil {
|
|
return s3AudioMaterializationStats{}, err
|
|
}
|
|
|
|
workAudioDir := sessionPathsForEnv(env, sessionID).AudioDir
|
|
if err := fileops.EnsureWorkspaceDirectory(workAudioDir); err != nil {
|
|
return s3AudioMaterializationStats{}, fmt.Errorf("create work audio directory %q: %w", workAudioDir, err)
|
|
}
|
|
stats := s3AudioMaterializationStats{}
|
|
priorByPath := make(map[string]*manifest.InputRecord)
|
|
for i := range m.Inputs {
|
|
record := &m.Inputs[i]
|
|
if record.Kind != "audio" {
|
|
continue
|
|
}
|
|
key := filepath.Clean(record.Path)
|
|
if _, exists := priorByPath[key]; !exists {
|
|
priorByPath[key] = record
|
|
}
|
|
}
|
|
for _, obj := range audioObjects {
|
|
workPath := filepath.Join(workAudioDir, path.Base(obj.Key))
|
|
prior := priorByPath[filepath.Clean(workPath)]
|
|
result, err := audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
|
|
Reporter: env.Reporter, Store: env.ObjectStore, Object: obj,
|
|
Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), DestPath: workPath, Prior: prior,
|
|
})
|
|
if err != nil {
|
|
return s3AudioMaterializationStats{}, err
|
|
}
|
|
if result.Reused {
|
|
stats.Reused++
|
|
}
|
|
if result.Downloaded {
|
|
stats.Downloads++
|
|
}
|
|
*inputs = append(*inputs, manifest.InputRecord{
|
|
Kind: "audio", Path: workPath, Checksum: result.Checksum, Source: "s3",
|
|
S3Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), S3Key: result.Object.Key,
|
|
S3Size: result.Object.Size, S3ETag: result.Object.ETag,
|
|
})
|
|
}
|
|
|
|
return stats, nil
|
|
}
|
|
|
|
func listS3AudioObjects(ctx context.Context, env *Env, campaign, sessionID string) ([]storage.ObjectInfo, error) {
|
|
if env == nil || env.ObjectStore == nil || env.Config == nil || env.Config.Pipeline == nil ||
|
|
env.Config.Session == nil || env.Config.Pipeline.Storage.S3 == nil || env.Config.Session.Inputs.AudioS3 == nil {
|
|
return nil, fmt.Errorf("s3 audio input requires object store and resolved storage configuration")
|
|
}
|
|
sessionPrefix := artifacts.S3SessionPrefix(env.Config.Pipeline.Storage.S3.RootPrefix, campaign, sessionID)
|
|
audioPrefix := artifacts.S3AudioPrefix(sessionPrefix, env.Config.Session.Inputs.AudioS3.Prefix)
|
|
return audio.DiscoverS3(ctx, env.ObjectStore, audioPrefix)
|
|
}
|
|
|
|
func countAudioInputs(inputs []manifest.InputRecord) int {
|
|
count := 0
|
|
for _, in := range inputs {
|
|
if in.Kind == "audio" {
|
|
count++
|
|
}
|
|
}
|
|
return count
|
|
}
|
|
|
|
func preparePreviousRequirements(env *Env) ([]artifacts.PreviousArtifactRequirement, error) {
|
|
if env.PreparePreviousRequirements != nil {
|
|
return env.PreparePreviousRequirements, nil
|
|
}
|
|
return collectPreparePreviousRequirements(env.Config, env.EffectiveArtifacts)
|
|
}
|
|
|
|
func collectPreparePreviousRequirements(cfg *config.Config, effective artifacts.EffectiveArtifactSet) ([]artifacts.PreviousArtifactRequirement, error) {
|
|
if cfg == nil || cfg.Pipeline == nil || cfg.Pipeline.Scriptorium == nil {
|
|
return nil, nil
|
|
}
|
|
if !effective.Resolved() {
|
|
var err error
|
|
effective, err = artifacts.ResolveEffectiveArtifactSet(
|
|
artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts()),
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return artifacts.CollectPreviousArtifactRequirements(cfg.ConcreteArtifacts(), effective)
|
|
}
|
|
|
|
func clearManagedPreviousState(paths artifacts.SessionPaths) error {
|
|
previousDir := filepath.Clean(paths.PreviousDir)
|
|
sessionRoot := filepath.Clean(paths.Root)
|
|
if strings.TrimSpace(previousDir) == "" || strings.TrimSpace(sessionRoot) == "" {
|
|
return fmt.Errorf("previous/session root paths are required")
|
|
}
|
|
if previousDir == sessionRoot {
|
|
return fmt.Errorf("refusing to clear session root as previous cache: %q", previousDir)
|
|
}
|
|
prefix := sessionRoot + string(filepath.Separator)
|
|
if !strings.HasPrefix(previousDir, prefix) {
|
|
return fmt.Errorf("refusing to clear path outside session root: %q", previousDir)
|
|
}
|
|
if filepath.Base(previousDir) != config.PathPreviousDirSegment {
|
|
return fmt.Errorf("refusing to clear non-previous path %q", previousDir)
|
|
}
|
|
if err := fileops.RemoveAllUnderRoot(sessionRoot, previousDir); err != nil {
|
|
return err
|
|
}
|
|
return fileops.EnsureWorkspaceDirectory(previousDir)
|
|
}
|
|
|
|
func resolvePath(baseDir, p string) (string, error) {
|
|
trimmed := strings.TrimSpace(p)
|
|
if trimmed == "" {
|
|
return "", fmt.Errorf("path is required")
|
|
}
|
|
if filepath.IsAbs(trimmed) {
|
|
return filepath.Clean(trimmed), nil
|
|
}
|
|
return filepath.Clean(filepath.Join(baseDir, trimmed)), nil
|
|
}
|
|
|
|
func requireFile(path string, label string) error {
|
|
if strings.TrimSpace(path) == "" {
|
|
return fmt.Errorf("%s path is required", label)
|
|
}
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
return fmt.Errorf("%s %q not found: %w", label, path, err)
|
|
}
|
|
if info.IsDir() {
|
|
return fmt.Errorf("%s %q is a directory", label, path)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func requireRegularReadableFile(path string, label string) error {
|
|
if strings.TrimSpace(path) == "" {
|
|
return fmt.Errorf("%s path is required", label)
|
|
}
|
|
declared, err := os.Lstat(path)
|
|
if err != nil {
|
|
return fmt.Errorf("inspect %s %q: %w", label, path, err)
|
|
}
|
|
if declared.Mode()&os.ModeSymlink != 0 || !declared.Mode().IsRegular() {
|
|
return fmt.Errorf("%s %q is not a regular file without symlinks", label, path)
|
|
}
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return fmt.Errorf("open %s %q: %w", label, path, err)
|
|
}
|
|
info, statErr := file.Stat()
|
|
closeErr := file.Close()
|
|
if statErr != nil {
|
|
return fmt.Errorf("stat %s %q: %w", label, path, statErr)
|
|
}
|
|
current, currentErr := os.Lstat(path)
|
|
if currentErr != nil {
|
|
return fmt.Errorf("reinspect %s %q: %w", label, path, currentErr)
|
|
}
|
|
if !info.Mode().IsRegular() || current.Mode()&os.ModeSymlink != 0 || !current.Mode().IsRegular() ||
|
|
!os.SameFile(info, declared) || !os.SameFile(info, current) {
|
|
return fmt.Errorf("%s %q changed while being opened", label, path)
|
|
}
|
|
if closeErr != nil {
|
|
return fmt.Errorf("close %s %q: %w", label, path, closeErr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func copyFileIfChanged(store artifacts.Store, src, dst string) (string, error) {
|
|
srcChecksum, err := store.Checksum(src)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
exists, err := store.Exists(dst)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if exists {
|
|
dstChecksum, err := store.Checksum(dst)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if dstChecksum == srcChecksum {
|
|
return srcChecksum, nil
|
|
}
|
|
}
|
|
|
|
return fileops.CopyFileAtomicWithChecksum(src, dst, fileops.WorkspaceFileMode)
|
|
}
|
|
|
|
func writeBytesIfChanged(store artifacts.Store, dst string, data []byte) (string, error) {
|
|
digest := sha256.Sum256(data)
|
|
targetChecksum := hex.EncodeToString(digest[:])
|
|
|
|
exists, err := store.Exists(dst)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if exists {
|
|
dstChecksum, err := store.Checksum(dst)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if dstChecksum == targetChecksum {
|
|
return targetChecksum, nil
|
|
}
|
|
}
|
|
|
|
if err := store.WriteFileAtomic(dst, data, fileops.WorkspaceFileMode); err != nil {
|
|
return "", err
|
|
}
|
|
return targetChecksum, nil
|
|
}
|