-
Notifications
You must be signed in to change notification settings - Fork 60
/
add-connection.ts
223 lines (202 loc) · 6.87 KB
/
add-connection.ts
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { Args, Flags } from '@oclif/core'
import fs from 'fs'
import path from 'path'
import parseJSON from 'json-parse-better-errors'
// locals
import fetch from '../fetchWithProxy'
import JBrowseCommand from '../base'
type Connection = Record<string, unknown>
interface Assembly {
name: string
sequence: Record<string, unknown>
}
interface Config {
assemblies?: Assembly[]
configuration?: {}
connections?: Connection[]
defaultSession?: {}
tracks?: unknown[]
}
export default class AddConnection extends JBrowseCommand {
// @ts-expect-error
private target: string
static description = 'Add a connection to a JBrowse 2 configuration'
static examples = [
'$ jbrowse add-connection http://mysite.com/jbrowse/data/ -a hg19',
'$ jbrowse add-connection http://mysite.com/jbrowse/custom_data_folder/ --type JBrowse1Connection -a hg38',
'$ jbrowse add-connection http://mysite.com/path/to/hub.txt',
'$ jbrowse add-connection http://mysite.com/path/to/custom_hub_name.txt --type UCSCTrackHubConnection',
`$ jbrowse add-connection http://mysite.com/path/to/custom --type custom --config '{"uri":{"url":"https://mysite.com/path/to/custom"}, "locationType": "UriLocation"}' -a hg19`,
'$ jbrowse add-connection https://mysite.com/path/to/hub.txt --connectionId newId --name newName --target /path/to/jb2/installation/config.json',
]
static args = {
connectionUrlOrPath: Args.string({
required: true,
description: `URL of data directory\nFor hub file, usually called hub.txt\nFor JBrowse 1, location of JB1 data directory similar to http://mysite.com/jbrowse/data/ `,
}),
}
static flags = {
type: Flags.string({
char: 't',
description:
'type of connection, ex. JBrowse1Connection, UCSCTrackHubConnection, custom',
}),
assemblyNames: Flags.string({
char: 'a',
description:
'For UCSC, optional: Comma separated list of assembly name(s) to filter from this connection. For JBrowse: a single assembly name',
}),
config: Flags.string({
char: 'c',
description: `Any extra config settings to add to connection in JSON object format, such as '{"uri":"url":"https://sample.com"}, "locationType": "UriLocation"}'`,
}),
connectionId: Flags.string({
description: `Id for the connection that must be unique to JBrowse. Defaults to 'connectionType-assemblyName-currentTime'`,
}),
name: Flags.string({
char: 'n',
description:
'Name of the connection. Defaults to connectionId if not provided',
}),
target: Flags.string({
description:
'path to config file in JB2 installation directory to write out to.',
}),
out: Flags.string({
description: 'synonym for target',
}),
help: Flags.help({ char: 'h' }),
skipCheck: Flags.boolean({
description:
"Don't check whether or not the data directory URL exists or if you are in a JBrowse directory",
}),
overwrite: Flags.boolean({
description: 'Overwrites any existing connections if same connection id',
}),
force: Flags.boolean({
char: 'f',
description: 'Equivalent to `--skipCheck --overwrite`',
}),
}
async run() {
const { args: runArgs, flags: runFlags } = await this.parse(AddConnection)
const output = runFlags.target || runFlags.out || '.'
const isDir = fs.lstatSync(output).isDirectory()
this.target = isDir ? `${output}/config.json` : output
const { connectionUrlOrPath } = runArgs
const { assemblyNames, type, name, config, connectionId } = runFlags
const { skipCheck, force } = runFlags
const url = await this.resolveURL(
connectionUrlOrPath,
!(skipCheck || force),
)
const configContents = await this.readJsonFile<Config>(this.target)
this.debug(`Using config file ${this.target}`)
if (!configContents.assemblies?.length) {
this.error(
'No assemblies found. Please add one before adding connections',
{ exit: 120 },
)
}
const configType = type || this.determineConnectionType(url)
const id =
connectionId ||
[configType, assemblyNames, +Date.now()].filter(f => !!f).join('-')
const connectionConfig = {
type: configType,
name: name || id,
...(configType === 'UCSCTrackHubConnection'
? {
hubTxtLocation: {
uri: url,
locationType: 'UriLocation',
},
}
: {}),
...(configType === 'JBrowse1Connection'
? {
dataDirLocation: {
uri: url,
locationType: 'UriLocation',
},
}
: {}),
connectionId: id,
assemblyNames: assemblyNames
? assemblyNames.split(',')
: type === 'JBrowse1Connection'
? [configContents.assemblies[0]?.name]
: undefined,
...(config ? parseJSON(config) : {}),
}
if (!configContents.connections) {
configContents.connections = []
}
const idx = configContents.connections.findIndex(
c => c.connectionId === connectionId,
)
if (idx !== -1) {
if (runFlags.force || runFlags.overwrite) {
configContents.connections[idx] = connectionConfig
} else {
this.error(
`Cannot add connection with id ${connectionId}, a connection with that id already exists.\nUse --overwrite if you would like to replace the existing connection`,
{ exit: 150 },
)
}
} else {
configContents.connections.push(connectionConfig)
}
this.debug(`Writing configuration to file ${this.target}`)
await this.writeJsonFile(this.target, configContents)
this.log(
`${idx !== -1 ? 'Overwrote' : 'Added'} connection "${name}" ${
idx !== -1 ? 'in' : 'to'
} ${this.target}`,
)
}
async resolveURL(location: string, check = true) {
let locationUrl: URL | undefined
try {
locationUrl = new URL(location)
} catch (error) {
this.error('The location provided is not a valid URL', { exit: 160 })
}
if (locationUrl) {
let response
try {
if (check) {
// @ts-expect-error
response = await fetch(locationUrl, { method: 'HEAD' })
}
if (!response || response.ok) {
return locationUrl.href
}
this.error(`Response returned with code ${response.status}`)
} catch (error) {
// ignore
this.error(`Unable to fetch from URL, ${error}`, { exit: 170 })
}
}
return this.error(`Could not resolve to a URL: "${location}"`, {
exit: 180,
})
}
determineConnectionType(url: string) {
if (path.basename(url) === 'hub.txt') {
return 'UCSCTrackHubConnection'
}
if (url.includes('jbrowse/data')) {
return 'JBrowse1Connection'
}
return 'custom'
}
isValidJSON(str: string) {
try {
JSON.parse(str)
return true
} catch (error) {
return false
}
}
}