Skip to content

Commit

Permalink
very first version
Browse files Browse the repository at this point in the history
  • Loading branch information
kpym committed Aug 19, 2021
0 parents commit ef51b5f
Show file tree
Hide file tree
Showing 16 changed files with 1,641 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Text files have auto line endings
* text=auto

# Go source files always have LF line endings
*.go text eol=lf
34 changes: 34 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# the configuration of goreleaser is in
# .goreleaser.yml in the root folder

# workflow name
name: goreleaser

# on events
on:
push:
tags:
- '*'

jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.16
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
38 changes: 38 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# This is an example goreleaser.yaml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
project_name: lol
before:
hooks:
# You may remove this if you don't use go modules.
- go mod download
# you may remove this if you don't need go generate
- go generate ./...
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
ldflags:
- -s -w -X github.com/kpym/lol/app.Version={{.Version}}
archives:
- replacements:
darwin: MacOS
linux: Linux
windows: Windows
386: 32bit
amd64: 64bit
format_overrides:
- goos: windows
format: zip
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ .Tag }}"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Kroum Tzanev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# lol a LaTeX online compiler CLI tool

lol is a small command line interface (CLI) that sends local files to distant server (https://latexonline.cc/ or [latex.ytotech.com](https://github.com/YtoTech/latex-on-http)) for LaTeX compilation and save the resulting `pdf`.

## Usage

To compile a single `main.tex` file to `main.pdf` using `latexonline.cc`:
```
> ./lol main.tex
```

To compile `main.tex` including `png` images in `imgs` folder with `xelatex` using `latex.ytotech.com`:
```
> ./lol -s ytotech -c xelatex main.tex imgs/*.png
```

A help message is provided:
```
> ./lol -h
lol (version: ---)
LaTeX online compiler. More info at www.github.com/kpym/lol.
Available options:
-s, --service string Service can be laton or ytotex.
-c, --compiler string One of pdflatex,xelatex or lualatex.
For ytotex platex, uplatex and context are also available.
(default "pdflatex")
-f, --force Do not use the laton cache. Force compile. Ignored by ytotech.
-b, --biblio string Can be bibtex or biber for ytotex. Not used by laton.
-o, --output string The name of the pdf file. If empty, same as the main tex file.
-m, --main string The main tex file to compile.
-q, --quiet Prevent any output.
-v, --verbose Print info and errors. No debug info is printed.
--debug Print everithing (debug info included).
Examples:
> lol main.tex
> lol -s ytotech -c xelatex main.tex
> lol main.tex personal.sty images/img*.pdf
> cat main.tex | lol -c lualatex -o out.pdf
```

## License

[MIT](LICENSE) for this code _(but all used libraries may have different licence)_.
238 changes: 238 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
package app

import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"

"github.com/kpym/lol/builder"
"github.com/kpym/lol/log"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

// parameters constants
const (
// The name of our config file, without the file extension
// because viper supports many different config file languages.
defaultConfigFilename = "lol"

// The environment variable prefix of all environment variables.
// For example, --server flag is bound to $LOL_SERVER.
envPrefix = "LOL"

// If the main file is piped to stdin, this name is used.
MainNameIfStdin = "main_from_stdin.tex"
)

// The version that is set by goreleaser
var Version = "dev"

// Help displays usage message if -h/--help flag is set or in case of falg error.
func Help() {
var out = os.Stderr
fmt.Fprintf(out, "lol (version: %s)\n", Version)
fmt.Fprintln(out, "LaTeX online compiler. More info at www.github.com/kpym/lol.")
fmt.Fprintln(out, "\nAvailable options:")
pflag.PrintDefaults()

fmt.Fprintln(out, "\nExamples:")
fmt.Fprintln(out, "> lol main.tex")
fmt.Fprintln(out, "> lol -s ytotech -c xelatex main.tex")
fmt.Fprintln(out, "> lol main.tex personal.sty images/img*.pdf")
fmt.Fprintln(out, "> cat main.tex | lol -c lualatex -o out.pdf")
fmt.Fprintln(out, "")
}

// InitFlag define the CLI flags.
func InitFlags() {
pflag.StringP("service", "s", "", "Service can be laton or ytotex.")
pflag.StringP("compiler", "c", "pdflatex", "One of pdflatex,xelatex or lualatex.\nFor ytotex platex, uplatex and context are also available.\n")
pflag.BoolP("force", "f", false, "Do not use the laton cache. Force compile. Ignored by ytotech.")
pflag.StringP("biblio", "b", "", "Can be bibtex or biber for ytotex. Not used by laton.")
pflag.StringP("output", "o", "", "The name of the pdf file. If empty, same as the main tex file.")
pflag.StringP("main", "m", "", "The main tex file to compile.")
pflag.BoolP("quiet", "q", false, "Prevent any output.")
pflag.BoolP("verbose", "v", false, "Print info and errors. No debug info is printed.")
pflag.Bool("debug", false, "Print everithing (debug info included).")
pflag.Parse()
}

// stringsIn checks if the first argument is equal to one of the following parameters.
// Used in GetParameters only.
func stringIn(str string, values ...string) bool {
for _, v := range values {
if str == v {
return true
}
}
return false
}

// GetParameters use pflag and viper to set the parameters.
func GetParameters(params *builder.Parameters) error {
v := viper.New()

// Bind the current command's flags to viper
v.BindPFlags(pflag.CommandLine)

// Set the base name of the config file, without the file extension.
v.SetConfigName(defaultConfigFilename)

// We are only looking in the current working directory.
v.AddConfigPath(".")

// Attempt to read the config file, gracefully ignoring errors
// caused by a config file not being found. Return an error
// if we cannot parse the config file.
if err := v.ReadInConfig(); err != nil {
// It's okay if there isn't a config file
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return err
}
}

// Set environment variables prefix.
v.SetEnvPrefix(envPrefix)

// Bind to environment variables.
// I we have --compsed-flags we can use :
// v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv()

// Transfer the parameters values to params struct.
err := v.Unmarshal(params)
if err != nil {
return err
}

// set log level
level := log.ErrorLevel
if v.GetBool("quiet") {
level = log.Quiet
}
if v.GetBool("verbose") {
level = log.InfoLevel
}
if v.GetBool("debug") {
level = log.DebugLevel
}
// the default writer is os.Stdout (color.Output)
params.Log = log.New(log.WithLevel(level), log.WithColor())

// Chack if the service support the requested options.
if !stringIn(params.Service, "laton", "ytotech", "") {
return fmt.Errorf("Unknown %s service.", params.Service)
}
if stringIn(params.Compiler, "platex", "uplatex", "context") {
if params.Service == "laton" {
return fmt.Errorf("Laton do not support %s compiler.", params.Compiler)
}
if params.Service == "" {
params.Service = "ytotech"
}
} else if !stringIn(params.Compiler, "pdflatex", "xelatex", "lualatex") {
return fmt.Errorf("Non supported %s compiler.", params.Compiler)
}
if params.Biblio != "" {
if params.Service == "laton" {
return fmt.Errorf("Laton do not support %s bibliography.", params.Biblio)
}
if params.Service == "" {
params.Service = "ytotech"
}
}
if params.Service == "" {
// TODO : choose the fastest ?
params.Service = "laton"
}
// check if the input is piped
fi, err := os.Stdin.Stat()
if err == nil {
params.PipedMain = ((fi.Mode() & os.ModeCharDevice) == 0) && (fi.Mode()&os.ModeNamedPipe != 0)
params.Log.Debugf("Piped input: %v, Stdin mode: %v.\n", params.PipedMain, fi.Mode())
}
// Get the patterns
params.Patterns = append(pflag.Args(), params.Patterns...)
if len(params.Patterns) == 0 && params.Main == "" && !params.PipedMain {
return fmt.Errorf("Missing file to compile.")
}
if params.Main != "" && params.PipedMain {
return fmt.Errorf("Main file can't be set when there is piped input.")
}
// set the main file (if needed)
if params.Main == "" {
if !params.PipedMain {
params.Main = params.Patterns[0]
}
} else {
params.Patterns = append([]string{params.Main}, params.Patterns...)
}

// set the output (if not piped input)
if params.Output == "" && params.Main != "" {
params.Output = strings.TrimSuffix(params.Main, ".tex") + ".pdf"
}

// set Main if piped input
if params.PipedMain {
params.Main = MainNameIfStdin
}

return nil
}

