Repository navigation
Expand file tree
/
Copy pathDockerHubClient.ts
More file actions
83 lines (66 loc) · 2.48 KB
/
Copy pathDockerHubClient.ts
File metadata and controls
83 lines (66 loc) · 2.48 KB
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
import { URL } from 'url'
import { compare, validate } from 'compare-versions'
import { CreateLogger, CreateOptions } from '@nofrills/lincoln-debug'
import { Tag } from './Tag'
import { tagMap } from './TagMap'
import { tagSort } from './TagSort'
import { tagMatch } from './TagMatch'
import { TagMatcher } from './TagMatcher'
import { tagResolveAll } from './TagResolveAll'
import { Tags } from './Resources/Tags'
import { Namespaces } from './Resources/Namespaces'
import { Repositories } from './Resources/Repositories'
import { Authentication } from './Resources/Authentication'
const options = CreateOptions('dockerhub')
const logger = CreateLogger(options)
export class DockerHubClient {
private readonly matchers: Set<TagMatcher> = new Set<TagMatcher>()
auth: Authentication
namespaces: Namespaces
repositories: Repositories
tags: Tags
constructor(token?: string, version: number = 2) {
const endpoint = new URL(`https://hub.docker.com/v${version}`)
this.auth = new Authentication(endpoint, logger, (token) => {
const authtoken = `JWT ${token}`
this.namespaces.setAuthorization(authtoken)
this.repositories.setAuthorization(authtoken)
this.tags.setAuthorization(authtoken)
})
this.namespaces = new Namespaces(endpoint, logger)
this.repositories = new Repositories(endpoint, logger)
this.tags = new Tags(endpoint, logger)
if (token) {
this.auth.setToken(token)
}
}
match(matcher: TagMatcher): DockerHubClient {
this.matchers.add(matcher)
return this
}
async find(repository: string, reverse: boolean = false): Promise<Tag[]> {
const matchers = Array.from(this.matchers.values())
const source = await this.tags.list(repository)
this.matchers.clear()
return Promise.resolve(
matchers
.reduce<Tag[]>((tags, matcher) => tagMatch(tags, matcher), tagResolveAll(tagMap(source.results)))
.filter((tag) => tag.version)
.sort(tagSort(reverse)),
)
}
async latest(repository: string): Promise<Tag | null> {
const tags = await this.find(repository)
const latest = (source: Tag, target: Tag | null) => {
if (source.repotag.name === 'latest') {
return true
}
return target
? validate(source.repotag.name) &&
validate(target.repotag.name) &&
compare(source.repotag.name, target.repotag.name, '>')
: true
}
return tags.reduce<Tag | null>((result, tag) => (latest(tag, result) ? tag : result), null)
}
}