Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit e7b02be

Browse files
committed
git: worktree, add Clean() method for git clean
This change implement git clean with a `Dir` option. By default, clean removes only the untracked files in the working directory. If `Dir` option is set to true, untracked files under other directories are also cleaned.
1 parent 44c364f commit e7b02be

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

options.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,3 +360,8 @@ type ListOptions struct {
360360
// Auth credentials, if required, to use with the remote repository.
361361
Auth transport.AuthMethod
362362
}
363+
364+
// CleanOptions describes how a clean should be performed.
365+
type CleanOptions struct {
366+
Dir bool
367+
}

worktree.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,33 @@ func (w *Worktree) readGitmodulesFile() (*config.Modules, error) {
684684
return m, m.Unmarshal(input)
685685
}
686686

687+
// Clean the worktree by removing untracked files.
688+
func (w *Worktree) Clean(opts *CleanOptions) error {
689+
s, err := w.Status()
690+
if err != nil {
691+
return err
692+
}
693+
694+
// Check Worktree status to be Untracked, obtain absolute path and delete.
695+
for relativePath, status := range s {
696+
// Check if the path contains a directory and if Dir options is false,
697+
// skip the path.
698+
if relativePath != filepath.Base(relativePath) && !opts.Dir {
699+
continue
700+
}
701+
702+
// Remove the file only if it's an untracked file.
703+
if status.Worktree == Untracked {
704+
absPath := filepath.Join(w.Filesystem.Root(), relativePath)
705+
if err := os.Remove(absPath); err != nil {
706+
return err
707+
}
708+
}
709+
}
710+
711+
return nil
712+
}
713+
687714
func rmFileAndDirIfEmpty(fs billy.Filesystem, name string) error {
688715
if err := util.RemoveAll(fs, name); err != nil {
689716
return err

0 commit comments

Comments
 (0)