<commit_before>fs              = require 'fs'
sys             = require 'sys'

cli             = require 'cli'
git             = require 'gitjs'
rest            = require 'restler'

renderer                            = require './renderer'
{ htmlResponse, cacheResponse }     = require './http_utils'
{ cacheFileFromURL }                = require './cache'
VERSION                             = require './VERSION'

{
    VIEWER_URL
    PROTO_DIR
    SETTINGS_FILE
    LIB_DIR
    PROTO_FILES
} = require './settings'


CWD         = process.cwd()

# Some helpers...

pad = (val) ->
    if val < 10
        return "0#{ val }"
    else
        return val.toString()

stamp = (args...) ->
    t = new Date()
    hour = pad(t.getHours())
    min = pad(t.getMinutes())
    sec = pad(t.getSeconds())
    t = "#{ hour }:#{ min }:#{ sec }"
    sys.puts("#{ t }: #{ args.join(' ') }")

quitWithMsg = (message) ->
    stamp(message)
    process.exit()

projectPath = (project_name) ->
    return "#{ CWD }/#{ project_name }"



# Fetch a Gist from the GitHub API. Calls the callback whether or not the
# request was successful.
getGist = (url, callback) ->
    GIST_API = 'https://api.github.com/gists'
    post_req = rest.get(GIST_API + url)
    post_req.on 'complete', (data, response) ->
        callback(data, response.statusCode)


# Initialize a project using the specified project name and the default
# template. Optionally, use the specified Gist URL/ID to load a gist and use
# that as the template.
initializeProject = (project_name, gist_url=null, cli_args) ->

    # No name was specified, so use a generated on in the format
    # proto-YYYYMMDD-N, where N is an incremental counter to avoid conflicts.
    if not project_name and not gist_url
        counter = 1
        date = new Date()
        makeName = -> "proto-#{ date.getFullYear() }#{ date.getMonth() + 1 }#{ date.getDate() }-#{ counter }"
        project_name = makeName()
        while fs.existsSync(project_name)
            counter += 1
            project_name = makeName()

    # Actual init function, taking a set of templates for each file. If the
    # project_path already exists, warns and quits.
    doInit = (templates) ->
        project_path = "#{ CWD }/#{ project_name }"

        sys.puts("Initializing '#{ project_name }' in #{ project_path }")

        if not fs.existsSync(project_path)
            fs.mkdirSync(project_path)
            for file_name in PROTO_FILES
                fs.writeFileSync("#{ project_path }/#{ file_name }", templates[file_name])
            quitWithMsg("#{ project_name } initialized!")
        else
            quitWithMsg("Error: #{ project_path } already exists")

    if gist_url
        # Parse the ID and fetch the Gist, using that as a template.
        gist_id = gist_url.split('/')
        gist_id = gist_id[gist_id.length - 1]
        stamp("Fetching Gist: #{ gist_id }")
        getGist '/' + gist_id, (data, status_code) ->
            if status_code isnt 200
                quitWithMsg("Unable to fetch gist: #{ status_code }")
            else
                # Load the Gist contents into a template for the init.
                templates = {}
                for proto_f in PROTO_FILES
                    # If the needed file isn't in the Gist, warn and quit.
                    if not data.files?[proto_f]?
                        quitWithMsg("Gist is invalid Proto project, missing file: #{ proto_f }")
                    else
                        templates[proto_f] = data.files[proto_f].content

                if cli_args[0]?
                    # If there is a second name specified, use that as the
                    # project name.
                    project_name = cli_args[0]
                else
                    # Use the name specified name in the settings file.
                    project_name = JSON.parse(templates['settings.json']).name

                stamp("Fetched Gist, project name is #{ project_name }")

                doInit(templates)

    else
        # Do the init with the default template.
        doInit
            'script.coffee' : 'console.log "loaded"\n\n\n'
            'markup.jade'   : 'h1 Hello, world!\n\n\n'
            'style.styl'    : '@import \'nib\'\n\nh1\n    font-weight 300\n    font-family Helvetica\n\n\n'
            'notes.md'      : "# #{ project_name }\n\n\n"
            'settings.json' : """{
                "name": "#{ project_name }",
                "proto_version": "#{ VERSION }",
                "script_libraries": [
                    "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.2/jquery.ui.touch-punch.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.3/underscore.string.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
                ],
                "style_libraries": [
                    "https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/base/jquery.ui.all.css"
                ],
                "extra_head_markup": "<meta name='viewport' content='width=device-width'>"
            }"""


# Send the project to a Gist, creating a new one or updating an existing one.<commit_msg>Update underscore library<commit_after>fs              = require 'fs'
sys             = require 'sys'

cli             = require 'cli'
git             = require 'gitjs'
rest            = require 'restler'

