Remove removes a path.
(name string)
| 577 | |
| 578 | // Remove removes a path. |
| 579 | func (obj *Fs) Remove(name string) error { |
| 580 | if err := obj.mount(); err != nil { |
| 581 | return err |
| 582 | } |
| 583 | if name == "" { |
| 584 | return fmt.Errorf("invalid input path") |
| 585 | } |
| 586 | if !strings.HasPrefix(name, "/") { |
| 587 | return fmt.Errorf("invalid input path (not absolute)") |
| 588 | } |
| 589 | |
| 590 | // remove possible trailing slashes |
| 591 | cleanPath := path.Clean(name) |
| 592 | |
| 593 | for strings.HasSuffix(cleanPath, "/") { // bonus clean for "/" as input |
| 594 | cleanPath = strings.TrimSuffix(cleanPath, "/") |
| 595 | } |
| 596 | |
| 597 | if cleanPath == "" { |
| 598 | return fmt.Errorf("can't remove root") |
| 599 | } |
| 600 | |
| 601 | f, err := obj.find(name) // get the file |
| 602 | if err != nil { |
| 603 | return err |
| 604 | } |
| 605 | |
| 606 | if len(f.Children) > 0 { // this file or dir has children, can't remove! |
| 607 | return &os.PathError{Op: "remove", Path: name, Err: syscall.ENOTEMPTY} |
| 608 | } |
| 609 | |
| 610 | // find the parent node |
| 611 | parentPath, filePath := path.Split(cleanPath) // looking for this |
| 612 | |
| 613 | node, err := obj.find(parentPath) |
| 614 | if err != nil { // might be ErrNotExist |
| 615 | if os.IsNotExist(err) { // race! must have just disappeared |
| 616 | return nil |
| 617 | } |
| 618 | return err |
| 619 | } |
| 620 | |
| 621 | var index = -1 // int |
| 622 | for i, n := range node.Children { |
| 623 | if n.Path == filePath { |
| 624 | index = i // found here! |
| 625 | break |
| 626 | } |
| 627 | } |
| 628 | if index == -1 { |
| 629 | return fmt.Errorf("programming error") |
| 630 | } |
| 631 | // remove from list |
| 632 | node.Children = append(node.Children[:index], node.Children[index+1:]...) |
| 633 | return obj.sync() |
| 634 | } |
| 635 | |
| 636 | // RemoveAll removes path and any children it contains. It removes everything it |