<commit_before>package main

import (
	"bytes"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"os"
	"sort"

	"github.com/pressly/chi"
	"github.com/pressly/chi/middleware"

	"github.com/disintegration/bebop/api"
	"github.com/disintegration/bebop/avatar"
	"github.com/disintegration/bebop/config"
	"github.com/disintegration/bebop/jwt"
	"github.com/disintegration/bebop/oauth"
	"github.com/disintegration/bebop/static"
)

// startServer configures and starts the bebop web server.
func startServer() {
	cfg, err := config.ReadFile(configFile)
	if err != nil {
		log.Fatalf("failed to load configuration file: %s", err)
	}

	logger := log.New(os.Stdout, "", log.LstdFlags|log.LUTC)

	baseURL, err := url.Parse(cfg.BaseURL)
	if err != nil {
		log.Fatalf("failed to parse base url: %s", err)
	}

	fileStorage, err := getFileStorage(cfg)
	if err != nil {
		log.Fatalf("failed to init file storage: %s", err)
	}

	store, err := getStore(cfg)
	if err != nil {
		log.Fatalf("failed to init data store: %s", err)
	}

	jwtService, err := jwt.NewService(cfg.JWT.Secret)
	if err != nil {
		log.Fatalf("failed to create jwt service: %s", err)
	}

	avatarService := avatar.NewService(store.Users(), fileStorage, logger)

	apiHandler := api.New(&api.Config{
		Logger:        logger,
		Store:         store,
		JWTService:    jwtService,
		AvatarService: avatarService,
	})

	oauthHandler := oauth.New(&oauth.Config{
		Logger:     logger,
		UserStore:  store.Users(),
		JWTService: jwtService,
		MountURL:   baseURL.String() + "/oauth",
		CookiePath: baseURL.Path + "/",
	})

	for providerName, provider := range cfg.OAuth {
		if provider.ClientID != "" && provider.Secret != "" {
			err := oauthHandler.AddProvider(providerName, provider.ClientID, provider.Secret)
			if err != nil {
				log.Fatalf("failed to init oauth provider (%s): %s", providerName, err)
			}
		}
	}

	indexHandler, err := newIndexHandler(cfg)
	if err != nil {
		log.Fatalf("failed to create index handler: %s", err)
	}

	router := chi.NewRouter()

	router.Use(middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: logger}))
	router.Use(middleware.Recoverer)

	router.Mount("/api/v1", apiHandler)
	router.Mount("/oauth", oauthHandler)

	router.Mount("/static/-", static.Embedded("/static/-"))

	if cfg.FileStorage.Type == "local" {
		router.Mount("/static", static.Dir("/static", cfg.FileStorage.Local.Dir))
	}

	router.Get("/", indexHandler)

	log.Printf("starting the server: %s", cfg.Address)

	if err := http.ListenAndServe(cfg.Address, http.StripPrefix(baseURL.Path, router)); err != nil {
		log.Fatalf("listen and serve failed: %v", err)
	}
}

