2
2
mirror of https://github.com/octoleo/restic.git synced 2024-05-28 22:50:48 +00:00
restic/cmd/restic/cmd_rebuild_index.go

86 lines
1.8 KiB
Go
Raw Normal View History

2015-10-25 16:24:52 +00:00
package main
2016-09-17 10:36:05 +00:00
import (
"context"
2017-07-23 12:21:03 +00:00
"github.com/restic/restic/internal/index"
2017-07-24 15:42:25 +00:00
"github.com/restic/restic/internal/restic"
2015-10-25 16:24:52 +00:00
2016-09-17 10:36:05 +00:00
"github.com/spf13/cobra"
)
2015-10-25 16:24:52 +00:00
2016-09-17 10:36:05 +00:00
var cmdRebuildIndex = &cobra.Command{
Use: "rebuild-index [flags]",
Short: "build a new index file",
Long: `
The "rebuild-index" command creates a new index based on the pack files in the
repository.
2016-09-17 10:36:05 +00:00
`,
RunE: func(cmd *cobra.Command, args []string) error {
return runRebuildIndex(globalOptions)
},
2015-10-25 16:24:52 +00:00
}
func init() {
2016-09-17 10:36:05 +00:00
cmdRoot.AddCommand(cmdRebuildIndex)
2015-10-25 16:24:52 +00:00
}
2016-09-17 10:36:05 +00:00
func runRebuildIndex(gopts GlobalOptions) error {
repo, err := OpenRepository(gopts)
2015-10-25 16:24:52 +00:00
if err != nil {
return err
}
lock, err := lockRepoExclusive(repo)
defer unlockRepo(lock)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(gopts.ctx)
defer cancel()
return rebuildIndex(ctx, repo, restic.NewIDSet())
}
func rebuildIndex(ctx context.Context, repo restic.Repository, ignorePacks restic.IDSet) error {
Verbosef("counting files in repo\n")
var packs uint64
2017-06-04 09:16:55 +00:00
for range repo.List(ctx, restic.DataFile) {
packs++
}
2017-06-16 17:03:26 +00:00
bar := newProgressMax(!globalOptions.Quiet, packs-uint64(len(ignorePacks)), "packs")
idx, _, err := index.New(ctx, repo, ignorePacks, bar)
if err != nil {
return err
}
Verbosef("finding old index files\n")
var supersedes restic.IDs
2017-06-04 09:16:55 +00:00
for id := range repo.List(ctx, restic.IndexFile) {
supersedes = append(supersedes, id)
}
2017-06-04 09:16:55 +00:00
id, err := idx.Save(ctx, repo, supersedes)
if err != nil {
return err
}
Verbosef("saved new index as %v\n", id.Str())
Verbosef("remove %d old index files\n", len(supersedes))
for _, id := range supersedes {
2017-06-04 09:16:55 +00:00
if err := repo.Backend().Remove(ctx, restic.Handle{
Type: restic.IndexFile,
Name: id.String(),
}); err != nil {
Warnf("error removing old index %v: %v\n", id.Str(), err)
}
}
return nil
2015-10-25 16:24:52 +00:00
}