package arrange import ( "errors" "fmt" "io" "io/fs" "os" "path/filepath" "time" ) // Media is the high-level filetype that can be arranged. type Media struct { Path string Hash string Extension string Time time.Time Size int64 } // Move is called to push Media into its final destination, by content address // and by date. // // The content file is written under a temporary name, checked against m.Hash, // synced, and only then linked into place, so an interrupted run never leaves // a truncated file in the store looking like a dup. func (m Media) Move(root string) error { content := m.Content(root) if _, err := os.Stat(content); !os.IsNotExist(err) { return Dup{content} } if err := m.store(content); err != nil { if errors.Is(err, fs.ErrExist) { return Dup{content} } return err } year := fmt.Sprintf("%04d", m.Time.Year()) month := fmt.Sprintf("%02d", m.Time.Month()) ts := fmt.Sprintf("%d", m.Time.UnixNano()) if err := os.MkdirAll(filepath.Join(root, "date", year, month), 0755); err != nil { return fmt.Errorf("problem creating date directory: %v", err) } date := filepath.Join(root, "date", year, month, ts) name := date + m.Extension for i := 0; i < 10000; i++ { err := os.Link(content, name) if !errors.Is(err, fs.ErrExist) { return err } name = fmt.Sprintf("%s_%04d%s", date, i, m.Extension) } return fmt.Errorf("too many files at %q", date) } // store copies m.Path to content via a verified temporary file. func (m Media) store(content string) error { f, err := os.Open(m.Path) if err != nil { return fmt.Errorf("problem opening file %q: %v", m.Path, err) } defer f.Close() tmp, err := os.CreateTemp(filepath.Dir(content), ".tmp-") if err != nil { return fmt.Errorf("could not create output file: %v", err) } defer os.Remove(tmp.Name()) hash := NewHash() if _, err := io.Copy(io.MultiWriter(tmp, hash), f); err != nil { tmp.Close() return fmt.Errorf("trouble copying file: %v", err) } if got := fmt.Sprintf("%x", hash.Sum(nil)); got != m.Hash { tmp.Close() return fmt.Errorf("%q changed while arranging: hashed %s, copied %s", m.Path, m.Hash, got) } if err := tmp.Sync(); err != nil { tmp.Close() return fmt.Errorf("couldn't sync %q: %v", tmp.Name(), err) } if err := tmp.Close(); err != nil { return fmt.Errorf("couldn't close %q: %v", tmp.Name(), err) } if err := os.Chmod(tmp.Name(), 0644); err != nil { return fmt.Errorf("couldn't chmod %q: %v", tmp.Name(), err) } if err := os.Chtimes(tmp.Name(), time.Now(), m.Time); err != nil { return fmt.Errorf("couldn't chtimes for %q: %v", tmp.Name(), err) } // link, not rename: it fails rather than clobbers if content appeared // in the meantime. return os.Link(tmp.Name(), content) } // Content returns the content-address path starting at root. func (m Media) Content(root string) string { return filepath.Join(root, "content", m.Hash[:2], m.Hash[2:]+m.Extension) }