DeletePrefix deletes everything starting with the specified prefix. The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_").
(prefix string)
| 310 | // |
| 311 | // The prefix could be subpath (ex. "/a/b/") or filename prefix (ex. "/a/b/file_"). |
| 312 | func (s *System) DeletePrefix(prefix string) []error { |
| 313 | failed := []error{} |
| 314 | |
| 315 | if prefix == "" { |
| 316 | failed = append(failed, errors.New("prefix mustn't be empty")) |
| 317 | return failed |
| 318 | } |
| 319 | |
| 320 | dirsMap := map[string]struct{}{} |
| 321 | |
| 322 | var isPrefixDir bool |
| 323 | |
| 324 | // treat the prefix as directory only if it ends with trailing slash |
| 325 | if strings.HasSuffix(prefix, "/") { |
| 326 | isPrefixDir = true |
| 327 | dirsMap[strings.TrimRight(prefix, "/")] = struct{}{} |
| 328 | } |
| 329 | |
| 330 | // delete all files with the prefix |
| 331 | // --- |
| 332 | iter := s.bucket.List(&blob.ListOptions{ |
| 333 | Prefix: prefix, |
| 334 | }) |
| 335 | for { |
| 336 | obj, err := iter.Next(s.ctx) |
| 337 | if err != nil { |
| 338 | if !errors.Is(err, io.EOF) { |
| 339 | failed = append(failed, err) |
| 340 | } |
| 341 | break |
| 342 | } |
| 343 | |
| 344 | if err := s.Delete(obj.Key); err != nil { |
| 345 | failed = append(failed, err) |
| 346 | } else if isPrefixDir { |
| 347 | slashIdx := strings.LastIndex(obj.Key, "/") |
| 348 | if slashIdx > -1 { |
| 349 | dirsMap[obj.Key[:slashIdx]] = struct{}{} |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | // --- |
| 354 | |
| 355 | // try to delete the empty remaining dir objects |
| 356 | // (this operation usually is optional and there is no need to strictly check the result) |
| 357 | // --- |
| 358 | // fill dirs slice |
| 359 | dirs := make([]string, 0, len(dirsMap)) |
| 360 | for d := range dirsMap { |
| 361 | dirs = append(dirs, d) |
| 362 | } |
| 363 | |
| 364 | // sort the child dirs first, aka. ["a/b/c", "a/b", "a"] |
| 365 | sort.SliceStable(dirs, func(i, j int) bool { |
| 366 | return len(strings.Split(dirs[i], "/")) > len(strings.Split(dirs[j], "/")) |
| 367 | }) |
| 368 | |
| 369 | // delete dirs |