func newIndexHandler(cfg *config.Config) (http.HandlerFunc, error) {
	t, err := template.New("indexTemplate").Parse(indexTemplate)
	if err != nil {
		return nil, fmt.Errorf("failed to parse template: %s", err)
	}

	appConfig := struct {
		Title string   `json:"title"`
		OAuth []string `json:"oauth"`
	}{
		Title: cfg.Title,
		OAuth: []string{},
	}

	for providerName := range cfg.OAuth {
		appConfig.OAuth = append(appConfig.OAuth, providerName)
	}
	sort.Strings(appConfig.OAuth)

	buf := new(bytes.Buffer)
	err = t.Execute(buf, map[string]interface{}{
		"title":     cfg.Title,
		"appConfig": appConfig,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to execute index template: %s", err)
	}
<commit_msg>server: don't add unused oauth providers to config<commit_after>package main

import (
	"bytes"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"os"
	"sort"

	"github.com/pressly/chi"
	"github.com/pressly/chi/middleware"

	"github.com/disintegration/bebop/api"
	"github.com/disintegration/bebop/avatar"
	"github.com/disintegration/bebop/config"
	"github.com/disintegration/bebop/jwt"
	"github.com/disintegration/bebop/oauth"
	"github.com/disintegration/bebop/static"
)

// startServer configures and starts the bebop web server.
func startServer() {
	cfg, err := config.ReadFile(configFile)
	if err != nil {
		log.Fatalf("failed to load configuration file: %s", err)
	}

	logger := log.New(os.Stdout, "", log.LstdFlags|log.LUTC)

	baseURL, err := url.Parse(cfg.BaseURL)
	if err != nil {
		log.Fatalf("failed to parse base url: %s", err)
	}

	fileStorage, err := getFileStorage(cfg)
	if err != nil {
		log.Fatalf("failed to init file storage: %s", err)
	}

	store, err := getStore(cfg)
	if err != nil {
		log.Fatalf("failed to init data store: %s", err)
	}

	jwtService, err := jwt.NewService(cfg.JWT.Secret)
	if err != nil {
		log.Fatalf("failed to create jwt service: %s", err)
	}

	avatarService := avatar.NewService(store.Users(), fileStorage, logger)

	apiHandler := api.New(&api.Config{
		Logger:        logger,
		Store:         store,
		JWTService:    jwtService,
		AvatarService: avatarService,
	})

	oauthHandler := oauth.New(&oauth.Config{
		Logger:     logger,
		UserStore:  store.Users(),
		JWTService: jwtService,
		MountURL:   baseURL.String() + "/oauth",
		CookiePath: baseURL.Path + "/",
	})

	for providerName, provider := range cfg.OAuth {
		if provider.ClientID != "" && provider.Secret != "" {
			err := oauthHandler.AddProvider(providerName, provider.ClientID, provider.Secret)
			if err != nil {
				log.Fatalf("failed to init oauth provider (%s): %s", providerName, err)
			}
		}
	}

	indexHandler, err := newIndexHandler(cfg)
	if err != nil {
		log.Fatalf("failed to create index handler: %s", err)
	}

	router := chi.NewRouter()

	router.Use(middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: logger}))
	router.Use(middleware.Recoverer)

	router.Mount("/api/v1", apiHandler)
	router.Mount("/oauth", oauthHandler)

	router.Mount("/static/-", static.Embedded("/static/-"))

	if cfg.FileStorage.Type == "local" {
		router.Mount("/static", static.Dir("/static", cfg.FileStorage.Local.Dir))
	}

	router.Get("/", indexHandler)

	log.Printf("starting the server: %s", cfg.Address)

	if err := http.ListenAndServe(cfg.Address, http.StripPrefix(baseURL.Path, router)); err != nil {
		log.Fatalf("listen and serve failed: %v", err)
	}
}

func newIndexHandler(cfg *config.Config) (http.HandlerFunc, error) {
	t, err := template.New("indexTemplate").Parse(indexTemplate)
	if err != nil {
		return nil, fmt.Errorf("failed to parse template: %s", err)
	}

	appConfig := struct {
		Title string   `json:"title"`
		OAuth []string `json:"oauth"`
	}{
		Title: cfg.Title,
		OAuth: []string{},
	}

	for providerName, provider := range cfg.OAuth {
		if provider.ClientID != "" && provider.Secret != "" {
			appConfig.OAuth = append(appConfig.OAuth, providerName)
		}
	}
	sort.Strings(appConfig.OAuth)

	buf := new(bytes.Buffer)
	err = t.Execute(buf, map[string]interface{}{
		"title":     cfg.Title,
		"appConfig": appConfig,
	})
	if err != nil {
		return nil, fmt.Errorf("failed to execute index template: %s", err)
	}

{'fraction_non_alphanumeric': 0.16061946902654867, 'fraction_numerical': 0.0002949852507374631, 'mean_word_length': 4.075598802395209, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, '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': '7616525', 'n_tokens_mistral': 2532, 'n_tokens_neox': 2407, 'n_words': 527}