sync

package
v0.0.0-...-13a52e5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sync provides Google Drive sync functionality.

Index

Constants

View Source
const (
	// PIDFileName is the name of the PID file.
	PIDFileName = "sync.pid"
	// LogFileName is the name of the sync log file.
	LogFileName = "sync.log"
)
View Source
const DefaultPollIntervalDuration = 5 * time.Second

DefaultPollIntervalDuration is the default poll interval for Drive changes.

Variables

This section is empty.

Functions

func CheckNotAlreadyRunning

func CheckNotAlreadyRunning() error

CheckNotAlreadyRunning returns an error if the daemon is already running.

func DBPath

func DBPath() (string, error)

DBPath returns the path to the sync database file.

func DefaultPollInterval

func DefaultPollInterval() time.Duration

DefaultPollInterval returns the poll interval from environment or default.

func InstallService

func InstallService(cfg ServiceConfig, manager ServiceManager) error

InstallService installs the sync daemon as a managed service.

func LogFilePath

func LogFilePath() (string, error)

LogFilePath returns the path to the sync log file.

func PIDFilePath

func PIDFilePath() (string, error)

PIDFilePath returns the path to the PID file.

func RemovePIDFile

func RemovePIDFile() error

RemovePIDFile removes the PID file.

func ServiceStatus

func ServiceStatus(manager ServiceManager) (bool, string, error)

ServiceStatus checks the status of the installed service. Returns (running, statusText, error).

func StartDaemon

func StartDaemon(localPath, account, conflict string) (int, error)

StartDaemon starts the sync daemon in the background. It re-executes the current binary with --internal-daemon flag.

func StopDaemon

func StopDaemon() error

StopDaemon stops the running daemon by sending SIGTERM.

func UninstallService

func UninstallService(manager ServiceManager) error

UninstallService removes the sync service.

func WritePIDFile

func WritePIDFile() error

WritePIDFile writes the current process ID to the PID file.

Types

type ConflictInfo

type ConflictInfo struct {
	LocalPath      string
	DriveID        string
	LocalMD5       string
	RemoteMD5      string
	LocalMtime     time.Time
	RemoteMtime    time.Time
	LastSyncMD5    string
	LastSyncMtime  time.Time
	LocalModified  bool
	RemoteModified bool
}

ConflictInfo contains information about a detected conflict.

type ConflictResolver

type ConflictResolver struct {
	// contains filtered or unexported fields
}

ConflictResolver handles sync conflict detection and resolution.

func NewConflictResolver

func NewConflictResolver(db *DB, configID int64, strategy ConflictStrategy) *ConflictResolver

NewConflictResolver creates a new conflict resolver.

func (*ConflictResolver) DetectConflict

func (r *ConflictResolver) DetectConflict(ctx context.Context, item *SyncItem, localPath string, remoteMD5 string, remoteMtime time.Time) (*ConflictInfo, error)

DetectConflict checks if a file has a conflict.

func (*ConflictResolver) Resolve

func (r *ConflictResolver) Resolve(ctx context.Context, conflict *ConflictInfo, localRoot string) (*ResolveResult, error)

Resolve resolves a conflict according to the configured strategy.

type ConflictStrategy

type ConflictStrategy string

ConflictStrategy defines how to handle sync conflicts.

const (
	// ConflictRename keeps both versions by renaming the conflicting file.
	ConflictRename ConflictStrategy = "rename"
	// ConflictLocalWins overwrites the remote with the local version.
	ConflictLocalWins ConflictStrategy = "local-wins"
	// ConflictRemoteWins overwrites the local with the remote version.
	ConflictRemoteWins ConflictStrategy = "remote-wins"
)

func ParseConflictStrategy

func ParseConflictStrategy(s string) (ConflictStrategy, error)

ParseConflictStrategy parses a conflict strategy string.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB provides sync state persistence using SQLite.

func OpenDB

func OpenDB() (*DB, error)

OpenDB opens (or creates) the sync database.

func (*DB) AddLogEntry

func (d *DB) AddLogEntry(configID int64, action, path string, details map[string]any) error

