File: resources.go

package info (click to toggle)
aptly 1.6.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 49,928 kB
  • sloc: python: 10,398; sh: 252; makefile: 184
file content (106 lines) | stat: -rw-r--r-- 2,354 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package task

import (
	"strings"
)

// AllLocalReposResourcesKey to be used as resource key when all local repos are needed
const AllLocalReposResourcesKey = "__alllocalrepos__"

// AllResourcesKey to be used as resource key when all resources are needed
const AllResourcesKey = "__all__"

// ResourceConflictError represents a list tasks
// using conflicitng resources
type ResourceConflictError struct {
	Tasks   []Task
	Message string
}

func (e *ResourceConflictError) Error() string {
	return e.Message
}

// ResourcesSet represents a set of task resources.
// A resource is represented by its unique key
type ResourcesSet struct {
	set map[string]*Task
}

// NewResourcesSet creates new instance of resources set
func NewResourcesSet() *ResourcesSet {
	return &ResourcesSet{make(map[string]*Task)}
}

// MarkInUse given resources as used by given task
func (r *ResourcesSet) MarkInUse(resources []string, task *Task) {
	for _, resource := range resources {
		r.set[resource] = task
	}
}

// UsedBy checks whether one of given resources
// is used by a task and if yes returns slice of such task
func (r *ResourcesSet) UsedBy(resources []string) []Task {
	var tasks []Task
	var task *Task
	var found bool

	for _, resource := range resources {

		if resource == AllLocalReposResourcesKey {
			for taskResource, task := range r.set {
				if strings.HasPrefix(taskResource, "L") {
					tasks = appendTask(tasks, task)
				}
			}
		} else if resource == AllResourcesKey {
			for _, task := range r.set {
				tasks = appendTask(tasks, task)
			}

			break
		}

		task, found = r.set[resource]
		if found {
			tasks = appendTask(tasks, task)
		}
	}

	task, found = r.set[AllLocalReposResourcesKey]
	if found {
		tasks = appendTask(tasks, task)
	}
	task, found = r.set[AllResourcesKey]
	if found {
		tasks = appendTask(tasks, task)
	}

	return tasks
}

// appendTask only appends task to tasks slice if not already
// on slice
func appendTask(tasks []Task, task *Task) []Task {
	needsAppending := true
	for _, givenTask := range tasks {
		if givenTask.ID == task.ID {
			needsAppending = false
			break
		}
	}

	if needsAppending {
		return append(tasks, *task)
	}

	return tasks
}

// Free removes given resources from dependency set
func (r *ResourcesSet) Free(resources []string) {
	for _, resource := range resources {
		delete(r.set, resource)
	}
}