Class: Solutus

Inherits:
Object
  • Object
show all
Defined in:
lib/solutus.rb

Overview

TODO: Add support for tags TODO: Make stress tests TODO: Fix bug : day being off with time in file

Defined Under Namespace

Classes: SolutusStache, Solutus_Server

Constant Summary collapse

ARCHIVE =
"archive"
DEFAULT_TEMPLATE =
"default"
BLOG_TEMPLATE =
"post"
BUILD_PATH =
"deploy"
SITE_PATH =
File.join(BUILD_PATH, "site")
BLOG_BUILD_PATH =
File.join(SITE_PATH, ARCHIVE)
STATIC_PATH =
"static"
TEMPLATES_PATH =
"templates"
SITE_PAGES_PATH =
File.join("pages", "site-pages")
POSTS_PATH =
File.join("pages", "posts")
BLOG_DATE_FORMAT =
"%b %e, %Y"
BLOG_DATE_DATA =
"%Y-%m-%d %I:%M:%S"
SETTINGS_FILE =
"settings.yml"
CACHE =
".solutus-cache"
PASSWORD_FILE =
"password.txt"
DAY_ENDINGS =
["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"]
VERSION =
'0.2.0'
LOG_FILE =
'log'
@@blog_urls =
Hash.new
@@page_urls =
Array.new

Class Method Summary collapse

Class Method Details

.blog_urlsObject



534
535
536
# File 'lib/solutus.rb', line 534

def self.blog_urls
    @@blog_urls
end

.buildObject



612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/solutus.rb', line 612

def self.build
    puts "Solutus is building the static site"
    settings_data = load_settings
    if settings_data == false
        return
    end
    
    if File.directory?(BUILD_PATH)
        FileUtils.remove_dir(BUILD_PATH)
    end
    Dir.mkdir(BUILD_PATH)
    Dir.mkdir(SITE_PATH)
    copy_static

    @@templates = Hash.new
    Dir.entries(TEMPLATES_PATH).each do |entry|
        next if entry == "." || entry == ".."
        puts "Loading template #{entry}"
        path = File.join(TEMPLATES_PATH, entry)
        if File.file?(path)
            contents = ""
            f = File.open(path, "r")
            f.each_line do |line|
                contents += line
            end
            @@templates[entry.split(".")[0]] = contents
        end
    end

    yaml_data = Hash.new

    @@blog_urls = Hash.new
    Dir.entries(POSTS_PATH).each do |entry|
        next if entry == "." || entry == ".."
        path = File.join(POSTS_PATH, entry)
        f = File.open(path, "r")
        contents = ""
        f.each_line do |line|
            contents += line
        end
        f.close

        yaml_data[entry] = contents
        data = YAML.load(contents)
        date = data["date"]
        subtitle = data.fetch("subtitle", "")
        relative_dir = File.join(date.year.to_s, date.month.to_s, date.day.to_s, entry.split(".")[0])
        year = date.year.to_s
        if !@@blog_urls.key?(year)
            @@blog_urls[year] = Array.new
        end
        @@blog_urls[year].push({
            "title" => data["title"], 
            "url" => File.join(ARCHIVE, relative_dir),
            "file_path" => path,
            "date" => date,
            "subtitle" => subtitle
        })
    end

    recents_count = 3
    recents = ""
    get_recents(recents_count).reverse.each do |post|
        url = post["url"]
        title = post["title"]
        date = prettify_date(post["date"])
        subtitle = post["subtitle"]

        block = "<div class=\"solutus-recents-block\">\n<a class=\"solutus-blog-thumbnail\" href=\"/\#{url}\">\#{title}</a> - \#{date}\n<div class=\"solutus-blog-subtitle\"><i>\#{subtitle}</i></div>\n</div>\n"
        recents += block
    end

    yaml_data.each do |entry, contents|
        path = File.join(POSTS_PATH, entry)
        data = YAML.load(contents)
        markdown_parsed = render_markdown(contents.split("---")[-1])
        data["content"] = markdown_parsed
        data["recents"] = recents
        date = data["date"]

        puts "Rendering blog post #{entry}"
        html = render_page(@@templates, settings_data, data, true)

        relative_dir = File.join(date.year.to_s, date.month.to_s, date.day.to_s, entry.split(".")[0])
        root_url = File.join(ARCHIVE, relative_dir, "index.html")

        year = date.year.to_s

        dir_path = File.join(BLOG_BUILD_PATH, relative_dir)
        if !File.directory?(dir_path)
            FileUtils.mkdir_p(dir_path)
        end
        file_path = File.join(SITE_PATH, root_url)
        puts "Created #{file_path}"
        f = File.new(file_path, "w")
        f.write(html)
        f.close()
    end    

    @@page_urls = Array.new
    relative_path_to_all_files_in_dir(SITE_PAGES_PATH).each do |entry|
        next if entry == "." || entry == ".."
        puts "Rendering page #{entry}"
        path = File.join(SITE_PAGES_PATH, entry)
        if File.file?(path)
            yml_text = ""
            f = File.open(path, "r")
            f.each_line do |line|
                yml_text += line
            end
            data = YAML.load(yml_text)
            data["recents"] = recents
            html = render_page(@@templates, settings_data, data, false)
            new_dir = File.join(SITE_PATH, entry.split(".")[0])
            if ["error", "index"].include? entry.split(".")[0]
                new_path = File.join(SITE_PATH, entry.split(".")[0] + ".html")
            else
                if !File.directory?(new_dir)
                    FileUtils.mkdir_p(new_dir)
                end
                new_path = File.join(new_dir, "index.html")
            end
            f = File.new(new_path, "w")
            puts "Created #{new_path}"
            f.write(html)
            f.close
            @@page_urls.push({
                "title" => data["title"],
                "file_path" => path
            })
        end
    end    

    # Create blog archive page 
    content = ""
    @@blog_urls.each do |yr, arr|
        sorted = arr.sort_by {|k| k["date"]} .reverse
        content += "<h3>#{yr}</h3>\n<hr>\n"
        sorted.each do |hash|
            url = hash["url"]
            title = hash["title"]
            pretty_date = prettify_date(hash["date"])
            content += "<div class=\"solutus-blog-block\">\n"
            content += "    <div class=\"solutus-blog-title\">\n"
            content += "        <a href=\"/#{url}\">#{title}</a>\n"
            content += "    </div>\n"
            content += "    <div>#{pretty_date}</div>\n"
            content += "</div>\n"
        end
    end
    if File.directory?(File.join(SITE_PATH, ARCHIVE))
        path = File.join(SITE_PATH, ARCHIVE, "index.html")
        data = Hash.new
        data["title"] = "Archive"
        data["content"] = content
        data["recents"] = recents
        html = render_page(@@templates, settings_data, data, false)
        f = File.new(path, "w")
        f.write(html)
        f.close
        puts "Created blog archive @ #{path}"
    end

    # Mirror build
    if settings_data["mirror"]
        dir_path = settings_data["mirror"]
        FileUtils.rm_rf("#{dir_path}/.", secure: true)
        FileUtils.copy_entry(SITE_PATH, dir_path)
    end