AddLogEntry adds an entry to the sync log.

func (*DB) Close

func (d *DB) Close() error

Close closes the database connection.

func (*DB) CreateConfig

func (d *DB) CreateConfig(localPath, driveFolderID, driveID string) (*SyncConfig, error)

CreateConfig creates a new sync configuration.

func (*DB) CreateSyncFolder

func (d *DB) CreateSyncFolder(configID int64, driveID, localPath string) error

CreateSyncFolder creates or updates a folder mapping.

func (*DB) CreateSyncItem

func (d *DB) CreateSyncItem(configID int64, localPath, driveID, localMD5, remoteMD5 string, localMtime, remoteMtime time.Time) error

CreateSyncItem creates a new sync item.

func (*DB) DeleteSyncFolders

func (d *DB) DeleteSyncFolders(configID int64) error

DeleteSyncFolders deletes all sync_folders for a config.

func (*DB) GetConfig

func (d *DB) GetConfig(localPath string) (*SyncConfig, error)

GetConfig retrieves a sync configuration by local path.

func (*DB) GetConfigByID

func (d *DB) GetConfigByID(id int64) (*SyncConfig, error)

GetConfigByID retrieves a sync configuration by ID.

func (*DB) GetRecentLogs

func (d *DB) GetRecentLogs(configID int64, limit int) ([]SyncLogEntry, error)

GetRecentLogs returns recent log entries for a config.

func (*DB) GetStatus

func (d *DB) GetStatus(configID int64) (*SyncStatus, error)

GetStatus returns the sync status for a configuration.

func (*DB) GetSyncFolderByDriveID

func (d *DB) GetSyncFolderByDriveID(configID int64, driveID string) (*SyncFolder, error)

GetSyncFolderByDriveID looks up a folder by its Drive ID.

func (*DB) GetSyncFolderByPath

func (d *DB) GetSyncFolderByPath(configID int64, localPath string) (*SyncFolder, error)

GetSyncFolderByPath looks up a folder by its local path.

func (*DB) GetSyncItem

func (d *DB) GetSyncItem(configID int64, localPath string) (*SyncItem, error)

GetSyncItem retrieves a sync item by local path.

func (*DB) GetSyncItemByDriveID

func (d *DB) GetSyncItemByDriveID(configID int64, driveID string) (*SyncItem, error)

GetSyncItemByDriveID retrieves a sync item by Drive file ID.

func (*DB) ListAllItems

func (d *DB) ListAllItems(configID int64) ([]SyncItem, error)

ListAllItems returns all sync items for a config, regardless of state.

func (*DB) ListConfigs

func (d *DB) ListConfigs() ([]SyncConfig, error)

ListConfigs returns all sync configurations.

func (*DB) ListPendingUploads

func (d *DB) ListPendingUploads(configID int64) ([]SyncItem, error)

ListPendingUploads returns all sync items with pending_upload state for a config.

func (*DB) ListStatuses

func (d *DB) ListStatuses() ([]SyncStatus, error)

ListStatuses returns the sync status for all configurations.

func (*DB) ListSyncFolderDriveIDs

func (d *DB) ListSyncFolderDriveIDs(configID int64) (map[string]bool, error)

ListSyncFolderDriveIDs returns all known Drive folder IDs for a config.

func (*DB) ListSyncedItems

func (d *DB) ListSyncedItems(configID int64) ([]SyncItem, error)

ListSyncedItems returns all sync items with state "synced" for a config.

func (*DB) RemoveConfig

func (d *DB) RemoveConfig(localPath string) error

RemoveConfig removes a sync configuration by local path.

func (*DB) RemoveSyncItem

func (d *DB) RemoveSyncItem(configID int64, localPath string) error

RemoveSyncItem removes a sync item by local path.

func (*DB) RemoveSyncItemByID

func (d *DB) RemoveSyncItemByID(itemID int64) error

RemoveSyncItemByID removes a sync item by its ID.

func (*DB) UpdateChangeToken

func (d *DB) UpdateChangeToken(configID int64, token string) error

