fixed some go vet warnings, fixed formatting

This commit is contained in:
Bora Alper 2018-08-03 15:40:04 +03:00
parent e4bb7b5b35
commit 4b9b354171
16 changed files with 173 additions and 138 deletions

View File

@ -7,3 +7,16 @@ magneticow:
# TODO: minify files!
go-bindata -o="magneticow/bindata.go" -prefix="magneticow/data/" magneticow/data/...
go install magnetico/magneticow
test:
go test github.com/boramalper/magnetico/cmd/magneticod/...
@echo
go test github.com/boramalper/magnetico/cmd/magneticow/...
@echo
go test github.com/boramalper/magnetico/pkg/persistence/...
format:
gofmt -w cmd/magneticod
gofmt -w cmd/magneticow
gofmt -w pkg/persistence

View File

@ -86,7 +86,9 @@ func (l *Leech) doBtHandshake() error {
))
// ASSERTION
if len(lHandshake) != 68 { panic(fmt.Sprintf("len(lHandshake) == %d", len(lHandshake))) }
if len(lHandshake) != 68 {
panic(fmt.Sprintf("len(lHandshake) == %d", len(lHandshake)))
}
err := l.writeAll(lHandshake)
if err != nil {
@ -148,15 +150,15 @@ func (l *Leech) doExHandshake() error {
}
func (l *Leech) requestAllPieces() error {
/*
* reqq
* An integer, the number of outstanding request messages this client supports without
* dropping any. The default in in libtorrent is 250.
* "handshake message" @ "Extension Protocol" @ http://www.bittorrent.org/beps/bep_0010.html
*
* TODO: maybe by requesting all pieces at once we are exceeding this limit? maybe we should
* request as we receive pieces?
*/
// reqq
// An integer, the number of outstanding request messages this client supports without
// dropping any. The default in in libtorrent is 250.
//
// "handshake message" @ "Extension Protocol" @ http://www.bittorrent.org/beps/bep_0010.html
//
// TODO: maybe by requesting all pieces at once we are exceeding this limit? maybe we should
// request as we receive pieces?
// Request all the pieces of metadata
nPieces := int(math.Ceil(float64(l.metadataSize) / math.Pow(2, 14)))
for piece := 0; piece < nPieces; piece++ {
@ -172,7 +174,7 @@ func (l *Leech) requestAllPieces() error {
err = l.writeAll([]byte(fmt.Sprintf(
"%s\x14%s%s",
toBigEndian(uint(2 + len(extDictDump)), 4),
toBigEndian(uint(2+len(extDictDump)), 4),
toBigEndian(uint(l.ut_metadata), 1),
extDictDump,
)))
@ -213,7 +215,7 @@ func (l *Leech) readExMessage() ([]byte, error) {
// Every extension message has at least 2 bytes.
if len(rMessage) < 2 {
continue;
continue
}
// We are interested only in extension messages, whose first byte is always 20
@ -483,4 +485,3 @@ func toBigEndian(i uint, n int) []byte {
return b
}

View File

@ -7,7 +7,7 @@ import (
"github.com/anacrolix/torrent/bencode"
)
var operationsTest_instances = []struct{
var operationsTest_instances = []struct {
dump []byte
surplus []byte
}{
@ -31,14 +31,14 @@ var operationsTest_instances = []struct{
func TestDecoder(t *testing.T) {
for i, instance := range operationsTest_instances {
buf := bytes.NewBuffer(instance.dump)
err := bencode.NewDecoder(buf).Decode(&struct {}{})
err := bencode.NewDecoder(buf).Decode(&struct{}{})
if err != nil {
t.Errorf("Couldn't decode the dump #%d! %s", i + 1, err.Error())
t.Errorf("Couldn't decode the dump #%d! %s", i+1, err.Error())
}
bufSurplus := buf.Bytes()
if !bytes.Equal(bufSurplus, instance.surplus) {
t.Errorf("Surplus #%d is not equal to what we expected! `%s`", i + 1, bufSurplus)
t.Errorf("Surplus #%d is not equal to what we expected! `%s`", i+1, bufSurplus)
}
}
}

View File

@ -258,7 +258,6 @@ func (e *Error) UnmarshalBencode(b []byte) (err error) {
}
if len(matches[2]) != msgLen {
return
return fmt.Errorf("error message have different lengths (%d vs %d) \"%s\"!", len(matches[2]), msgLen, matches[2])
}

View File

@ -221,9 +221,8 @@ func (p *Protocol) CalculateToken(address net.IP) []byte {
func (p *Protocol) VerifyToken(address net.IP, token []byte) bool {
p.tokenLock.Lock()
defer p.tokenLock.Unlock()
// TODO: implement VerifyToken()
panic("VerifyToken() not implemented yet!")
// TODO
return false
}
func (p *Protocol) updateTokenSecret() {

View File

@ -113,7 +113,7 @@ func (s *TrawlingService) bootstrap() {
if err != nil {
zap.L().Error("Could NOT resolve (UDP) address of the bootstrapping node!",
zap.String("node", node))
continue;
continue
}
s.protocol.SendMessage(NewFindNodeQuery(s.trueNodeID, target), addr)

View File

@ -83,7 +83,7 @@ func (t *Transport) Start() {
}
func (t *Transport) Terminate() {
unix.Close(t.fd);
unix.Close(t.fd)
}
// readMessages is a goroutine!
@ -131,7 +131,7 @@ func (t *Transport) WriteMessages(msg *Message, addr *net.UDPAddr) {
if addrSA == nil {
zap.L().Debug("Wrong net address for the remote peer!",
zap.String("addr", addr.String()))
return;
return
}
err = unix.Sendto(t.fd, data, 0, addrSA)

View File

@ -76,7 +76,7 @@ func main() {
switch opFlags.Profile {
case "cpu":
file, err := os.OpenFile("magneticod_cpu.prof", os.O_CREATE | os.O_WRONLY, 0755)
file, err := os.OpenFile("magneticod_cpu.prof", os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
zap.L().Panic("Could not open the cpu profile file!", zap.Error(err))
}

View File

@ -16,8 +16,7 @@ import (
func apiTorrentsHandler(w http.ResponseWriter, r *http.Request) {
// @lastOrderedValue AND @lastID are either both supplied or neither of them should be supplied
// at all; and if that is NOT the case, then return an error.
if q := r.URL.Query(); !(
(q.Get("lastOrderedValue") != "" && q.Get("lastID") != "") ||
if q := r.URL.Query(); !((q.Get("lastOrderedValue") != "" && q.Get("lastID") != "") ||
(q.Get("lastOrderedValue") == "" && q.Get("lastID") == "")) {
respondError(w, 400, "`lastOrderedValue`, `lastID` must be supplied altogether, if supplied.")
return

View File

@ -10,7 +10,6 @@ import (
"github.com/gorilla/mux"
)
// DONE
func rootHandler(w http.ResponseWriter, r *http.Request) {
nTorrents, err := database.GetNumberOfTorrents()

View File

@ -38,7 +38,7 @@ var decoder = schema.NewDecoder()
var templates map[string]*template.Template
var database persistence.Database
var opts struct{
var opts struct {
Addr string
Database string
Credentials map[string][]byte // TODO: encapsulate credentials and mutex for safety
@ -175,7 +175,6 @@ func respondError(w http.ResponseWriter, statusCode int, format string, a ...int
w.Write([]byte(fmt.Sprintf(format, a...)))
}
func mustAsset(name string) []byte {
data, err := Asset(name)
if err != nil {
@ -249,12 +248,12 @@ func loadCred(cred string) error {
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break;
break
}
return fmt.Errorf("error while reading line %d: %s", lineno, err.Error())
}
line = line[:len(line) - 1] // strip '\n'
line = line[:len(line)-1] // strip '\n'
/* The following regex checks if the line satisfies the following conditions:
*

View File

@ -26,9 +26,15 @@ func TestSchemaUnsuppliedNil(t *testing.T) {
t.Error("decoding error", err.Error())
}
if ss.PString != nil { t.Error("PString is not nil") }
if ss.PUint64 != nil { t.Error("PUint64 is not nil") }
if ss.PBool != nil { t.Error("PBool is not nil") }
if ss.PString != nil {
t.Error("PString is not nil")
}
if ss.PUint64 != nil {
t.Error("PUint64 is not nil")
}
if ss.PBool != nil {
t.Error("PBool is not nil")
}
}
// TestSchemaInvalidUint64 tests that an invalid uint64 value yields nil.
@ -38,7 +44,9 @@ func TestSchemaInvalidUint64(t *testing.T) {
ss := new(schemaStruct)
err := decoder.Decode(ss, dict)
if err == nil { t.Error("err is nil") }
if err == nil {
t.Error("err is nil")
}
}
// TestSchemaInvalidBool tests that an invalid bool value yields nil.
@ -48,7 +56,9 @@ func TestSchemaInvalidBool(t *testing.T) {
ss := new(schemaStruct)
err := decoder.Decode(ss, dict)
if err == nil { t.Error("err is nil") }
if err == nil {
t.Error("err is nil")
}
}
// TestSchemaOverflow tests that integer values greater than the maximum value a field can store
@ -59,7 +69,9 @@ func TestSchemaOverflow(t *testing.T) {
ss := new(schemaStruct)
err := decoder.Decode(ss, dict)
if err == nil { t.Error("err is nil") }
if err == nil {
t.Error("err is nil")
}
}
// TestSchemaEmptyString tests that empty string yields nil.
@ -72,7 +84,9 @@ func TestSchemaEmptyString(t *testing.T) {
t.Error("decoding error", err.Error())
}
if ss.PString != nil { t.Error("PString is not nil") }
if ss.PString != nil {
t.Error("PString is not nil")
}
}
// TestSchemaDefault tests if unsupplied values defaults to "zero" and doesn't err
@ -82,14 +96,22 @@ func TestSchemaDefault(t *testing.T) {
t.Error("decoding error", err.Error())
}
if ss.String != "" { t.Error("String is not empty") }
if ss.Uint64 != 0 { t.Error("Uint64 is not 0") }
if ss.Bool != false { t.Error("Bool is not false") }
if ss.String != "" {
t.Error("String is not empty")
}
if ss.Uint64 != 0 {
t.Error("Uint64 is not 0")
}
if ss.Bool != false {
t.Error("Bool is not false")
}
}
func TestSchemaRequired(t *testing.T) {
rs := new(schemaRStruct)
err := decoder.Decode(rs, make(map[string][]string))
if err == nil { t.Error("err is nil") }
if err == nil {
t.Error("err is nil")
}
fmt.Printf(err.Error())
}

View File

@ -42,6 +42,7 @@ type Database interface {
}
type OrderingCriteria uint8
const (
ByRelevance OrderingCriteria = iota
ByTotalSize
@ -51,9 +52,11 @@ const (
ByNLeechers
ByUpdatedOn
)
// TODO: search `swtich (orderBy)` and see if all cases are covered all the time
type databaseEngine uint8
const (
Sqlite3 databaseEngine = 1
)

View File

@ -14,6 +14,7 @@ var dayRE = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`)
var hourRE = regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})T(\d{2})$`)
type Granularity int
const (
Year Granularity = iota
Month
@ -50,7 +51,7 @@ func ParseISO8601(s string) (*time.Time, Granularity, error) {
if err != nil {
return nil, -1, err
}
t := time.Date(year, time.January, week * 7, 23, 59, 59, 0, time.UTC)
t := time.Date(year, time.January, week*7, 23, 59, 59, 0, time.UTC)
return &t, Week, nil
}
@ -122,11 +123,11 @@ func daysOfMonth(month time.Month, year int) int {
}
func isLeap(year int) bool {
if year % 4 != 0 {
if year%4 != 0 {
return false
} else if year % 100 != 0 {
} else if year%100 != 0 {
return true
} else if year % 400 != 0 {
} else if year%400 != 0 {
return false
} else {
return true

View File

@ -147,7 +147,7 @@ func (db *sqlite3Database) GetNumberOfTorrents() (uint, error) {
defer rows.Close()
if rows.Next() != true {
fmt.Errorf("No rows returned from `SELECT MAX(ROWID)`")
return 0, fmt.Errorf("No rows returned from `SELECT MAX(ROWID)`")
}
var n uint
@ -357,7 +357,7 @@ func (db *sqlite3Database) GetStatistics(from string, n uint) (*Statistics, erro
toTime = fromTime.AddDate(0, int(n), 0)
timef = "%Y-%m"
case Week:
toTime = fromTime.AddDate(0, 0, int(n) * 7)
toTime = fromTime.AddDate(0, 0, int(n)*7)
timef = "%Y-%W"
case Day:
toTime = fromTime.AddDate(0, 0, int(n))