Skip to content

Commit

Permalink
Merge develop into master (#1)
Browse files Browse the repository at this point in the history
Initial master commit.
  • Loading branch information
efine authored Aug 14, 2018
1 parent 883cd70 commit 72a1793
Show file tree
Hide file tree
Showing 13 changed files with 659 additions and 0 deletions.
63 changes: 63 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto

###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
6 changes: 6 additions & 0 deletions bakeit-fsharp/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
41 changes: 41 additions & 0 deletions bakeit-fsharp/AssemblyInfo.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace bakeit_fsharp.AssemblyInfo

open System.Reflection
open System.Runtime.CompilerServices
open System.Runtime.InteropServices

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[<assembly: AssemblyTitle("bakeit-fsharp")>]
[<assembly: AssemblyDescription("")>]
[<assembly: AssemblyConfiguration("")>]
[<assembly: AssemblyCompany("")>]
[<assembly: AssemblyProduct("bakeit-fsharp")>]
[<assembly: AssemblyCopyright("Copyright © 2017")>]
[<assembly: AssemblyTrademark("")>]
[<assembly: AssemblyCulture("")>]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[<assembly: ComVisible(false)>]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[<assembly: Guid("ba7fbf99-e113-4c92-ac90-8e02dcbe13a9")>]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [<assembly: AssemblyVersion("1.0.*")>]
[<assembly: AssemblyVersion("1.0.0.0")>]
[<assembly: AssemblyFileVersion("1.0.0.0")>]

do
()
80 changes: 80 additions & 0 deletions bakeit-fsharp/Bakeit.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
module Bakeit

open System
open GetOpts
open Upload
open WebBrowser

let optItem (opts: Opts) key = opts.Item(key)

let toString (item : DocoptNet.ValueObject) = string item.Value

let toUInt (item : DocoptNet.ValueObject) = uint32 item.AsInt

let toList (item : DocoptNet.ValueObject) = item.AsList

let toBool (item : DocoptNet.ValueObject) =
match item with
| _ when item.IsTrue -> true
| _ when item.IsFalse -> false
| _ -> failwithf "Not a bool: %A" item

let run argv =
let debug = false
let api_key = Ini.read()
let opts = getopts argv
if debug then opts |> Map.iter (fun k v -> printfn "%s : %A" k v)

let lookup = optItem opts

let file_name () = "<filename>" |> lookup |> toString

let read_data f =
match f with
| "-" -> stdin.ReadToEnd()
| _ -> System.IO.File.ReadAllText(f)

let title () = match "--title" |> lookup |> toString with
| "" | "false" -> file_name.ToString()
| str -> str

let make_cfg () =
if "--get-pastes" |> lookup |> toBool then
{ Upload.defaultCfg with
GetPastes = true;
ApiKey = api_key
}
else
{ Upload.defaultCfg with
Data = read_data <| file_name ();
ApiKey = api_key;
Title = title ();
Language = "--language" |> lookup |> toString;
Duration = "--duration" |> lookup |> toUInt;
MaxViews = "--max-views" |> lookup |> toUInt;
OpenBrowser = "--open-browser" |> lookup |> toBool
}



let cfg = make_cfg ()
if cfg.GetPastes then
printfn "%s" <| get_pastes cfg
else
let url = upload cfg
printfn "%s" url
if cfg.OpenBrowser then
open_url url

0


[<EntryPoint>]
let main argv =
try
run argv
with
| exc ->
printfn "%s" exc.Message
printf "%s" exc.StackTrace
1
31 changes: 31 additions & 0 deletions bakeit-fsharp/GetOpts.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module GetOpts

[<Literal>]
let version = "0.1"

open DocoptNet

type Opts = Map<string, ValueObject>

let getopts (argv : string[]) : Opts =
let usage = @"Bakeit.
Usage:
bakeit.exe -g
bakeit.exe [options] <filename>
Options:
-h, --help Show this help.
-g, --get-pastes Get JSON describing all pastes [default: false].
-t <t>, --title=<t> The title of the paste [default: false].
-l <l>, --language=<l> The language highlighter to use [default: text].
-d <d>, --duration=<d> The duration (in minutes) before the paste expires [default: 1440].
-v <v>, --max-views=<v> How many times this paste can be viewed before it expires [default: 20].
-b, --open-browser Automatically open a browser window when done [default: false].
-V, --version Show the version and quit.
"
let docopt = new DocoptNet.Docopt()
let opts = docopt.Apply (usage, argv, help=true, exit=true)
let folder (m : Map<string, ValueObject>) (KeyValue(k, v)) = m.Add (k, v)
Seq.fold folder Map.empty opts
65 changes: 65 additions & 0 deletions bakeit-fsharp/Ini.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
module Ini

open System
open System.IO
open IniParser

[<Literal>]
let CFG_PATH = @".config\bakeit.cfg"

[<Literal>]
let HOME = "USERPROFILE"

// The definition of Result in FSharp.Core
[<StructuralEquality; StructuralComparison>]
[<CompiledName("FSharpResult`2")>]
[<Struct>]
type Result<'T,'TError> =
| Ok of ResultValue:'T
| Error of ErrorValue:'TError

let home_dir =
match Environment.GetEnvironmentVariable HOME with
| null -> Error (sprintf "No %s environment variable!" HOME)
| dirname -> Ok dirname


let get_section section (config : INIContents) =
match List.tryFind (fun (sec_key, _sec_vals) -> sec_key.Equals(section)) config with
| Some (_sec_key, secdata) -> secdata
| None -> let h = match home_dir with
| Ok h' -> h'
| Error _ -> "(unknown)"
failwithf @"[%s] section not found. Please add a [%s] section to the %s\%s file and try again."
section section h CFG_PATH

let get_val (key: string) (section: string) (secdata : (string * string) list) =
match List.tryFind (fun (k, _v) -> k.Equals(key)) secdata with
| Some (_k, v) -> v
| None ->
failwithf @"No %s entry found. Please add an entry for %s to the [%s] section with your API key in it. You can find the latter on your account page on https://www.pastery.net."
key key section

//--------------------------------------------------------------------
let load_from_string ini_text =
match parse ini_text with
| INIFile.Values ini_data -> ini_data
| INIFile.Error _msg ->
failwithf @"Config file not found. Make sure you have a config file
at ~/%s with a [pastery] section containing
your Pastery API key, which you can get from your
https://www.pastery.net account page." CFG_PATH
//--------------------------------------------------------------------
let read () =
match home_dir with
| Ok dir ->
System.IO.File.ReadAllText(Path.Combine(dir, CFG_PATH)).Trim()
|> load_from_string
|> get_section "pastery"
|> get_val "api_key" "pastery"
| Error msg -> failwith msg

//--------------------------------------------------------------------


//--------------------------------------------------------------------
67 changes: 67 additions & 0 deletions bakeit-fsharp/IniParser.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
(*
* Copyright 2014 Anthony Perez (@amazingant)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)

module IniParser

open FParsec

type INIContents = (string * (string * string) list) list

type INIFile =
| Error of string
| Values of INIContents


let parse (ini: string) : INIFile =
let clearNone v = List.fold (fun x y -> match y with None -> x | Some(z) -> z :: x) [] v
let escape =
pchar '\\' >>.
anyOf "\"\\/trn" |>>
function
| 't' -> '\t'
| 'r' -> '\r'
| 'n' -> '\n'
| c -> c
let valueParser: Parser<(string * string) option, unit> = parse {
do! spaces
let! comment = opt <| skipChar '#'
match comment with
| Some(_) ->
do! skipRestOfLine true
return None
| None ->
let! name = many1 (noneOf [' '; '['; ']'; '=']) .>> spaces .>> skipChar '='
let! value = (many <| skipChar ' ') >>. many (noneOf ['\n'; '\\'] <|> escape)
do! skipRestOfLine true
return Some(System.String.Concat(name), System.String.Concat(value).Trim())
}

let sectionParser: Parser<(string * (string * string) list) option, unit> = parse {
do! spaces
let! comment = opt <| skipChar '#'
match comment with
| Some(_) ->
do! skipRestOfLine true
return None
| None ->
let! section = spaces >>. skipChar '[' >>. many1 (noneOf [' '; '['; ']']) .>> skipChar ']' .>> skipRestOfLine true
let! values = many valueParser
return Some(System.String.Concat(section), clearNone values)
}

match run (many sectionParser) ini with
| Success (v, _, _) -> Values(clearNone v)
| Failure (msg, _err, _) -> Error("There was a problem parsing the settings file:\n" + msg)
14 changes: 14 additions & 0 deletions bakeit-fsharp/OsDetection.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module OsDetection

open System

type OS =
| MacOS
| Windows
| Linux

let getOS =
match int Environment.OSVersion.Platform with
| 4 | 128 -> Linux
| 6 -> MacOS
| _ -> Windows
Loading

0 comments on commit 72a1793

Please sign in to comment.