UpdateChangeToken updates the change token for a config.

func (*DB) UpdateSyncItem

func (d *DB) UpdateSyncItem(itemID int64, driveID, localMD5, remoteMD5 string, state SyncState) error

UpdateSyncItem updates a sync item.

type DaemonStatus

type DaemonStatus struct {
	Running bool   `json:"running"`
	PID     int    `json:"pid,omitempty"`
	Error   string `json:"error,omitempty"`
}

DaemonStatus represents the status of the daemon.

func GetDaemonStatus

func GetDaemonStatus() (*DaemonStatus, error)

GetDaemonStatus checks if the daemon is running.

type DownloadResult

type DownloadResult struct {
	LocalPath string
	MD5       string
}

DownloadResult contains the result of a download operation.

type Downloader

type Downloader struct {
	// contains filtered or unexported fields
}

Downloader handles downloading files from Google Drive.

func NewDownloader

func NewDownloader(service *drive.Service, localRoot string, db *DB, configID int64) *Downloader

NewDownloader creates a new downloader.

func (*Downloader) DownloadFile

func (d *Downloader) DownloadFile(ctx context.Context, fileID, fileName string) (*DownloadResult, error)

DownloadFile downloads a file from Drive to the local filesystem.

func (*Downloader) DownloadFolder

func (d *Downloader) DownloadFolder(ctx context.Context, folderID, folderName string) error

DownloadFolder creates a local folder.

type DriveChange

type DriveChange struct {
	FileID    string
	FileName  string
	MimeType  string
	MD5       string
	Op        DriveChangeOp
	Removed   bool // File was deleted/trashed
	Timestamp time.Time
}

DriveChange represents a change detected on Google Drive.

type DriveChangeOp

type DriveChangeOp int

DriveChangeOp represents the type of Drive change.

const (
	// DriveOpCreate indicates a file was created.
	DriveOpCreate DriveChangeOp = iota
	// DriveOpModify indicates a file was modified.
	DriveOpModify
	// DriveOpDelete indicates a file was deleted.
	DriveOpDelete
)

func (DriveChangeOp) String

func (op DriveChangeOp) String() string

String returns the string representation of the change operation.

type DrivePoller

type DrivePoller struct {
	// contains filtered or unexported fields
}

DrivePoller polls Google Drive for changes.

func NewDrivePoller

func NewDrivePoller(service *drive.Service, db *DB, configID int64, folderID string, pollInterval time.Duration) *DrivePoller

NewDrivePoller creates a new Drive changes poller.

func (*DrivePoller) Errors

func (p *DrivePoller) Errors() <-chan error

Errors returns the channel of errors.

func (*DrivePoller) Events

func (p *DrivePoller) Events() <-chan DriveChange

Events returns the channel of drive changes.

func (*DrivePoller) Start

func (p *DrivePoller) Start(ctx context.Context) error

Start begins polling. Blocks until context is cancelled.

type DuplicateFolder

type DuplicateFolder struct {
	Name      string   `json:"name"`
	ParentID  string   `json:"parent_id"`
	FolderIDs []string `json:"folder_ids"` // All Drive IDs; first is the "keep" candidate (oldest)
}

DuplicateFolder represents folders with the same name under the same parent.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine orchestrates bidirectional sync between a local folder and Google Drive.

func NewEngine

func NewEngine(opts EngineOptions) (*Engine, error)

NewEngine creates a new sync engine.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context) error

Start begins the sync loop. Blocks until context is cancelled.

type EngineOptions

type EngineOptions struct {
	DB           *DB
	Config       *SyncConfig
	DriveService *drive.Service
	Debounce     time.Duration
	PollInterval time.Duration
}

EngineOptions configures the sync engine.

type OrphanedItem

type OrphanedItem struct {
	LocalPath string `json:"local_path"`
	DriveID   string `json:"drive_id"`
	Reason    string `json:"reason"` // "no_local_file", "no_remote_file", "both_missing"
	ItemID    int64  `json:"item_id"`
	ConfigID  int64  `json:"config_id"`
}

