Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added a clashes command #532

Merged
merged 1 commit into from
Dec 26, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
- [Help](#help)
- [Move](#move)
- [Rename](#rename)
- [Clashes](#clashes)
- [DriveIgnore](#driveignore)
- [DriveRC](#driverc)
- [DesktopEntry](#desktopentry)
Expand Down Expand Up @@ -847,6 +848,22 @@ $ drive rename openSrc/2015 2015-Contributions
$ drive rename 0fM9rt0Yc9RTPeHRfRHRRU0dIY97 fluxing
```

### Clashes

You can deal with clashes by using command `drive clashes`.

* To list clashes, you can do

```shell
$ drive clashes [paths...]
$ drive clashes --list [paths...] # To be more explicit
```

* To fix clashes, you can do:

```
$ drive clashes --fix [paths...]
```

### Move

Expand Down
48 changes: 48 additions & 0 deletions cmd/drive/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func main() {
bindCommandWithAliases(drive.DuKey, drive.DescDu, &duCmd{}, []string{})
bindCommandWithAliases(drive.StarKey, drive.DescStar, &starCmd{}, []string{})
bindCommandWithAliases(drive.UnStarKey, drive.DescUnStar, &unstarCmd{}, []string{})
bindCommandWithAliases(drive.ClashesKey, drive.DescFixClashes, &clashesCmd{}, []string{})

command.DefineHelp(&helpCmd{})
command.ParseAndRun()
Expand Down Expand Up @@ -1528,6 +1529,53 @@ func (cmd *unstarCmd) Run(args []string, definedFlags map[string]*flag.Flag) {
exitWithError(drive.New(context, opts).UnStar(*cmd.ById))
}

type clashesCmd struct {
Fix *bool `json:"fix"`
List *bool `json:"list"`
ById *bool `json:"by-id"`
Depth *int `json:"depth"`
Hidden *bool `json:"hidden"`
}

func (cmd *clashesCmd) Flags(fs *flag.FlagSet) *flag.FlagSet {
cmd.Fix = fs.Bool(drive.CLIOptionFixClashes, false, drive.DescFixClashes)
cmd.List = fs.Bool(drive.CLIOptionListClashes, true, drive.DescListClashes)
cmd.ById = fs.Bool(drive.CLIOptionId, false, drive.DescClashesOpById)
cmd.Depth = fs.Int(drive.DepthKey, drive.InfiniteDepth, "maximum recursion depth")
cmd.Hidden = fs.Bool(drive.HiddenKey, true, "allows operation on hidden paths")

return fs
}

func (ccmd *clashesCmd) Run(args []string, definedFlags map[string]*flag.Flag) {
sources, context, path := preprocessArgsByToggle(args, *ccmd.ById)
cmd := clashesCmd{}
df := defaultsFiller{
from: *ccmd, to: &cmd,
rcSourcePath: context.AbsPathOf(path),
definedFlags: definedFlags,
}

if err := fillWithDefaults(df); err != nil {
exitWithError(err)
}

opts := &drive.Options{
Path: path,
Sources: sources,
Depth: *cmd.Depth,
Hidden: *cmd.Hidden,
}

driveInstance := drive.New(context, opts)
fn := driveInstance.ListClashes
if *cmd.Fix {
fn = driveInstance.FixClashes
}

exitWithError(fn(*cmd.ById))
}

func initContext(args []string) *config.Context {
var err error
var gdPath string
Expand Down
234 changes: 234 additions & 0 deletions src/clashes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package drive

import (
"fmt"
"path/filepath"
"strings"
)

func (g *Commands) ListClashes(byId bool) error {
clashes, err := listClashes(g, g.opts.Sources, byId)
if len(clashes) < 1 {
if err == nil {
return fmt.Errorf("no clashes exist!")
} else {
return err
}
}

if err != nil && err != ErrClashesDetected {
return err
}

warnClashesPersist(g.log, clashes)
return nil
}

func (g *Commands) FixClashes(byId bool) error {
clashes, err := listClashes(g, g.opts.Sources, byId)

if len(clashes) < 1 {
return err
}

if err != nil && err != ErrClashesDetected {
return err
}

return autoRenameClashes(g, clashes)
}

func findClashesForChildren(g *Commands, parentId, relToRootPath string, depth int) (clashes []*Change, err error) {
if depth == 0 {
return
}

memoized := map[string][]*File{}
children := g.rem.FindByParentId(parentId, g.opts.Hidden)
decrementedDepth := decrementTraversalDepth(depth)

discoveryOrder := []string{}
for child := range children {
if child == nil {
continue
}
cluster, alreadyDiscovered := memoized[child.Name]
if !alreadyDiscovered {
discoveryOrder = append(discoveryOrder, child.Name)
}

cluster = append(cluster, child)
memoized[child.Name] = cluster
}

// To preserve the discovery order
for _, commonKey := range discoveryOrder {
cluster, _ := memoized[commonKey]
fullRelToRootPath := sepJoin(RemoteSeparator, relToRootPath, commonKey)
nameClashesPresent := len(cluster) > 1

for _, rem := range cluster {
if nameClashesPresent {
change := &Change{
Src: rem, g: g,
Path: fullRelToRootPath,
Parent: g.opts.Path,
}

clashes = append(clashes, change)
}

ccl, cErr := findClashesForChildren(g, rem.Id, fullRelToRootPath, decrementedDepth)
clashes = append(clashes, ccl...)
if cErr != nil {
err = reComposeError(err, cErr.Error())
}
}
}

return
}

func findClashesByPath(g *Commands, relToRootPath string, depth int) (clashes []*Change, err error) {
if depth == 0 {
return
}

remotes := g.rem.FindByPathM(relToRootPath)

iterCount := uint64(0)
clashThresholdCount := uint64(1)

cl := []*Change{}

for rem := range remotes {
if rem == nil {
continue
}

iterCount++

change := &Change{
Src: rem, g: g,
Path: relToRootPath,
Parent: g.opts.Path,
}

cl = append(cl, change)
}

if iterCount > clashThresholdCount {
clashes = append(clashes, cl...)
}

decrementedDepth := decrementTraversalDepth(depth)
if decrementedDepth == 0 {
return
}

for _, change := range cl {
ccl, cErr := findClashesForChildren(g, change.Src.Id, change.Path, decrementedDepth)
if cErr != nil {
err = reComposeError(err, cErr.Error())
}

clashes = append(clashes, ccl...)
}

return
}

func listClashes(g *Commands, sources []string, byId bool) (clashes []*Change, err error) {
for _, relToRootPath := range g.opts.Sources {
cclashes, cErr := findClashesByPath(g, relToRootPath, g.opts.Depth)

clashes = append(clashes, cclashes...)

if cErr != nil {
err = reComposeError(err, cErr.Error())
}
}

return
}

func autoRenameClashes(g *Commands, clashes []*Change) error {
clashesMap := map[string][]*Change{}

for _, clash := range clashes {
group := clashesMap[clash.Path]
if clash.Src == nil {
continue
}
clashesMap[clash.Path] = append(group, clash)
}

renames := make([]renameOp, 0, len(clashesMap)) // we will have at least len(clashesMap) renames

for commonPath, group := range clashesMap {
ext := filepath.Ext(commonPath)
name := strings.TrimSuffix(commonPath, ext)
nextIndex := 0

for i, n := 1, len(group); i < n; i++ { // we can leave first item with original name
var newName string
for {
newName = fmt.Sprintf("%v_%d%v", name, nextIndex, ext)
nextIndex++

dupCheck, err := g.rem.FindByPath(newName)
if err != nil && err != ErrPathNotExists {
return err
}

if dupCheck == nil {
newName = filepath.Base(newName)
break
}
}

r := renameOp{newName: newName, change: group[i], originalPath: commonPath}
renames = append(renames, r)
}
}

if g.opts.canPrompt() {
g.log.Logln("Some clashes found, we can fix them by following renames:")
for _, r := range renames {
g.log.Logf("%v %v -> %v\n", r.originalPath, r.change.Src.Id, r.newName)
}
status := promptForChanges("Proceed with the changes [Y/N] ? ")
if !accepted(status) {
return ErrClashFixingAborted
}
}

var composedError error

for _, r := range renames {
message := fmt.Sprintf("Renaming %s %v -> %s\n", r.originalPath, r.change.Src.Id, r.newName)
_, err := g.rem.rename(r.change.Src.Id, r.newName)
if err == nil {
g.log.Log(message)
continue
}

composedError = reComposeError(composedError, fmt.Sprintf("%s err: %v", message, err))
}

return composedError
}
5 changes: 5 additions & 0 deletions src/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ const (
ExcludeOpsKey = "exclude-ops"
IgnoreConflictKey = "ignore-conflict"
IgnoreNameClashesKey = "ignore-name-clashes"
ClashesKey = "clashes"
CommentStr = "#"
DepthKey = "depth"
EmailsKey = "emails"
Expand Down Expand Up @@ -171,11 +172,13 @@ const (
DescUrl = "returns the remote URL of each file"
DescVerbose = "show step by step information verbosely"
DescFixClashes = "fix clashes by renaming files"
DescListClashes = "list clashes"
DescDescription = "set the description"
DescQR = "open up the QR code for specified files"
DescStarred = "operate only on starred files"
DescUnifiedDiff = "unified diff"
DescDiffBaseLocal = "when set uses local as the base other remote will be used as the base"
DescClashesOpById = "operate on clashes by id instead of by path"
)

const (
Expand Down Expand Up @@ -213,6 +216,8 @@ const (
CLIOptionUnified = "unified"
CLIOptionUnifiedShortKey = "u"
CLIOptionDiffBaseLocal = "base-local"
CLIOptionFixClashes = "fix"
CLIOptionListClashes = "list"
)

const (
Expand Down
Loading