예제 #1
0
파일: lst.go 프로젝트: tgrijalva/lst
func mv(l *list.List, args []string) {
	switch len(args) {
	case 0:
		fmt.Println("What item do you want to move?")
		os.Exit(1)
	case 1:
		fmt.Println("Too few arguments.")
		os.Exit(1)
	case 2:
		// Check if remaining args are integers
		nums := make([]int, len(args))
		for i, a := range args {
			n, err := strconv.Atoi(a)
			if err != nil {
				fmt.Printf("%q is not an item number.\n", a)
				os.Exit(1)
			}
			nums[i] = n
		}

		// Make sure integers is not out of bounds
		if max(nums...) > l.Len() {
			fmt.Printf("item [%d] is out of bounds.\n", max(nums...))
			os.Exit(1)
		} else if min(nums...) < 1 {
			fmt.Printf("item [%d] is out of bounds.\n", min(nums...))
			os.Exit(1)
		} else if nums[0] == nums[1] { // Make sure numbers are different
			fmt.Println("Item alread in place.")
			os.Exit(1)
		}

		// Collect elements
		elements := make([]*list.Element, len(nums))
		itemNumber, element := 1, l.Front()
		for itemNumber <= max(nums...) {
			if itemNumber == nums[0] {
				elements[0] = element
			}
			if itemNumber == nums[1] {
				elements[1] = element
			}
			element = element.Next()
			itemNumber++
		}

		// Update date
		elements[0].Value.(ListItem)[DATE] = time.Now().Format(DATE_FORMAT)

		// Move item
		if nums[0] < nums[1] { // Use moveAfter
			l.MoveAfter(elements[0], elements[1])
		} else { // Use moveBefore
			l.MoveBefore(elements[0], elements[1])
		}
		fmt.Printf("Moving item:[%d] to location:[%d]\n", nums[0], nums[1])

	default:
		fmt.Println("Too many arguments.")
		os.Exit(1)
	}
}