OrphanedItem represents a sync_item with no corresponding local or remote file.

type RepairReport

type RepairReport struct {
	DuplicateFolders []DuplicateFolder `json:"duplicate_folders"`
	StaleHashes      []StaleHash       `json:"stale_hashes"`
	OrphanedItems    []OrphanedItem    `json:"orphaned_items"`
}

RepairReport contains the results of a repair scan.

func (*RepairReport) HasIssues

func (r *RepairReport) HasIssues() bool

HasIssues returns true if the report contains any issues.

type Repairer

type Repairer struct {
	// contains filtered or unexported fields
}

Repairer handles sync state repair operations.

func NewRepairer

func NewRepairer(db *DB, config *SyncConfig, service *drive.Service) *Repairer

NewRepairer creates a new Repairer.

func (*Repairer) Apply

func (r *Repairer) Apply(ctx context.Context, report *RepairReport) error

Apply executes the fixes described in the report.

func (*Repairer) Scan

func (r *Repairer) Scan(ctx context.Context) (*RepairReport, error)

Scan performs a dry-run scan and builds the repair report.

type ResolveResult

type ResolveResult struct {
	Action         string // "rename", "local-wins", "remote-wins"
	RenamedPath    string // For rename strategy, the new path
	UploadLocal    bool   // True if local file should be uploaded
	DownloadRemote bool   // True if remote file should be downloaded
}

ResolveResult contains the result of conflict resolution.

type ServiceConfig

type ServiceConfig struct {
	LocalPath  string
	Account    string
	Conflict   string
	Executable string // Path to wk binary
}

ServiceConfig holds the parameters for service installation.

type ServiceManager

type ServiceManager string

ServiceManager represents a process management system.

const (
	ServiceManagerSystemd       ServiceManager = "systemd"
	ServiceManagerPM2           ServiceManager = "pm2"
	ServiceManagerLaunchd       ServiceManager = "launchd"
	ServiceManagerTaskScheduler ServiceManager = "schtasks"
)

func DetectServiceManager

func DetectServiceManager() (ServiceManager, error)

DetectServiceManager auto-detects the available service manager.

type StaleHash

type StaleHash struct {
	LocalPath string `json:"local_path"`
	StoredMD5 string `json:"stored_md5"`
	ActualMD5 string `json:"actual_md5"`
	ItemID    int64  `json:"item_id"`
	DriveID   string `json:"drive_id"`
}

StaleHash represents a tracked file whose local MD5 doesn't match the DB.

type SyncConfig

type SyncConfig struct {
	ID            int64     `json:"id"`
	LocalPath     string    `json:"local_path"`
	DriveFolderID string    `json:"drive_folder_id"`
	DriveID       string    `json:"drive_id,omitempty"` // For shared drives
	CreatedAt     time.Time `json:"created_at"`
	LastSyncAt    time.Time `json:"last_sync_at,omitempty"`
	ChangeToken   string    `json:"change_token,omitempty"` // Drive changes page token
}

SyncConfig represents a sync configuration between a local folder and a Drive folder.

type SyncFolder

type SyncFolder struct {
	ID        int64  `json:"id"`
	ConfigID  int64  `json:"config_id"`
	DriveID   string `json:"drive_id"`
	LocalPath string `json:"local_path"` // Relative to config's local_path
}

SyncFolder represents a tracked folder in the sync tree.

type SyncItem

type SyncItem struct {
	ID          int64     `json:"id"`
	ConfigID    int64     `json:"config_id"`
	LocalPath   string    `json:"local_path"`  // Relative to config's local_path
	DriveID     string    `json:"drive_id"`    // Drive file ID
	LocalMD5    string    `json:"local_md5"`   // MD5 hash of local file
	RemoteMD5   string    `json:"remote_md5"`  // MD5 hash from Drive
	LocalMtime  time.Time `json:"local_mtime"` // Local modification time
	RemoteMtime time.Time `json:"remote_mtime"`
	SyncState   SyncState `json:"sync_state"`
}

SyncItem represents a tracked file/folder in a sync configuration.

type SyncLogEntry

