github.com/fawick/restic@v0.1.1-0.20171126184616-c02923fbfc79/internal/restic/snapshot_find.go (about)

     1  package restic
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"time"
     8  
     9  	"github.com/restic/restic/internal/errors"
    10  )
    11  
    12  // ErrNoSnapshotFound is returned when no snapshot for the given criteria could be found.
    13  var ErrNoSnapshotFound = errors.New("no snapshot found")
    14  
    15  // FindLatestSnapshot finds latest snapshot with optional target/directory, tags and hostname filters.
    16  func FindLatestSnapshot(ctx context.Context, repo Repository, targets []string, tagLists []TagList, hostname string) (ID, error) {
    17  	var (
    18  		latest   time.Time
    19  		latestID ID
    20  		found    bool
    21  	)
    22  
    23  	for snapshotID := range repo.List(ctx, SnapshotFile) {
    24  		snapshot, err := LoadSnapshot(ctx, repo, snapshotID)
    25  		if err != nil {
    26  			return ID{}, errors.Errorf("Error listing snapshot: %v", err)
    27  		}
    28  		if snapshot.Time.Before(latest) || (hostname != "" && hostname != snapshot.Hostname) {
    29  			continue
    30  		}
    31  
    32  		if !snapshot.HasTagList(tagLists) {
    33  			continue
    34  		}
    35  
    36  		if !snapshot.HasPaths(targets) {
    37  			continue
    38  		}
    39  
    40  		latest = snapshot.Time
    41  		latestID = snapshotID
    42  		found = true
    43  	}
    44  
    45  	if !found {
    46  		return ID{}, ErrNoSnapshotFound
    47  	}
    48  
    49  	return latestID, nil
    50  }
    51  
    52  // FindSnapshot takes a string and tries to find a snapshot whose ID matches
    53  // the string as closely as possible.
    54  func FindSnapshot(repo Repository, s string) (ID, error) {
    55  
    56  	// find snapshot id with prefix
    57  	name, err := Find(repo.Backend(), SnapshotFile, s)
    58  	if err != nil {
    59  		return ID{}, err
    60  	}
    61  
    62  	return ParseID(name)
    63  }
    64  
    65  // FindFilteredSnapshots yields Snapshots filtered from the list of all
    66  // snapshots.
    67  func FindFilteredSnapshots(ctx context.Context, repo Repository, host string, tags []TagList, paths []string) Snapshots {
    68  	results := make(Snapshots, 0, 20)
    69  
    70  	for id := range repo.List(ctx, SnapshotFile) {
    71  		sn, err := LoadSnapshot(ctx, repo, id)
    72  		if err != nil {
    73  			fmt.Fprintf(os.Stderr, "could not load snapshot %v: %v\n", id.Str(), err)
    74  			continue
    75  		}
    76  		if (host != "" && host != sn.Hostname) || !sn.HasTagList(tags) || !sn.HasPaths(paths) {
    77  			continue
    78  		}
    79  
    80  		results = append(results, sn)
    81  	}
    82  	return results
    83  }