end

.command(*args) ⇒ Object



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/solutus.rb', line 546

def self.command(*args)
    start_time = Time.now
    if args.length >= 1
        if ["-v", "--version"].include?(args[0])
            puts VERSION
            return
        elsif args[0] == "deploy"
            deploy
        elsif args[0] == "build"
            build
        elsif args[0] == "serve"
            build #right now, the server won't werve unless its built. 
                  #consider serializing data in cache to save time.
                  #TODO: Stress test the build for speed.
            serve
            return
        elsif args[0] == "start"
            build 
            serve
            return
        elsif args[0] == "publish"
            build
            deploy
        else 
            if args.length >= 2
                if args[0] == "password"
                    create_password(args[1])
                elsif args[0] == "create"
                    new_project(args[1])
                else
                    if args.length >= 3
                        if args[0] == "new"
                            if args[1] == "page"
                                new_page(args[2])
                            elsif args[1] == "post"
                                return new_post(args[2])
                            end
                        end
                    else
                        puts "Invalid arguments"
                        return
                    end
                end
            else
                puts "Unknown command."
                return
            end
        end
    end

    end_time = Time.now
    diff = end_time - start_time
    puts "Completed in #{diff} seconds."
end

.copy_staticObject



874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/solutus.rb', line 874

def self.copy_static
    Dir.entries(STATIC_PATH).each do |entry|
        next if entry == "." || entry == ".."
        path = File.join(STATIC_PATH, entry)
        if File.file?(path)
            puts "Copying static file #{path}"
            FileUtils.copy(path, File.join(SITE_PATH, entry))
        elsif File.directory?(path)
            puts "Recursively copying static dir #{path}"
            FileUtils.copy_entry(path, File.join(SITE_PATH, entry))
        end
    end
