2024-01-02 08:29:18 +08:00
|
|
|
package store
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-01-03 08:31:59 +08:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
2024-01-02 08:29:18 +08:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2024-01-03 08:31:59 +08:00
|
|
|
|
|
|
|
"github.com/usememos/memos/internal/log"
|
2024-01-02 08:29:18 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// MigrateResourceInternalPath migrates resource internal path from absolute path to relative path.
|
|
|
|
func (s *Store) MigrateResourceInternalPath(ctx context.Context) error {
|
|
|
|
resources, err := s.ListResources(ctx, &FindResource{})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to list resources")
|
|
|
|
}
|
|
|
|
|
2024-01-03 08:31:59 +08:00
|
|
|
dataPath := strings.ReplaceAll(s.Profile.Data, `\`, "/")
|
|
|
|
migrateStartTime := time.Now()
|
|
|
|
migratedCount := 0
|
2024-01-02 08:29:18 +08:00
|
|
|
for _, resource := range resources {
|
|
|
|
if resource.InternalPath == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-01-03 08:31:59 +08:00
|
|
|
internalPath := strings.ReplaceAll(resource.InternalPath, `\`, "/")
|
|
|
|
if !strings.HasPrefix(internalPath, dataPath) {
|
|
|
|
continue
|
2024-01-02 08:29:18 +08:00
|
|
|
}
|
2024-01-03 08:31:59 +08:00
|
|
|
|
|
|
|
internalPath = strings.TrimPrefix(internalPath, dataPath)
|
|
|
|
|
|
|
|
for os.IsPathSeparator(internalPath[0]) {
|
|
|
|
internalPath = internalPath[1:]
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := s.UpdateResource(ctx, &UpdateResource{
|
|
|
|
ID: resource.ID,
|
|
|
|
InternalPath: &internalPath,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "failed to update local resource path")
|
|
|
|
}
|
|
|
|
migratedCount++
|
2024-01-02 08:29:18 +08:00
|
|
|
}
|
|
|
|
|
2024-01-06 16:55:13 +08:00
|
|
|
if migratedCount > 0 && s.Profile.Mode == "prod" {
|
2024-01-03 08:31:59 +08:00
|
|
|
log.Info(fmt.Sprintf("migrated %d local resource paths in %s", migratedCount, time.Since(migrateStartTime)))
|
|
|
|
}
|
2024-01-02 08:29:18 +08:00
|
|
|
return nil
|
|
|
|
}
|