// GetFiles read all files based on params.Patterns.
func GetFiles(params builder.Parameters) (builder.Files, error) {
// temporary variables
var (
err error
filedata []byte
)
// files to be read
files := make(builder.Files)
// get the main file
if params.PipedMain {
params.Log.Debug("Read the main file from stdin.")
filedata, err = ioutil.ReadAll(os.Stdin)
} else {
params.Log.Debugf("Read the main file from %s.\n", params.Main)
filedata, err = ioutil.ReadFile(params.Main)
}
files[params.Main] = filedata
if err != nil {
return nil, fmt.Errorf("Error while reading the main file: %w", err)
}
// get all other files (if any) that are readable
for _, pat := range params.Patterns {
// check if is folder or pattern
patInfo, err := os.Stat(pat)
if err == nil {
if patInfo.IsDir() {
pat = path.Join(pat, "*")
}
}
names, _ := filepath.Glob(pat)
for _, fname := range names {
// if on Windows, transform to unix name
uname := filepath.ToSlash(fname)
// if this file is already present
if _, ok := files[uname]; ok {
continue
}
// read the file, or skipt it if not readable
filedata, err = ioutil.ReadFile(fname)
if err == nil {
files[uname] = filedata
params.Log.Debugf("File %s (%d bytes) added to the list.", uname, len(filedata))
} else {
params.Log.Debugf("Probleam reading support file (we skip it): %s.", fname)
}
}
}

return files, nil
}
3 changes: 3 additions & 0 deletions app/app.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# app.md

This file is here only for testing.
Loading

0 comments on commit ef51b5f

Please sign in to comment.