| 1 | // Copyright ©2012 The bíogo Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package sam |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "encoding/binary" |
| 10 | "encoding/hex" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "net/url" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "time" |
| 18 | ) |
| 19 | |
| 20 | var ( |
| 21 | errBadHeader = errors.New("sam: malformed header line") |
| 22 | errDupTag = errors.New("sam: duplicate field") |
| 23 | ) |
| 24 | |
| 25 | var bamMagic = [4]byte{'B', 'A', 'M', 0x1} |
| 26 | |
| 27 | // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. |
| 28 | func (bh *Header) UnmarshalBinary(b []byte) error { |
| 29 | return bh.DecodeBinary(bytes.NewReader(b)) |
| 30 | } |
| 31 | |
| 32 | // DecodeBinary unmarshals a Header from the given io.Reader. The byte |
| 33 | // stream must be in the format described in the SAM specification, |
| 34 | // section 4.2. |
| 35 | func (bh *Header) DecodeBinary(r io.Reader) error { |
| 36 | var ( |
| 37 | lText, nRef int32 |
| 38 | err error |
| 39 | ) |
| 40 | var magic [4]byte |
| 41 | err = binary.Read(r, binary.LittleEndian, &magic) |
| 42 | if err != nil { |
| 43 | return err |
| 44 | } |
| 45 | if magic != bamMagic { |
| 46 | return errors.New("sam: magic number mismatch") |
| 47 | } |
| 48 | err = binary.Read(r, binary.LittleEndian, &lText) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | if lText < 0 { |
| 53 | return errors.New("sam: invalid text length") |
| 54 | } |
| 55 | text := make([]byte, lText) |
| 56 | n, err := r.Read(text) |
| 57 | if err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if n != int(lText) { |
| 61 | return errors.New("sam: truncated header") |
| 62 | } |
| 63 | err = bh.UnmarshalText(text) |
| 64 | if err != nil { |
| 65 | return err |
| 66 | } |
| 67 | err = binary.Read(r, binary.LittleEndian, &nRef) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if nRef < 0 { |
| 72 | return errors.New("sam: invalid reference count field") |
| 73 | } |
| 74 | refs, err := readRefRecords(r, nRef) |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | for _, r := range refs { |
| 79 | err = bh.AddReference(r) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | } |
| 84 | return nil |
| 85 | } |
| 86 | |
| 87 | func readRefRecords(r io.Reader, n int32) ([]*Reference, error) { |
| 88 | // bootstrapSize is the maximum number of |
| 89 | // reference records to pre-allocate. |
| 90 | const bootstrapSize = 1000 |
| 91 | |
| 92 | rr := make([]*Reference, 0, min(n, bootstrapSize)) |
| 93 | var ( |
| 94 | lName int32 |
| 95 | err error |
| 96 | ) |
| 97 | for i := 0; i < int(n); i++ { |
| 98 | rr = append(rr, &Reference{id: int32(i)}) |
| 99 | err = binary.Read(r, binary.LittleEndian, &lName) |
| 100 | if err != nil { |
| 101 | return nil, err |
| 102 | } |
| 103 | if lName < 1 { |
| 104 | return nil, errors.New("sam: invalid name length") |
| 105 | } |
| 106 | name := make([]byte, lName) |
| 107 | n, err := r.Read(name) |
| 108 | if err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | if n != int(lName) || name[n-1] != 0 { |
| 112 | return nil, errors.New("sam: truncated reference name") |
| 113 | } |
| 114 | rr[i].name = string(name[:n-1]) |
| 115 | err = binary.Read(r, binary.LittleEndian, &rr[i].lRef) |
| 116 | if err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | } |
| 120 | return rr, nil |
| 121 | } |
| 122 | |
| 123 | func min(a, b int32) int32 { |
| 124 | if a < b { |
| 125 | return a |
| 126 | } |
| 127 | return b |
| 128 | } |
| 129 | |
| 130 | // UnmarshalText implements the encoding.TextUnmarshaler interface. |
| 131 | func (bh *Header) UnmarshalText(text []byte) error { |
| 132 | if bh.seenRefs == nil { |
| 133 | bh.seenRefs = set{} |
| 134 | } |
| 135 | if bh.seenGroups == nil { |
| 136 | bh.seenGroups = set{} |
| 137 | } |
| 138 | if bh.seenProgs == nil { |
| 139 | bh.seenProgs = set{} |
| 140 | } |
| 141 | var t Tag |
| 142 | for i, l := range bytes.Split(text, []byte{'\n'}) { |
| 143 | if len(l) > 0 && l[len(l)-1] == '\r' { |
| 144 | l = l[:len(l)-1] |
| 145 | } |
| 146 | if len(l) == 0 { |
| 147 | continue |
| 148 | } |
| 149 | if l[0] != '@' || len(l) < 3 { |
| 150 | return errBadHeader |
| 151 | } |
| 152 | copy(t[:], l[1:3]) |
| 153 | var err error |
| 154 | switch t { |
| 155 | case headerTag: |
| 156 | err = headerLine(l, bh) |
| 157 | case refDictTag: |
| 158 | err = referenceLine(l, bh) |
| 159 | case readGroupTag: |
| 160 | err = readGroupLine(l, bh) |
| 161 | case programTag: |
| 162 | err = programLine(l, bh) |
| 163 | case commentTag: |
| 164 | err = commentLine(l, bh) |
| 165 | default: |
| 166 | return errBadHeader |
| 167 | } |
| 168 | if err != nil { |
| 169 | return fmt.Errorf("%w: line %d: %q", err, i+1, l) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | return nil |
| 174 | } |
| 175 | |
| 176 | func headerLine(l []byte, bh *Header) error { |
| 177 | fields := bytes.Split(l, []byte{'\t'}) |
| 178 | if len(fields) < 2 { |
| 179 | return errBadHeader |
| 180 | } |
| 181 | |
| 182 | var t Tag |
| 183 | for _, f := range fields[1:] { |
| 184 | if f[2] != ':' { |
| 185 | return errBadHeader |
| 186 | } |
| 187 | copy(t[:], f[:2]) |
| 188 | fs := string(f[3:]) |
| 189 | switch t { |
| 190 | case versionTag: |
| 191 | if bh.Version != "" { |
| 192 | return errBadHeader |
| 193 | } |
| 194 | bh.Version = fs |
| 195 | case sortOrderTag: |
| 196 | if bh.SortOrder != UnknownOrder { |
| 197 | return errBadHeader |
| 198 | } |
| 199 | bh.SortOrder = sortOrderMap[fs] |
| 200 | case groupOrderTag: |
| 201 | if bh.GroupOrder != GroupUnspecified { |
| 202 | return errBadHeader |
| 203 | } |
| 204 | bh.GroupOrder = groupOrderMap[fs] |
| 205 | default: |
| 206 | bh.otherTags = append(bh.otherTags, tagPair{tag: t, value: fs}) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | if bh.Version == "" { |
| 211 | return errBadHeader |
| 212 | } |
| 213 | |
| 214 | return nil |
| 215 | } |
| 216 | |
| 217 | func referenceLine(l []byte, bh *Header) error { |
| 218 | fields := bytes.Split(l, []byte{'\t'}) |
| 219 | if len(fields) < 3 { |
| 220 | return errBadHeader |
| 221 | } |
| 222 | |
| 223 | var ( |
| 224 | t Tag |
| 225 | rf = &Reference{} |
| 226 | seen = map[Tag]struct{}{} |
| 227 | nok, lok bool |
| 228 | dupID int32 |
| 229 | dup bool |
| 230 | ) |
| 231 | |
| 232 | for _, f := range fields[1:] { |
| 233 | if f[2] != ':' { |
| 234 | return errBadHeader |
| 235 | } |
| 236 | copy(t[:], f[:2]) |
| 237 | if _, ok := seen[t]; ok { |
| 238 | return errDupTag |
| 239 | } |
| 240 | seen[t] = struct{}{} |
| 241 | fs := string(f[3:]) |
| 242 | switch t { |
| 243 | case refNameTag: |
| 244 | dupID, dup = bh.seenRefs[fs] |
| 245 | rf.name = fs |
| 246 | nok = true |
| 247 | case refLengthTag: |
| 248 | l, err := strconv.Atoi(fs) |
| 249 | if err != nil { |
| 250 | return errBadHeader |
| 251 | } |
| 252 | if !validLen(l) { |
| 253 | return errBadLen |
| 254 | } |
| 255 | rf.lRef = int32(l) |
| 256 | lok = true |
| 257 | case assemblyIDTag: |
| 258 | rf.assemID = fs |
| 259 | case md5Tag: |
| 260 | hb := [16]byte{} |
| 261 | n, err := hex.Decode(hb[:], f[3:]) |
| 262 | if err != nil { |
| 263 | return err |
| 264 | } |
| 265 | if n != 16 { |
| 266 | return errBadHeader |
| 267 | } |
| 268 | rf.md5 = string(hb[:]) |
| 269 | case speciesTag: |
| 270 | rf.species = fs |
| 271 | case uriTag: |
| 272 | var err error |
| 273 | rf.uri, err = url.Parse(fs) |
| 274 | if err != nil { |
| 275 | return err |
| 276 | } |
| 277 | if rf.uri.Scheme != "http" && rf.uri.Scheme != "ftp" { |
| 278 | rf.uri.Scheme = "file" |
| 279 | } |
| 280 | default: |
| 281 | rf.otherTags = append(rf.otherTags, tagPair{tag: t, value: fs}) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | if dup { |
| 286 | if er := bh.refs[dupID]; equalRefs(er, rf) { |
| 287 | return nil |
| 288 | } else if !equalRefs(er, &Reference{id: er.id, name: er.name, lRef: er.lRef}) { |
| 289 | return errDupReference |
| 290 | } |
| 291 | old := bh.refs[dupID] |
| 292 | old.owner = nil |
| 293 | old.id = -1 |
| 294 | bh.refs[dupID] = rf |
| 295 | rf.owner = bh |
| 296 | return nil |
| 297 | } |
| 298 | if !nok || !lok { |
| 299 | return errBadHeader |
| 300 | } |
| 301 | id := int32(len(bh.refs)) |
| 302 | rf.owner = bh |
| 303 | rf.id = id |
| 304 | bh.seenRefs[rf.name] = id |
| 305 | bh.refs = append(bh.refs, rf) |
| 306 | |
| 307 | return nil |
| 308 | } |
| 309 | |
| 310 | // http://en.wikipedia.org/wiki/ISO_8601 |
| 311 | // |
| 312 | // Date: 2014-08-13 |
| 313 | // Time: 2014-08-13T16:02:01Z |
| 314 | // : 2014-08-13T16:02:01 |
| 315 | // : 2014-08-13T16:02:01+00:00 |
| 316 | // : 2014-08-13T16:02:01.000+00:00 |
| 317 | const ( |
| 318 | // This is the ISO8601 format used for output. |
| 319 | iso8601TimeDateN = "2006-01-02T15:04:05-0700" |
| 320 | |
| 321 | // This is the set of ISO8601 formats we accept. |
| 322 | // The input values are first converted to a |
| 323 | // basic ISO8601 form by removing all ':' |
| 324 | // characters. We cannot do the same thing with |
| 325 | // '-' since this has two meanings in ISO8601, |
| 326 | // a separator and a negative time zone offset. |
| 327 | iso8601DateB = "20060102" |
| 328 | iso8601DateE = "2006-01-02" |
| 329 | iso8601TimeDateB = "20060102T150405" |
| 330 | iso8601TimeDateE = "2006-01-02T150405" |
| 331 | iso8601TimeDateZB = "20060102T150405Z" |
| 332 | iso8601TimeDateZE = "2006-01-02T150405Z" |
| 333 | iso8601TimeDateNB = "20060102T150405-0700" |
| 334 | iso8601TimeDateNE = "2006-01-02T150405-0700" |
| 335 | iso8601TimeThouDateZB = "20060102T150405.999Z" |
| 336 | iso8601TimeThouDateZE = "2006-01-02T150405.999Z" |
| 337 | iso8601TimeThouDateNB = "20060102T150405.999-0700" |
| 338 | iso8601TimeThouDateNE = "2006-01-02T150405.999-0700" |
| 339 | ) |
| 340 | |
| 341 | var iso8601 = []struct { |
| 342 | isLocal bool |
| 343 | format string |
| 344 | }{ |
| 345 | {isLocal: true, format: iso8601DateB}, |
| 346 | {isLocal: true, format: iso8601DateE}, |
| 347 | {isLocal: false, format: iso8601TimeDateZB}, |
| 348 | {isLocal: false, format: iso8601TimeDateZE}, |
| 349 | {isLocal: false, format: iso8601TimeDateNB}, |
| 350 | {isLocal: false, format: iso8601TimeDateNE}, |
| 351 | {isLocal: false, format: iso8601TimeThouDateZB}, |
| 352 | {isLocal: false, format: iso8601TimeThouDateZE}, |
| 353 | {isLocal: false, format: iso8601TimeThouDateNB}, |
| 354 | {isLocal: false, format: iso8601TimeThouDateNE}, |
| 355 | {isLocal: true, format: iso8601TimeDateB}, |
| 356 | {isLocal: true, format: iso8601TimeDateE}, |
| 357 | } |
| 358 | |
| 359 | func parseISO8601(value string) (time.Time, error) { |
| 360 | value = strings.Replace(value, ":", "", -1) |
| 361 | var err error |
| 362 | for _, format := range iso8601 { |
| 363 | loc := time.UTC |
| 364 | if format.isLocal { |
| 365 | loc = time.Local |
| 366 | } |
| 367 | var t time.Time |
| 368 | t, err = time.ParseInLocation(format.format, value, loc) |
| 369 | if err == nil { |
| 370 | return t, nil |
| 371 | } |
| 372 | } |
| 373 | return time.Time{}, err |
| 374 | } |
| 375 | |
| 376 | func readGroupLine(l []byte, bh *Header) error { |
| 377 | fields := bytes.Split(l, []byte{'\t'}) |
| 378 | if len(fields) < 2 { |
| 379 | return errBadHeader |
| 380 | } |
| 381 | |
| 382 | var ( |
| 383 | t Tag |
| 384 | rg = &ReadGroup{} |
| 385 | seen = map[Tag]struct{}{} |
| 386 | idok bool |
| 387 | ) |
| 388 | |
| 389 | for _, f := range fields[1:] { |
| 390 | if f[2] != ':' { |
| 391 | return errBadHeader |
| 392 | } |
| 393 | copy(t[:], f[:2]) |
| 394 | if _, ok := seen[t]; ok { |
| 395 | return errDupTag |
| 396 | } |
| 397 | seen[t] = struct{}{} |
| 398 | fs := string(f[3:]) |
| 399 | switch t { |
| 400 | case idTag: |
| 401 | if _, ok := bh.seenGroups[fs]; ok { |
| 402 | return errDupReadGroup |
| 403 | } |
| 404 | rg.name = fs |
| 405 | idok = true |
| 406 | case centerTag: |
| 407 | rg.center = fs |
| 408 | case descriptionTag: |
| 409 | rg.description = fs |
| 410 | case dateTag: |
| 411 | var err error |
| 412 | rg.date, err = parseISO8601(fs) |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | case flowOrderTag: |
| 417 | rg.flowOrder = fs |
| 418 | case keySequenceTag: |
| 419 | rg.keySeq = fs |
| 420 | case libraryTag: |
| 421 | rg.library = fs |
| 422 | case programTag: |
| 423 | rg.program = fs |
| 424 | case insertSizeTag: |
| 425 | i, err := strconv.Atoi(fs) |
| 426 | if err != nil { |
| 427 | return err |
| 428 | } |
| 429 | if !validInt32(i) { |
| 430 | return errBadLen |
| 431 | } |
| 432 | rg.insertSize = i |
| 433 | case platformTag: |
| 434 | rg.platform = fs |
| 435 | case platformUnitTag: |
| 436 | rg.platformUnit = fs |
| 437 | case sampleTag: |
| 438 | rg.sample = fs |
| 439 | default: |
| 440 | rg.otherTags = append(rg.otherTags, tagPair{tag: t, value: fs}) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | if !idok { |
| 445 | return errBadHeader |
| 446 | } |
| 447 | id := int32(len(bh.rgs)) |
| 448 | rg.owner = bh |
| 449 | rg.id = id |
| 450 | bh.seenGroups[rg.name] = id |
| 451 | bh.rgs = append(bh.rgs, rg) |
| 452 | |
| 453 | return nil |
| 454 | } |
| 455 | |
| 456 | func programLine(l []byte, bh *Header) error { |
| 457 | fields := bytes.Split(l, []byte{'\t'}) |
| 458 | if len(fields) < 2 { |
| 459 | return errBadHeader |
| 460 | } |
| 461 | |
| 462 | var ( |
| 463 | t Tag |
| 464 | p = &Program{} |
| 465 | seen = map[Tag]struct{}{} |
| 466 | idok bool |
| 467 | ) |
| 468 | |
| 469 | for _, f := range fields[1:] { |
| 470 | if f[2] != ':' { |
| 471 | return errBadHeader |
| 472 | } |
| 473 | copy(t[:], f[:2]) |
| 474 | if _, ok := seen[t]; ok { |
| 475 | return errDupTag |
| 476 | } |
| 477 | seen[t] = struct{}{} |
| 478 | fs := string(f[3:]) |
| 479 | switch t { |
| 480 | case idTag: |
| 481 | if _, ok := bh.seenProgs[fs]; ok { |
| 482 | return errDupProgram |
| 483 | } |
| 484 | p.uid = fs |
| 485 | idok = true |
| 486 | case programNameTag: |
| 487 | p.name = fs |
| 488 | case commandLineTag: |
| 489 | p.command = fs |
| 490 | case previousProgTag: |
| 491 | p.previous = fs |
| 492 | case versionTag: |
| 493 | p.version = fs |
| 494 | default: |
| 495 | p.otherTags = append(p.otherTags, tagPair{tag: t, value: fs}) |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | if !idok { |
| 500 | return errBadHeader |
| 501 | } |
| 502 | id := int32(len(bh.progs)) |
| 503 | p.owner = bh |
| 504 | p.id = id |
| 505 | bh.seenProgs[p.uid] = id |
| 506 | bh.progs = append(bh.progs, p) |
| 507 | |
| 508 | return nil |
| 509 | } |
| 510 | |
| 511 | func commentLine(l []byte, bh *Header) error { |
| 512 | fields := bytes.Split(l, []byte{'\t'}) |
| 513 | if len(fields) < 2 { |
| 514 | return errBadHeader |
| 515 | } |
| 516 | bh.Comments = append(bh.Comments, string(fields[1])) |
| 517 | return nil |
| 518 | } |