end

.correct_time(time) ⇒ Object



900
901
902
# File 'lib/solutus.rb', line 900

def self.correct_time(time)
    time.utc.localtime("+05:30")
end

.create_password(password) ⇒ Object



934
935
936
937
938
939
940
941
942
943
# File 'lib/solutus.rb', line 934

def self.create_password(password)
    content = Digest::MD5.hexdigest password
    if File.file?(PASSWORD_FILE)
        FileUtils.rm(PASSWORD_FILE)
    end
    f = File.new(PASSWORD_FILE, "w")
    f.write(content)
    f.close
    puts "Wrote password to password.txt"
end

.deployObject



601
602
603
604
# File 'lib/solutus.rb', line 601

def self.deploy
    puts "Solutus is deploying"
    system load_settings["deploy-command"]
end

.get_recents(count) ⇒ Object



892
893
894
895
896
897
898
# File 'lib/solutus.rb', line 892

def self.get_recents(count)
    res = Array.new
    @@blog_urls.each do |yr, arr|
        res = res + arr.sort_by {|k| k["date"]}
    end
    res.last(count)
end

.load_settingsObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/solutus.rb', line 44

def self.load_settings
    begin
        yml_text = ""
        f = File.open(SETTINGS_FILE, "r")
        f.each_line do |line|
            yml_text += line
        end
        f.close
        YAML.load(yml_text)
    rescue
        puts "Not a Solutus Project (yet) --- settings.yml not found"
        false
    end
end

.new_page(title) ⇒ Object



810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/solutus.rb', line 810

def self.new_page(title)
    title = title.gsub(/\s+/, "").gsub(/[^a-zA-Z0-9\-]/, "").strip
    if title.empty?
        puts "Bad name"
        return
    end
    if ["edit"].include?(title)
        puts "Can't use #{title} as a page name."
        return
    end

    path = File.join(SITE_PAGES_PATH, title + ".yml")
    if File.file?(path)
        puts "Page with that name already exists."
        return
    end

    text = "template: default\ntitle: \#{title}\ncontent: |\n<h1>\#{title}</h1>\n<p>\n    Some Content\n</p>\n"
    f = File.new(path, "w")
    f.write(text)
    f.close
    puts "Created new site page #{title} at #{path}"
end

.new_post(title) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/solutus.rb', line 842

def self.new_post(title)
    i = 1
    new_title = title.gsub(/\s+/, "").gsub(/[^a-zA-Z0-9\-]/, "").strip
    if title.empty?
        puts "Empty title"
        return ""
    end
    while true
        path = File.join(POSTS_PATH, new_title + ".md")
        if File.file?(path)
            new_title = title + "#{i}"
            i += 1
        else
            break
        end
    end
    date = Time.now.strftime(BLOG_DATE_DATA)
    text = "---\ntitle: \#{title}\ndate: \#{date}\nsubtitle: Another new blog post\n---\n*This is a temporary blog post page!*\n"
    f = File.new(path, "w")
    f.write(text)
    f.close
    puts "Created new blog post #{title} at #{path}"
    path
end

.new_project(name) ⇒ Object



945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/solutus.rb', line 945

