-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
198 lines (181 loc) · 4.89 KB
/
main.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
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
package main
import (
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gocarina/gocsv"
)
// AccountsFilingEntry is the source data structure for the accounts entry
// in the output CSV file
type AccountsFilingEntry struct {
RegistrationID string `xml:"CompaniesHouseRegisteredNumber" csv:"company_registration"`
Name string `xml:"EntityNames>EntityCurrentLegalName" csv:"name"`
ApprovalDate string `xml:"DateApproval" csv:"approval_date"`
Dormant string `xml:"CompanyDormant" csv:"dormant"`
PeriodEnd string `xml:"context[0]>period>endDate" csv:"-"`
AddressLine1 string `csv:"address_line_1"`
AddressLine2 string `csv:"address_line_2"`
CityOrTown string `csv:"city_or_town"`
PostCode string `csv:"post_code"`
}
func main() {
// ~16s without goroutines
// ~6s with goroutines
start := time.Now()
defer func() {
fmt.Printf("Program took %v\n", time.Since(start))
}()
// load arguments
argsWithoutProg := os.Args[1:]
inputDirPath := "data"
outputFilePath := "output.csv"
for index, value := range argsWithoutProg {
if index == 0 {
inputDirPath = value
}
if index == 1 {
outputFilePath = value
}
}
err := convertAccountsDirToFile(inputDirPath, outputFilePath)
if err != nil {
panic(err)
}
}
func convertAccountsDirToFile(inputDirPath string, outputFilePath string) error {
// load directory
dir, err := os.Open(inputDirPath)
if err != nil {
panic(err)
}
defer dir.Close()
files, err := dir.Readdirnames(-1)
if err != nil {
panic(err)
}
// open output file before processing to see if any errors
output, err := os.Create(outputFilePath)
if err != nil {
panic(err)
}
defer output.Close()
var results []AccountsFilingEntry
// split up IO jobs across a WaitGroup
var wg sync.WaitGroup
c := make(chan AccountsFilingEntry)
done := make(chan bool)
fileClose := make(chan io.ReadCloser)
go func() {
for {
select {
case <-done:
fmt.Println("Closing collector goroutine")
return
case res := <-c:
fmt.Println(res)
results = append(results, res)
case closeMe := <-fileClose:
// close the file descriptor
closeMe.Close()
}
}
}()
fmt.Printf("Processing %v files\n", len(files))
for _, fileName := range files {
f, err := os.Open(path.Join(inputDirPath, fileName))
if err != nil {
panic(err)
}
fileType, err := detectFileType(f)
if err != nil {
panic(err)
}
switch fileType {
case HTML:
wg.Add(1)
go getStuffFromHTMLInput(f, &wg, c, fileClose)
case XML:
wg.Add(1)
go getStuffFromXMLInput(f, &wg, c, fileClose)
}
}
wg.Wait()
done <- true
err = gocsv.MarshalFile(&results, output)
if err != nil {
panic(err)
}
fmt.Printf("Processed %v / %v\n", len(results), len(files))
fmt.Printf("Data Quality score: %v%%\n", calculateDataQuality(results))
return nil
}
func getStuffFromXMLInput(input io.ReadCloser, wg *sync.WaitGroup, c chan AccountsFilingEntry, closer chan io.ReadCloser) {
defer wg.Done()
var result AccountsFilingEntry
b, err := ioutil.ReadAll(input)
if err != nil {
panic(err)
}
if err := xml.Unmarshal(b, &result); err != nil {
panic(err)
}
if result.RegistrationID == "" || result.Name == "" {
fmt.Println(result)
panic(string(b))
}
c <- result
closer <- input
}
func getStuffFromHTMLInput(input io.ReadCloser, wg *sync.WaitGroup, c chan AccountsFilingEntry, closer chan io.ReadCloser) {
defer wg.Done()
var result AccountsFilingEntry
doc, err := goquery.NewDocumentFromReader(input)
if err != nil {
panic(err)
}
// use 'contains' - * operator to search through all prefixes
// Assume only one result
doc.Find("[name*=\":UKCompaniesHouseRegisteredNumber\"]").Each(func(i int, s *goquery.Selection) {
result.RegistrationID = s.Text()
})
doc.Find("[name*=\":EntityCurrentLegalOrRegisteredName\"]").Each(func(i int, s *goquery.Selection) {
result.Name = s.Text()
})
doc.Find("[name*=\":DateAuthorisationFinancialStatementsForIssue\"]").Each(func(i int, s *goquery.Selection) {
result.ApprovalDate = s.Text()
})
doc.Find("[name*=\":EntityDormantTruefalse\"]").Each(func(i int, s *goquery.Selection) {
result.Dormant = s.Text()
})
doc.Find("[name*=\":EndDateForPeriodCoveredByReport\"]").Each(func(i int, s *goquery.Selection) {
result.PeriodEnd = s.Text()
})
// Address
doc.Find("[name*=\"AddressLine1\"]").Each(func(i int, s *goquery.Selection) {
result.AddressLine1 = s.Text()
})
doc.Find("[name*=\"AddressLine2\"]").Each(func(i int, s *goquery.Selection) {
result.AddressLine2 = s.Text()
})
doc.Find("[name*=\"CityOrTown\"]").Each(func(i int, s *goquery.Selection) {
result.CityOrTown = s.Text()
})
doc.Find("[name*=\"PostalCode\"]").Each(func(i int, s *goquery.Selection) {
result.PostCode = s.Text()
})
if result.RegistrationID == "" || result.Name == "" {
html, err := doc.Html()
if err != nil {
panic(err)
}
panic(html)
}
c <- result
closer <- input
}