<commit_before>package main

import (
    "github.com/russross/blackfriday" // parsing markdown
    "net/http"
    "text/template"
    "strings"
    "log"
    "io/ioutil"
    "os"
    "path"
    "regexp"
    "fmt"
    "encoding/json"
    "flag"
)

/* TODO
    - replace log.fatal with error page
    - ensure access is properly restricted
    - make sure bubble entries exist before replacing [[] []] with link
    - watch github repo and update
    - robustify posts functionality
    - clean up js bubbles so they follow user as they scroll

*/

// bloke should be launched from the sites root
// should be installed in gopath/src/github/ebuchman/bloke...
var SiteRoot = "."
var GoPath = os.Getenv("GOPATH")
var BlokePath = GoPath + "/src/github.com/ebuchman/bloke" // is there a nicer way to get this?

var InitSite = flag.String("init", "", "path to new site dir")



//parse template files
var templates = template.Must(template.ParseFiles(BlokePath+"/views/page.html", BlokePath+"/views/nav.html", BlokePath+"/views/footer.html", BlokePath+"/views/bubbles.html"))

func RenderTemplateToFile(tmpl, save_file string, p interface{}){
    //we already parsed the html templates
    f, err := os.Create(SiteRoot+"/sites/"+save_file+".html")
    if err != nil{
        log.Fatal("err opening file:", err)
    }
    err = templates.ExecuteTemplate(f, tmpl+".html", p)
    if err != nil {
        log.Fatal("err writing template to file", err)
    }
}