renderer                            = require './renderer'
{ htmlResponse, cacheResponse }     = require './http_utils'
{ cacheFileFromURL }                = require './cache'
VERSION                             = require './VERSION'

{
    VIEWER_URL
    PROTO_DIR
    SETTINGS_FILE
    LIB_DIR
    PROTO_FILES
} = require './settings'


CWD         = process.cwd()

# Some helpers...

pad = (val) ->
    if val < 10
        return "0#{ val }"
    else
        return val.toString()

stamp = (args...) ->
    t = new Date()
    hour = pad(t.getHours())
    min = pad(t.getMinutes())
    sec = pad(t.getSeconds())
    t = "#{ hour }:#{ min }:#{ sec }"
    sys.puts("#{ t }: #{ args.join(' ') }")

quitWithMsg = (message) ->
    stamp(message)
    process.exit()

projectPath = (project_name) ->
    return "#{ CWD }/#{ project_name }"



# Fetch a Gist from the GitHub API. Calls the callback whether or not the
# request was successful.
getGist = (url, callback) ->
    GIST_API = 'https://api.github.com/gists'
    post_req = rest.get(GIST_API + url)
    post_req.on 'complete', (data, response) ->
        callback(data, response.statusCode)


# Initialize a project using the specified project name and the default
# template. Optionally, use the specified Gist URL/ID to load a gist and use
# that as the template.
initializeProject = (project_name, gist_url=null, cli_args) ->

    # No name was specified, so use a generated on in the format
    # proto-YYYYMMDD-N, where N is an incremental counter to avoid conflicts.
    if not project_name and not gist_url
        counter = 1
        date = new Date()
        makeName = -> "proto-#{ date.getFullYear() }#{ date.getMonth() + 1 }#{ date.getDate() }-#{ counter }"
        project_name = makeName()
        while fs.existsSync(project_name)
            counter += 1
            project_name = makeName()

    # Actual init function, taking a set of templates for each file. If the
    # project_path already exists, warns and quits.
    doInit = (templates) ->
        project_path = "#{ CWD }/#{ project_name }"

        sys.puts("Initializing '#{ project_name }' in #{ project_path }")

        if not fs.existsSync(project_path)
            fs.mkdirSync(project_path)
            for file_name in PROTO_FILES
                fs.writeFileSync("#{ project_path }/#{ file_name }", templates[file_name])
            quitWithMsg("#{ project_name } initialized!")
        else
            quitWithMsg("Error: #{ project_path } already exists")

    if gist_url
        # Parse the ID and fetch the Gist, using that as a template.
        gist_id = gist_url.split('/')
        gist_id = gist_id[gist_id.length - 1]
        stamp("Fetching Gist: #{ gist_id }")
        getGist '/' + gist_id, (data, status_code) ->
            if status_code isnt 200
                quitWithMsg("Unable to fetch gist: #{ status_code }")
            else
                # Load the Gist contents into a template for the init.
                templates = {}
                for proto_f in PROTO_FILES
                    # If the needed file isn't in the Gist, warn and quit.
                    if not data.files?[proto_f]?
                        quitWithMsg("Gist is invalid Proto project, missing file: #{ proto_f }")
                    else
                        templates[proto_f] = data.files[proto_f].content

                if cli_args[0]?
                    # If there is a second name specified, use that as the
                    # project name.
                    project_name = cli_args[0]
                else
                    # Use the name specified name in the settings file.
                    project_name = JSON.parse(templates['settings.json']).name

                stamp("Fetched Gist, project name is #{ project_name }")

                doInit(templates)

    else
        # Do the init with the default template.
        doInit
            'script.coffee' : 'console.log "loaded"\n\n\n'
            'markup.jade'   : 'h1 Hello, world!\n\n\n'
            'style.styl'    : '@import \'nib\'\n\nh1\n    font-weight 300\n    font-family Helvetica\n\n\n'
            'notes.md'      : "# #{ project_name }\n\n\n"
            'settings.json' : """{
                "name": "#{ project_name }",
                "proto_version": "#{ VERSION }",
                "script_libraries": [
                    "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.2/jquery.ui.touch-punch.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/underscore.string/2.3.3/underscore.string.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js",
                    "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
                ],
                "style_libraries": [
                    "https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/base/jquery.ui.all.css"
                ],
                "extra_head_markup": "<meta name='viewport' content='width=device-width'>"
            }"""


# Send the project to a Gist, creating a new one or updating an existing one.
{'fraction_non_alphanumeric': 0.12437810945273632, 'fraction_numerical': 0.007640369580668088, 'mean_word_length': 1.8065320368985291, 'pattern_counts': {'":': 10, '<': 7, '<?xml version=': 0, '>': 25, 'https://': 18, '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': '3575960', 'n_tokens_mistral': 3559, 'n_tokens_neox': 3366, 'n_words': 817}