filemanager/filemanager.go (83 lines of code) (raw):

package filemanager import ( "fmt" "net/http" "path/filepath" "strings" "sync" ) // FileManager represents the structure of the File Manager type FileManager struct { Path string sync.Mutex } type Error struct { code int err error } func (e *Error) Error() string { if e.err != nil { return e.err.Error() } return "" } func (e *Error) Code() int { return e.code } // New builds a new FileManager object func New(path string) (*FileManager, *Error) { fm := &FileManager{Path: path} if customErr := fm.isGitRepository(); customErr != nil { return nil, customErr } return fm, nil } // Start starts the filewatcher service to detect // modifications in the current repository by the user func (fm *FileManager) Start() *Error { // TODO return nil } // Stop stops the filewatcher service func (fm *FileManager) Stop() *Error { // TODO return nil } // Patch applies diffs to the current repository func (fm *FileManager) Patch(diff string) *Error { fm.Lock() defer fm.Unlock() if diff == "" { return nil } return fm.runGitApply(diff, false) } // Delete can delete both files and firectories func (fm *FileManager) Delete(paths []string) *Error { fm.Lock() defer fm.Unlock() // Remove any empty string from paths var validPaths []string for _, path := range paths { if path != "" { validPaths = append(validPaths, path) } } return fm.runGitDelete(validPaths) } // ResetRepository resets and clean the repository func (fm *FileManager) ResetRepository() *Error { fm.Lock() defer fm.Unlock() if err := fm.runGitResetHard(); err != nil { return err } // Clean any non tracked file return fm.runCleanRepository() } func (fm *FileManager) currentPath(path string) (string, *Error) { actualPath := filepath.Join(fm.Path, path) _, err := filepath.Rel(fm.Path, actualPath) if err != nil || !strings.HasPrefix(actualPath, fm.Path) { return "", &Error{code: http.StatusUnprocessableEntity, err: fmt.Errorf("the path %s is outside the git repository", path)} } return actualPath, nil } // ResetChanges resets the changes in the index and the work tree func (fm *FileManager) ResetChanges() *Error { fm.Lock() defer fm.Unlock() // We reset the repository to HEAD, unstaging any // changes in the cache return fm.runGitResetHard() } func (fm *FileManager) CheckoutFiles() *Error { fm.Lock() defer fm.Unlock() // Now we remove the changes in the working copy, // by calling `git checkout .` return fm.runGitFilesCheckout() }