-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduleyear.go
102 lines (92 loc) · 2.36 KB
/
scheduleyear.go
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
package gamedayapi
import (
"bufio"
"bytes"
"io"
"log"
"os"
"path/filepath"
"sort"
"strconv"
s "strings"
"time"
)
// OpeningAndFinalDatesForYear will inspect the schedule for the year and return dates for opening day and the final
// day of the season
func OpeningAndFinalDatesForYear(year int) (time.Time, time.Time) { // return an error
var openingDay, finalDay time.Time
scheduleFilePath, err := scheduleFilePath(year)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(scheduleFilePath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
bf := bufio.NewReader(f)
firstLine, _ := bf.ReadString('\n')
openingDay = dateFromScheduleLine(firstLine)
for {
switch line, err := bf.ReadString('\n'); err {
case nil:
case io.EOF:
if line > "" {
finalDay = dateFromScheduleLine(line)
}
return openingDay, finalDay
default:
log.Fatal(err)
}
}
}
// TeamsForYear returns a list of valid team codes for the given year, sorted in alphabetical order.
func TeamsForYear(year int) []string {
teams := make([]string, 0, 30)
scheduleFilePath, err := scheduleFilePath(year)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(scheduleFilePath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
teamFromLine := firstTeamFromScheduleLine(line)
teams = appendIfMissing(teams, teamFromLine)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
sort.Strings(teams)
return teams
}
func scheduleFilePath(year int) (string, error) {
absPath, err := filepath.Abs("")
srcPos := s.Index(absPath, "/go/src/")
srcPath := absPath[0 : srcPos+8]
schedulePath := srcPath + "github.com/ecopony/gamedayapi/schedules"
if err != nil {
return "", err
}
var buffer bytes.Buffer
buffer.WriteString(schedulePath)
buffer.WriteString("/")
buffer.WriteString(strconv.Itoa(year))
buffer.WriteString("SKED.TXT")
return buffer.String(), nil
}
// Parses a line from the Retrosheet schedule files. Lines look like:
// "20110331","0","Thu","MIL","NL",1,"CIN","NL",1,"d","",""
func dateFromScheduleLine(line string) time.Time {
year, _ := strconv.Atoi(line[1:5])
month, _ := strconv.Atoi(line[5:7])
day, _ := strconv.Atoi(line[7:9])
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}
func firstTeamFromScheduleLine(line string) string {
return s.ToLower(line[22:25])
}