func renderTemplate(w http.ResponseWriter, tmpl string, p interface{}){
    //we already parsed the html templates
    err := templates.ExecuteTemplate(w, tmpl+".html", p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

// get name from blogpost url
func GetNameFromPost(s string) string{
       date_name := strings.Split(strings.Split(s, ".")[0], "-")
       title := date_name[3]
       return title
}

// parse and replace for bubbles and markdown to js/html
// takes the raw txt.md bytes
func DataTransform(s []byte) string{
    r, _ := regexp.Compile(`\[\[(.+?)\] \[(.+?)\]\]?`)
    s = blackfriday.MarkdownCommon(s)
    return r.ReplaceAllString(string(s), `<a href="#/" onClick="get_entry_data('$2')">$1</a>`)
}

// main routing function
func (g *Globals) handleIndex(w http.ResponseWriter, r *http.Request){
        log.Println("handle Index", r.URL.Path)
        /* url is either
            /                                   home page (recent blog posts)  
            /posts/Date-PostName                a specific blog post
            /ProjectName                        a particular project page
        */ 
        if len(r.URL.Path[1:]) > 0{
            path_elements := strings.Split(r.URL.Path[1:], "/")
            log.Println(path_elements)
            // posts
            if path_elements[0] == "posts"{
                b, err := ioutil.ReadFile(path.Join(SiteRoot,r.URL.Path[1:]))
                if err != nil{
                    log.Fatal("error acessing data", err)
                }
                g.Text = DataTransform(b) //string(blackfriday.MarkdownCommon(b))
                g.Title = GetNameFromPost(r.URL.Path[1:])
            // pages
            }else{
                b, err := ioutil.ReadFile(SiteRoot+"/pages/"+r.URL.Path[1:]+".md")
                if err != nil{
                    log.Fatal("error acessing data", err)
                }
                g.Text = DataTransform(b) //string(blackfriday.MarkdownCommon(b))
                log.Println(SiteRoot+"/pages/"+r.URL.Path[1:]+".md")
                split_path := strings.Split(r.URL.Path[1:], "/")
                g.Title = split_path[len(split_path)-1]
            }
        // home
        } else {
            b, err := ioutil.ReadFile(SiteRoot+"/posts/"+g.RecentPosts[0][1])
            if err != nil{
                log.Fatal("error opening post", err)
            }
            g.Text = string(blackfriday.MarkdownCommon(b))
            g.Title = g.RecentPosts[0][0]
        }
        renderTemplate(w, "page", g)
}


// ajax bubble response
func (g *Globals) ajaxResponse(w http.ResponseWriter, r *http.Request){
    //path_split := strings.Split(r.URL.Path[1:], "/")
    // path_split [0] should be "bubble"
    //bubble := path_split[1]
    b, err := ioutil.ReadFile(path.Join(SiteRoot, r.URL.Path[1:]))
    if err != nil{
        log.Fatal("error on bubble ", r.URL.Path[1:], err)
    }
    fmt.Fprintf(w, DataTransform(b))
}

// serve static files (assets)
func serveFile(w http.ResponseWriter, r *http.Request){
    // if img, load from SiteRoot
    // if js/css, load from BlokePath

    if !strings.Contains(r.URL.Path, "."){
        //s.handleIndex(w, r)
    }else{
        subs := strings.Split(r.URL.Path, ".")
        ext := subs[len(subs)-1]
        if ext == "js" || ext == "css"{
            http.ServeFile(w, r, path.Join(BlokePath, r.URL.Path[1:]))
        }else if ext == "png" || ext == "jpg"{
            http.ServeFile(w, r, path.Join(SiteRoot, r.URL.Path[1:]))
        }
    }
}

// serve a single html page
func servePage(w http.ResponseWriter, r *http.Request){
    if !strings.Contains(r.URL.Path, "."){
        http.ServeFile(w, r, SiteRoot+"/sites/main.html") //+r.URL.Path[1:])<commit_msg>simple page error<commit_after>package main

import (
    "github.com/russross/blackfriday" // parsing markdown
    "net/http"
    "text/template"
    "strings"
    "log"
    "io/ioutil"
    "os"
    "path"
    "regexp"
    "fmt"
    "encoding/json"
    "flag"
)

/* TODO
    - ensure access is properly restricted
    - make sure bubble entries exist before replacing [[] []] with link
    - watch github repo and update
    - robustify posts functionality
    - clean up js bubbles so they follow user as they scroll

*/

// bloke should be launched from the sites root
// should be installed in gopath/src/github/ebuchman/bloke...
var SiteRoot = "."
var GoPath = os.Getenv("GOPATH")
var BlokePath = GoPath + "/src/github.com/ebuchman/bloke" // is there a nicer way to get this?

var InitSite = flag.String("init", "", "path to new site dir")



//parse template files
var templates = template.Must(template.ParseFiles(BlokePath+"/views/page.html", BlokePath+"/views/nav.html", BlokePath+"/views/footer.html", BlokePath+"/views/bubbles.html"))

func RenderTemplateToFile(tmpl, save_file string, p interface{}){
    //we already parsed the html templates
    f, err := os.Create(SiteRoot+"/sites/"+save_file+".html")
    if err != nil{
        log.Fatal("err opening file:", err)
    }
    err = templates.ExecuteTemplate(f, tmpl+".html", p)
    if err != nil {
        log.Fatal("err writing template to file", err)
    }
}

func renderTemplate(w http.ResponseWriter, tmpl string, p interface{}){
    //we already parsed the html templates
    err := templates.ExecuteTemplate(w, tmpl+".html", p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

// get name from blogpost url
func GetNameFromPost(s string) string{
       date_name := strings.Split(strings.Split(s, ".")[0], "-")
       title := date_name[3]
       return title
}

// parse and replace for bubbles and markdown to js/html
// takes the raw txt.md bytes
func DataTransform(s []byte) string{
    r, _ := regexp.Compile(`\[\[(.+?)\] \[(.+?)\]\]?`)
    s = blackfriday.MarkdownCommon(s)
    return r.ReplaceAllString(string(s), `<a href="#/" onClick="get_entry_data('$2')">$1</a>`)
}

// main routing function
func (g *Globals) handleIndex(w http.ResponseWriter, r *http.Request){
        log.Println("handle Index", r.URL.Path)
        /* url is either
            /                                   home page (recent blog posts)  
            /posts/Date-PostName                a specific blog post
            /ProjectName                        a particular project page
        */ 
        if len(r.URL.Path[1:]) > 0{
            path_elements := strings.Split(r.URL.Path[1:], "/")
            log.Println(path_elements)
            // posts
            if path_elements[0] == "posts"{
                b, err := ioutil.ReadFile(path.Join(SiteRoot,r.URL.Path[1:]))
                if err != nil{
                    g.Title = "Error"
                    g.Text = err.Error()
                    renderTemplate(w, "page", g)
                    return 
                }
                g.Text = DataTransform(b) //string(blackfriday.MarkdownCommon(b))
                g.Title = GetNameFromPost(r.URL.Path[1:])
            // pages
            }else{
                b, err := ioutil.ReadFile(SiteRoot+"/pages/"+r.URL.Path[1:]+".md")
                if err != nil{
                    g.Title = "Error"
                    g.Text = err.Error()
                    renderTemplate(w, "page", g)
                    return 
                }
                g.Text = DataTransform(b) //string(blackfriday.MarkdownCommon(b))
                log.Println(SiteRoot+"/pages/"+r.URL.Path[1:]+".md")
                split_path := strings.Split(r.URL.Path[1:], "/")
                g.Title = split_path[len(split_path)-1]
            }
        // home
        } else {
            b, err := ioutil.ReadFile(SiteRoot+"/posts/"+g.RecentPosts[0][1])
            if err != nil{
                g.Title = "Error"
                g.Text = err.Error()
                renderTemplate(w, "page", g)
                return 
            }
            g.Text = string(blackfriday.MarkdownCommon(b))
            g.Title = g.RecentPosts[0][0]
        }
        renderTemplate(w, "page", g)
}


// ajax bubble response
func (g *Globals) ajaxResponse(w http.ResponseWriter, r *http.Request){
    //path_split := strings.Split(r.URL.Path[1:], "/")
    // path_split [0] should be "bubble"
    //bubble := path_split[1]
    b, err := ioutil.ReadFile(path.Join(SiteRoot, r.URL.Path[1:]))
    if err != nil{
        log.Println("error on bubble ", r.URL.Path[1:], err)
    }
    fmt.Fprintf(w, DataTransform(b))
}

// serve static files (assets)
func serveFile(w http.ResponseWriter, r *http.Request){
    // if img, load from SiteRoot
    // if js/css, load from BlokePath

    if !strings.Contains(r.URL.Path, "."){
        //s.handleIndex(w, r)
    }else{
        subs := strings.Split(r.URL.Path, ".")
        ext := subs[len(subs)-1]
        if ext == "js" || ext == "css"{
            http.ServeFile(w, r, path.Join(BlokePath, r.URL.Path[1:]))
        }else if ext == "png" || ext == "jpg"{
            http.ServeFile(w, r, path.Join(SiteRoot, r.URL.Path[1:]))
        }
    }
}

// serve a single html page
func servePage(w http.ResponseWriter, r *http.Request){
    if !strings.Contains(r.URL.Path, "."){
        http.ServeFile(w, r, SiteRoot+"/sites/main.html") //+r.URL.Path[1:])
{'fraction_non_alphanumeric': 0.15319188709225162, 'fraction_numerical': 0.0050472006729600895, 'mean_word_length': 2.0906990179087233, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1481370', 'n_tokens_mistral': 3517, 'n_tokens_neox': 3403, 'n_words': 798}