<commit_before>package km

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"syscall"
	"text/template"
	"time"

	"github.com/coopernurse/gorp"
	"github.com/gorilla/mux"
	_ "github.com/lib/pq"
)

type Config struct {
	Env string
	Log string
}

type StateGetter func(dbmap *gorp.DbMap, dateStr string) (err error, state State)
type SaveInterface func(dbmap *gorp.DbMap, date time.Time, fields []Field) (err error)
type GetTimesInterface func(dbmap *gorp.DbMap, year, month int64) (rows []TimeRow, err error)

type Server struct {
	mux.Router
	Dbmap     *gorp.DbMap
	templates *template.Template
	config    Config
	StateFunc StateGetter
	SaveKilos SaveInterface
	SaveTimes SaveInterface
	GetTimes  GetTimesInterface
}

func NewServer(dbName string, config Config) (s *Server, err error) {
	var logFile *os.File
	// Set up logging
	if config.Log != "" {
		logFile, err = os.OpenFile(config.Log, syscall.O_WRONLY|syscall.O_APPEND|syscall.O_CREAT, 0666)
		if err != nil {
			return nil, fmt.Errorf("could not open logfile: %s", err.Error())
		}
		log.SetOutput(logFile)
		log.SetPrefix("km-app:\t")
	}

	db, creating_db_error := sql.Open("postgres", "user=docker dbname="+dbName+" password=<PASSWORD> sslmode=disable")
	testDbRegex := regexp.MustCompile("_test$")
	err = db.Ping()
	if !testDbRegex.MatchString(dbName) && err != nil {
		return nil, fmt.Errorf("ping result: %s\nsql.Open result: %s", err, creating_db_error)
	}
	var Dbmap *gorp.DbMap
	Dbmap = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
	Dbmap.AddTable(Kilometers{}).SetKeys(true, "Id")
	Dbmap.AddTable(Times{}).SetKeys(true, "Id")

	var templates *template.Template
	if config.Env == "testing" {
		Dbmap.TraceOn("[gorp]", log.New(logFile, "DB:\t", log.LstdFlags))
	} else {
		templates = template.Must(template.ParseFiles("index.html"))
	}
	s = &Server{Dbmap: Dbmap,
		templates: templates,
		config:    config,
		StateFunc: GetState,
		SaveKilos: SaveKilometers,
		SaveTimes: SaveTimes,
		GetTimes:  GetAllTimes,
	}

	// static files get served directly
	if config.Env == "testing" {
		s.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("js/"))))
		s.PathPrefix("/img/").Handler(http.StripPrefix("/img/", http.FileServer(http.Dir("img/"))))
		s.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("css/"))))<commit_msg>better logging of where error occurs on sql.open<commit_after>package km

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"syscall"
	"text/template"
	"time"

	"github.com/coopernurse/gorp"
	"github.com/gorilla/mux"
	_ "github.com/lib/pq"
)

type Config struct {
	Env string
	Log string
}

type StateGetter func(dbmap *gorp.DbMap, dateStr string) (err error, state State)
type SaveInterface func(dbmap *gorp.DbMap, date time.Time, fields []Field) (err error)
type GetTimesInterface func(dbmap *gorp.DbMap, year, month int64) (rows []TimeRow, err error)

type Server struct {
	mux.Router
	Dbmap     *gorp.DbMap
	templates *template.Template
	config    Config
	StateFunc StateGetter
	SaveKilos SaveInterface
	SaveTimes SaveInterface
	GetTimes  GetTimesInterface
}

func NewServer(dbName string, config Config) (s *Server, err error) {
	var logFile *os.File
	// Set up logging
	if config.Log != "" {
		logFile, err = os.OpenFile(config.Log, syscall.O_WRONLY|syscall.O_APPEND|syscall.O_CREAT, 0666)
		if err != nil {
			return nil, fmt.Errorf("could not open logfile: %s", err.Error())
		}
		log.SetOutput(logFile)
		log.SetPrefix("km-app:\t")
	}

	db, creating_db_error := sql.Open("postgres", "user=docker dbname="+dbName+" password=<PASSWORD> sslmode=disable")
	testDbRegex := regexp.MustCompile("_test$")
	err = db.Ping()
	if !testDbRegex.MatchString(dbName) && err != nil {
		if creating_db_error != nil {
			return nil, fmt.Errorf("sql.Open result: %s", creating_db_error)
		}
		if err != nil {
			return nil, fmt.Errorf("ping result: %s", err)

		}
	}
	var Dbmap *gorp.DbMap
	Dbmap = &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}
	Dbmap.AddTable(Kilometers{}).SetKeys(true, "Id")
	Dbmap.AddTable(Times{}).SetKeys(true, "Id")

	var templates *template.Template
	if config.Env == "testing" {
		Dbmap.TraceOn("[gorp]", log.New(logFile, "DB:\t", log.LstdFlags))
	} else {
		templates = template.Must(template.ParseFiles("index.html"))
	}
	s = &Server{Dbmap: Dbmap,
		templates: templates,
		config:    config,
		StateFunc: GetState,
		SaveKilos: SaveKilometers,
		SaveTimes: SaveTimes,
		GetTimes:  GetAllTimes,
	}

	// static files get served directly
	if config.Env == "testing" {
		s.PathPrefix("/js/").Handler(http.StripPrefix("/js/", http.FileServer(http.Dir("js/"))))
		s.PathPrefix("/img/").Handler(http.StripPrefix("/img/", http.FileServer(http.Dir("img/"))))
		s.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("css/"))))
{'fraction_non_alphanumeric': 0.15941735787983005, 'fraction_numerical': 0.002427675500708072, 'mean_word_length': 4.637400228050171, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5780108', 'n_tokens_mistral': 1939, 'n_tokens_neox': 1849, 'n_words': 391}