def self.new_project(name)
    name = name.gsub(/[^a-zA-Z0-9\-]/, "").strip
    if name == ""
        puts "Invalid name"
        return
    end
    if File.directory?(name)
        puts "Invalid name, already a folder with that name"
        print "Overwrite? [Y/n]"
        if STDIN.gets.chomp == "Y"
            FileUtils.remove_dir(name)
        else 
            return
        end
    end
    
    Dir.mkdir(name)
    
    paths = Array.new
    ["deploy", "static", "templates", "pages", CACHE].each do |dir|
        paths.push(File.join(name, dir))
    end
    ["css", "js", "imgs"].each do |dir|
        paths.push(File.join(name, "static", dir))
    end
    ["posts", "site-pages"].each do |dir|
        paths.push(File.join(name, "pages", dir))
    end
    
    paths.each do |path|
        Dir.mkdir(path)
    end
    
    settings_file =  "name: \#{name}\nauthor: Your Name\ndomain: www.yoursite.tld\ndeploy-command: aws s3 sync --acl public-read --sse --delete deploy/site/ s3://www.yoursite.tld\nwatermark: |\n  <p style=\"text-align: center;\">\n  <small>Powered by <a href=\"https://github.com/jeromew21/solutus\">Solutus</a></small>\n  </p>\nstylesheets: |\n<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/styles.css\" />\nscripts: |\n<script></script>\nrecents-count: 3\nadvanced: false\n"

    styles_file = "body {\nbackground-color: #EEEEEE;\n}\n"

    default_file = "<!DOCTYPE html>\n<head>\n<title>{{title}}</title>\n{{{stylesheets}}}\n</head>\n<body>\n<div id=\"solutus-everything\">\n    {{#blog}}\n        <h1>{{title}}</h1>\n        {{{date}}}\n    {{/blog}}\n    {{{content}}}\n    <h3>Recent Posts</h3>\n    {{{recents}}}\n    <small style=\"display: block; text-align: center;\">&copy; {{year}} {{author}}</small>\n    {{{watermark}}}\n</div>\n{{{scripts}}}\n</body>\n</html>\n"

    datetime = Time.now.strftime(BLOG_DATE_DATA)
    test_file = "title: Example Blog Post\ndate: \#{datetime}\nsubtitle: an example post...\n---\n*This is an example blog post page!*\n"

    index_file = "template: default\ntitle: Home page\ntype: html\ncontent: |\n<h1>Hello World!</h1>\n<p>\n    this is a test\n</p>\n"

    files = {
        File.join(name, "settings.yml") => settings_file,
        File.join(name, ".gitignore") => PASSWORD_FILE + "\n",
        File.join(name, "static", "css", "styles.css") => styles_file,
        File.join(name, "templates", "default.html") => default_file,
        File.join(name, "pages", "posts", "test.md") => test_file,
        File.join(name, "pages", "site-pages", "index.yml") => index_file,
    }
    
    files.each do |filename, contents|
        puts "Created #{filename}"
        f = File.new(filename, "w")
        f.write(contents)
        f.close
    end

    puts "Created new project #{name}"
end

.page_urlsObject



538
539
540
# File 'lib/solutus.rb', line 538

def self.page_urls
    @@page_urls
end

.prettify_date(date) ⇒ Object



888
889
890
# File 'lib/solutus.rb', line 888

def self.prettify_date(date)
    date.strftime("%b %e") + DAY_ENDINGS[date.strftime("%e").to_i]
end

.relative_path_to_all_files_in_dir(dir) ⇒ Object



919
920
921
922
923
924
925
926
927
928
929
930
931
# File 'lib/solutus.rb', line 919

def self.relative_path_to_all_files_in_dir(dir)
    result = Array.new
    Dir.entries(dir).each do |entry|
        next if entry == "." || entry == ".."
        path = File.join(dir, entry)
        if File.file?(path)
            result.push(entry)
        elsif File.directory?(path)
            result = result + relative_path_to_all_files_in_dir(path).collect {|x| File.join(entry, x)}
        end
    end
    result
end

.render_markdown(markdown) ⇒ Object



904
905
906
# File 'lib/solutus.rb', line 904

def self.render_markdown(markdown)
    Redcarpet::Markdown.new(Redcarpet::Render::HTML.new).render(markdown)
end

.render_page(templates, default_data, data, blog = false) ⇒ Object



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
# File 'lib/solutus.rb', line 788

def self.render_page(templates, default_data, data, blog=false)
    if data.key?("template")
        SolutusStache.template = templates[data["template"]]
    else
        SolutusStache.template = templates[DEFAULT_TEMPLATE]
    end
    result = SolutusStache.new
    default_data.each do |key, val|
        result[key.to_sym] = val || ""
    end
    data.each do |key, val|
        next if key == "template"
        if key != "title"
            val = wrap_element(key, val)
        end
        result[key.to_sym] = val || ""
    end
    result[:blog] = blog || false
    result[:year] = Time.now.year
    result.render
end

.serveObject



606
607
608
609
610
# File 'lib/solutus.rb', line 606

def self.serve
    puts "Solutus is serving"
    puts "View at http://localhost:4567/"
    Solutus_Server.run!
end

.templatesObject



542
543
544
# File 'lib/solutus.rb', line 542

def self.templates
    @@templates
end

.wrap_element(key, content) ⇒ Object



908
909
910
911
912
913
914
915
916
917
# File 'lib/solutus.rb', line 908

def self.wrap_element(key, content)
    if content.is_a?(Time)
        content = correct_time(content).strftime(BLOG_DATE_FORMAT)
    end
    result = ""
    result += "<div id=\"solutus-#{key}\">\n"
    result += content
    result += "</div>"
    result
end