type SyncLogEntry struct {
	ID        int64     `json:"id"`
	ConfigID  int64     `json:"config_id"`
	Action    string    `json:"action"` // upload, download, delete, conflict, error
	Path      string    `json:"path"`
	Timestamp time.Time `json:"timestamp"`
	Details   string    `json:"details,omitempty"` // JSON details
}

SyncLogEntry represents an entry in the sync log.

type SyncState

type SyncState string

SyncState represents the state of a synced item.

const (
	// StateSynced means the local and remote files are in sync.
	StateSynced SyncState = "synced"
	// StatePendingUpload means the local file needs to be uploaded.
	StatePendingUpload SyncState = "pending_upload"
	// StatePendingDownload means the remote file needs to be downloaded.
	StatePendingDownload SyncState = "pending_download"
	// StateConflict means both local and remote have changed.
	StateConflict SyncState = "conflict"
	// StateError means there was an error syncing this file.
	StateError SyncState = "error"
)

type SyncStatus

type SyncStatus struct {
	Config        SyncConfig `json:"config"`
	TotalItems    int64      `json:"total_items"`
	SyncedItems   int64      `json:"synced_items"`
	PendingItems  int64      `json:"pending_items"`
	ConflictItems int64      `json:"conflict_items"`
	ErrorItems    int64      `json:"error_items"`
	DaemonRunning bool       `json:"daemon_running"`
}

SyncStatus represents the current status of a sync configuration.

type UploadResult

type UploadResult struct {
	DriveID string
	MD5     string
	ModTime time.Time
}

UploadResult contains the result of an upload operation.

type Uploader

type Uploader struct {
	// contains filtered or unexported fields
}

Uploader handles uploading files to Google Drive. It is safe for concurrent use from multiple goroutines.

func NewUploader

func NewUploader(service *drive.Service, rootFolder, driveID string, db *DB, configID int64) *Uploader

NewUploader creates a new uploader.

func (*Uploader) CreateFolder

func (u *Uploader) CreateFolder(ctx context.Context, relPath string) error

CreateFolder creates a folder in Drive.

func (*Uploader) Delete

func (u *Uploader) Delete(ctx context.Context, relPath string) error

Delete removes a file or folder from Drive.

func (*Uploader) SetFolderID

func (u *Uploader) SetFolderID(path, id string)

SetFolderID sets a folder ID in the in-memory cache (for external population).

func (*Uploader) UploadFile

func (u *Uploader) UploadFile(ctx context.Context, relPath, absPath string) (*UploadResult, error)

UploadFile uploads a file to Drive.

type WatchEvent

type WatchEvent struct {
	Path      string    // Absolute path
	RelPath   string    // Relative to watched root
	Op        WatchOp   // Operation type
	Timestamp time.Time // When the event occurred
}

WatchEvent represents a filesystem change event.

type WatchOp

type WatchOp int

WatchOp represents the type of filesystem operation.

const (
	// OpCreate indicates a file or directory was created.
	OpCreate WatchOp = iota
	// OpWrite indicates a file was modified.
	OpWrite
	// OpDelete indicates a file or directory was deleted.
	OpDelete
	// OpRename indicates a file or directory was renamed.
	OpRename
)

func (WatchOp) String

func (o WatchOp) String() string

String returns a string representation of the operation.

type Watcher

type Watcher struct {
	// contains filtered or unexported fields
}

Watcher watches a directory for filesystem changes.

func NewWatcher

func NewWatcher(root string, debounce time.Duration) (*Watcher, error)

NewWatcher creates a new filesystem watcher. debounce specifies how long to wait after the last event before emitting.

func (*Watcher) Errors

func (w *Watcher) Errors() <-chan error

Errors returns the channel of errors.

func (*Watcher) Events

func (w *Watcher) Events() <-chan WatchEvent

Events returns the channel of watch events.

func (*Watcher) Start

func (w *Watcher) Start(ctx context.Context) error

Start begins watching. Blocks until context is cancelled.

func (*Watcher) Stop

func (w *Watcher) Stop() error

Stop stops the watcher.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL