WIP: ♻️ Restructure test #36

Closed
ada wants to merge 46 commits from ada/rewrite-test into main
19 changed files with 560 additions and 355 deletions
Showing only changes of commit 021e4a731a - Show all commits

7
.env
View file

@ -1,7 +1,6 @@
PLAKKEN_INTERFACE=0.0.0.0 PLAKKEN_LISTEN=:3000
PLAKKEN_PORT=3000 PLAKKEN_REDIS_ADDRESS=localhost:6379
PLAKKEN_REDIS_ADDR=localhost:6379
PLAKKEN_REDIS_USER= PLAKKEN_REDIS_USER=
PLAKKEN_REDIS_PASSWORD= PLAKKEN_REDIS_PASSWORD=
PLAKKEN_REDIS_DB=0 PLAKKEN_REDIS_DB=0
PLAKKEN_REDIS_URL_LEN=5 PLAKKEN_URL_LENGTH=5

4
.gitignore vendored
View file

@ -1,3 +1,7 @@
# IDE specific
.idea
.vscode
### Go ### ### Go ###
*.exe *.exe
*.exe~ *.exe~

View file

@ -1,54 +0,0 @@
package main
import (
"github.com/joho/godotenv"
"log"
"os"
"strconv"
)
type Config struct {
host string
port string
redisAddr string
redisUser string
redisPassword string
redisDB int
urlLength int
}
func GetConfig() Config {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
port := os.Getenv("PLAKKEN_PORT")
redisAddr := os.Getenv("PLAKKEN_REDIS_ADDR")
db := os.Getenv("PLAKKEN_REDIS_DB")
uLen := os.Getenv("PLAKKEN_REDIS_URL_LEN")
if port == "" || redisAddr == "" {
log.Fatal("Missing or invalid PLAKKEN_PORT or PLAKKEN_REDIS_ADDR")
}
redisDB, err := strconv.Atoi(db)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_DB")
}
urlLen, err := strconv.Atoi(uLen)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_URL_LEN")
}
return Config{
host: os.Getenv("PLAKKEN_INTERFACE"),
port: port,
redisAddr: redisAddr,
redisUser: os.Getenv("PLAKKEN_REDIS_USER"),
redisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
redisDB: redisDB,
urlLength: urlLen,
}
}

49
db.go
View file

@ -1,49 +0,0 @@
package main
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
func ConnectDB() *redis.Client {
localDb := redis.NewClient(&redis.Options{
Addr: currentConfig.redisAddr,
Username: currentConfig.redisUser,
Password: currentConfig.redisPassword,
DB: currentConfig.redisDB,
})
return localDb
}
func insertPaste(key string, content string, secret string, ttl time.Duration) {
type dbSchema struct {
content string
secret string
}
hash := dbSchema{
content: content,
secret: secret,
}
err := db.HSet(ctx, key, "content", hash.content)
if err != nil {
log.Println(err)
}
err = db.HSet(ctx, key, "secret", hash.secret)
if ttl > -1 {
db.Expire(ctx, key, ttl)
}
}
func getContent(key string) string {
return db.HGet(ctx, key, "content").Val()
}
func DeleteContent(key string) {
db.Del(ctx, key)
}

4
go.mod
View file

@ -1,6 +1,6 @@
module plakken module git.gnous.eu/gnouseu/plakken
go 1.21 go 1.22
require ( require (
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1

59
internal/config/config.go Normal file
View file

@ -0,0 +1,59 @@
package config
import (
"log"
"os"
"strconv"
"github.com/joho/godotenv"
)
// InitConfig Structure for program initialisation
type InitConfig struct {
ListenAddress string
RedisAddress string
RedisUser string
RedisPassword string
RedisDB int
UrlLength uint8
}
// GetConfig Initialise configuration form .env
func GetConfig() InitConfig {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
listenAddress := os.Getenv("PLAKKEN_LISTEN")
redisAddress := os.Getenv("PLAKKEN_REDIS_ADDRESS")
db := os.Getenv("PLAKKEN_REDIS_DB")
uLen := os.Getenv("PLAKKEN_URL_LENGTH")
if listenAddress == "" || redisAddress == "" {
log.Fatal("Missing or invalid listenAddress or PLAKKEN_REDIS_ADDRESS")
}
redisDB, err := strconv.Atoi(db)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_DB")
}
urlLength, err := strconv.Atoi(uLen)
if err != nil {
log.Fatal("Invalid PLAKKEN_URL_LENGTH")
}
if urlLength > 255 {
log.Fatal("PLAKKEN_URL_LENGTH cannot be greater than 255")
}
return InitConfig{
ListenAddress: listenAddress,
RedisAddress: redisAddress,
RedisUser: os.Getenv("PLAKKEN_REDIS_USER"),
RedisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
RedisDB: redisDB,
UrlLength: uint8(urlLength),
}
}

View file

@ -0,0 +1,7 @@
package constant
import "time"
const (
HTTPTimeout = 3 * time.Second
)

64
internal/database/db.go Normal file
View file

@ -0,0 +1,64 @@
package database
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
type DBConfig struct {
DB *redis.Client
}
var ctx = context.Background()
// InitDB initialise redis connection settings
func InitDB(addr string, user string, password string, db int) *redis.Options {
DBConfig := &redis.Options{
Addr: addr,
Username: user,
Password: password,
DB: db,
}
return DBConfig
}
// ConnectDB make new database connection
func ConnectDB(dbConfig *redis.Options) *redis.Client {
localDb := redis.NewClient(dbConfig)
return localDb
}
func (config DBConfig) InsertPaste(key string, content string, secret string, ttl time.Duration) {
type dbSchema struct {
content string
secret string
}
hash := dbSchema{
content: content,
secret: secret,
}
err := config.DB.HSet(ctx, key, "content", hash.content).Err()
if err != nil {
log.Println(err)
}
err = config.DB.HSet(ctx, key, "secret", hash.secret).Err()
if err != nil {
log.Println(err)
}
if ttl > -1 {
config.DB.Expire(ctx, key, ttl)
}
}
func (config DBConfig) UrlExist(url string) bool {
return config.DB.Exists(ctx, url).Val() == 1
}
func (config DBConfig) VerifySecret(url string, secret string) bool {
return secret == config.DB.HGet(ctx, url, "secret").Val()
}

View file

@ -0,0 +1,51 @@
package httpServer
import (
"log"
"net/http"
"git.gnous.eu/gnouseu/plakken/internal/constant"
"git.gnous.eu/gnouseu/plakken/internal/web/plak"
"git.gnous.eu/gnouseu/plakken/internal/web/static"
"github.com/redis/go-redis/v9"
)
type ServerConfig struct {
HTTPServer *http.Server
UrlLength uint8
DB *redis.Client
}
// Configure HTTP router
func (config ServerConfig) router(_ http.ResponseWriter, _ *http.Request) {
WebConfig := plak.WebConfig{
DB: config.DB,
UrlLength: config.UrlLength,
}
http.HandleFunc("GET /{$}", static.Home)
http.HandleFunc("GET /{key}/{settings...}", WebConfig.View)
http.HandleFunc("GET /static/{file}", static.ServeStatic)
http.HandleFunc("POST /{$}", WebConfig.Create)
http.HandleFunc("DELETE /{key}", WebConfig.Delete)
}
// Config Configure HTTP server
func Config(listenAddress string) *http.Server {
server := &http.Server{
Addr: listenAddress,
ReadTimeout: constant.HTTPTimeout,
WriteTimeout: constant.HTTPTimeout,
}
return server
}
// Server Start HTTP server
func (config ServerConfig) Server() {
log.Println("Listening on " + config.HTTPServer.Addr)
http.HandleFunc("/", config.router)
log.Fatal(config.HTTPServer.ListenAndServe())
}

17
internal/utils/error.go Normal file
View file

@ -0,0 +1,17 @@
package utils
type ParseIntBeforeSeparatorError struct {
Message string
}
func (m *ParseIntBeforeSeparatorError) Error() string {
return "parseIntBeforeSeparator: " + m.Message
}
type ParseExpirationError struct {
Message string
}
func (m *ParseExpirationError) Error() string {
return "parseIntBeforeSeparator: " + m.Message
}

View file

@ -1,18 +1,18 @@
package main package utils
import ( import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt"
"log" "log"
mathrand "math/rand" mathrand "math/rand"
"strconv" "strconv"
"strings" "strings"
) )
func GenerateUrl() string { // GenerateUrl generate random string for plak url
func GenerateUrl(length uint8) string {
listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, currentConfig.urlLength) b := make([]rune, length)
for i := range b { for i := range b {
b[i] = listChars[mathrand.Intn(len(listChars))] b[i] = listChars[mathrand.Intn(len(listChars))]
} }
@ -20,6 +20,7 @@ func GenerateUrl() string {
return string(b) return string(b)
} }
// GenerateSecret generate random secret (32 bytes hexadecimal)
func GenerateSecret() string { func GenerateSecret() string {
key := make([]byte, 32) key := make([]byte, 32)
_, err := rand.Read(key) _, err := rand.Read(key)
@ -30,62 +31,73 @@ func GenerateSecret() string {
return hex.EncodeToString(key) return hex.EncodeToString(key)
} }
func UrlExist(url string) bool { // CheckCharRedundant verify is a character is redundant in a string
return db.Exists(ctx, url).Val() == 1 func CheckCharRedundant(source string, char string) bool { // Verify if a char is redundant
if strings.Count(source, char) > 1 {
return true
}
return false
} }
func VerifySecret(url string, secret string) bool { func parseIntBeforeSeparator(source *string, sep string) (int, error) { // return 0 & error if error, only accept positive number
return secret == db.HGet(ctx, url, "secret").Val() if CheckCharRedundant(*source, sep) {
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"}
} }
func parseIntBeforeSeparator(source *string, sep string) (int, error) { // return -1 if error, only accept positive number
var value int var value int
var err error var err error
if strings.Contains(*source, sep) { if strings.Contains(*source, sep) {
value, err = strconv.Atoi(strings.Split(*source, sep)[0]) value, err = strconv.Atoi(strings.Split(*source, sep)[0])
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return -1, fmt.Errorf("parseIntBeforeSeparator : \"%s\" : cannot parse value as int", *source) return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"}
} }
if value < 0 { // Only positive value is correct if value < 0 { // Only positive value is correct
return -1, fmt.Errorf("parseIntBeforeSeparator : \"%s\" : format only take positive value", *source) return 0, &ParseIntBeforeSeparatorError{Message: *source + ": format only take positive value"}
} }
if value > 99 {
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": Format only take two number"}
}
*source = strings.Join(strings.Split(*source, sep)[1:], "") *source = strings.Join(strings.Split(*source, sep)[1:], "")
} }
return value, nil return value, nil
} }
func ParseExpiration(source string) (int, error) { // return -1 if error // ParseExpiration Parse "1d1h1m1s" duration format. Return 0 & error if error
func ParseExpiration(source string) (int, error) {
var expiration int var expiration int
var tempOutput int var tempOutput int
var err error var err error
errMessage := "ParseExpiration : \"%s\" : invalid syntax"
if source == "0" { if source == "0" {
return 0, nil return 0, nil
} }
source = strings.ToLower(source)
tempOutput, err = parseIntBeforeSeparator(&source, "d") tempOutput, err = parseIntBeforeSeparator(&source, "d")
expiration = tempOutput * 86400 expiration = tempOutput * 86400
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return -1, fmt.Errorf(errMessage, source) return 0, &ParseExpirationError{Message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "h") tempOutput, err = parseIntBeforeSeparator(&source, "h")
expiration += tempOutput * 3600 expiration += tempOutput * 3600
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return -1, fmt.Errorf(errMessage, source) return 0, &ParseExpirationError{Message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "m") tempOutput, err = parseIntBeforeSeparator(&source, "m")
expiration += tempOutput * 60 expiration += tempOutput * 60
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return -1, fmt.Errorf(errMessage, source) return 0, &ParseExpirationError{Message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "s") tempOutput, err = parseIntBeforeSeparator(&source, "s")
expiration += tempOutput * 1 expiration += tempOutput * 1
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return -1, fmt.Errorf(errMessage, source) return 0, &ParseExpirationError{Message: "Invalid syntax"}
} }
return expiration, nil return expiration, nil

View file

@ -0,0 +1,10 @@
package plak
type DeletePlakError struct {
Name string
Err error
}
func (m *DeletePlakError) Error() string {
return "Cannot delete: " + m.Name + " : " + m.Err.Error()
}

134
internal/web/plak/plak.go Normal file
View file

@ -0,0 +1,134 @@
package plak
import (
"context"
"io"
"log"
"net/http"
"time"
"git.gnous.eu/gnouseu/plakken/internal/database"
"git.gnous.eu/gnouseu/plakken/internal/utils"
"github.com/redis/go-redis/v9"
"html/template"
)
var ctx = context.Background()
type WebConfig struct {
DB *redis.Client
UrlLength uint8
}
// Plak "Object" for plak
type Plak struct {
Key string
Content string
Expiration time.Duration
DB *redis.Client
}
// Create manage POST request for create Plak
func (config WebConfig) Create(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content")
if content == "" {
w.WriteHeader(http.StatusBadRequest)
}
dbConf := database.DBConfig{
DB: config.DB,
}
secret := utils.GenerateSecret()
key := utils.GenerateUrl(config.UrlLength)
rawExpiration := r.FormValue("exp")
expiration, err := utils.ParseExpiration(rawExpiration)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
} else if expiration == 0 {
dbConf.InsertPaste(key, content, secret, -1)
} else {
dbConf.InsertPaste(key, content, secret, time.Duration(expiration*int(time.Second)))
}
http.Redirect(w, r, key, http.StatusSeeOther)
}
// View for plak
func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{
DB: config.DB,
}
var plak Plak
key := r.PathValue("key")
if dbConf.UrlExist(key) {
plak = Plak{
Key: key,
DB: config.DB,
}
plak = plak.GetContent()
if r.PathValue("settings") == "raw" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err := io.WriteString(w, plak.Content)
if err != nil {
log.Println(err)
}
} else {
t, err := template.ParseFiles("templates/paste.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, plak)
if err != nil {
log.Println(err)
}
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
// Delete manage plak deletion endpoint
func (config WebConfig) Delete(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{
DB: config.DB,
}
key := r.PathValue("key")
if dbConf.UrlExist(key) {
secret := r.URL.Query().Get("secret")
if dbConf.VerifySecret(key, secret) {
plak := Plak{
Key: key,
DB: config.DB,
}
err := plak.deletePlak()
if err != nil {
log.Println(err)
}
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
w.WriteHeader(http.StatusNotFound)
}
// deletePlak Delete plak from database
func (plak Plak) deletePlak() error {
err := plak.DB.Del(ctx, plak.Key).Err()
if err != nil {
log.Println(err)
return &DeletePlakError{Name: plak.Key, Err: err}
}
return nil
}
// GetContent get plak content
func (plak Plak) GetContent() Plak {
plak.Content = plak.DB.HGet(ctx, plak.Key, "content").Val()
return plak
}

View file

@ -0,0 +1,15 @@
package static
import (
"net/http"
)
// ServeStatic Serve static file from static
func ServeStatic(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/"+r.PathValue("file")) // TODO: vérifier si c'est safe
}
// Home Serve index.html
func Home(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}

112
main.go
View file

@ -1,111 +1,21 @@
package main package main
import ( import (
"fmt" "git.gnous.eu/gnouseu/plakken/internal/config"
"github.com/redis/go-redis/v9" "git.gnous.eu/gnouseu/plakken/internal/database"
"html/template" "git.gnous.eu/gnouseu/plakken/internal/httpServer"
"io"
"log"
"net/http"
"strings"
"time"
) )
var currentConfig Config
var db *redis.Client
type pasteView struct {
Content string
Key string
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
clearPath := strings.ReplaceAll(r.URL.Path, "/raw", "")
staticResource := "/static/"
switch r.Method {
case "GET":
if path == "/" {
http.ServeFile(w, r, "./static/index.html")
} else if strings.HasPrefix(path, staticResource) {
fs := http.FileServer(http.Dir("./static"))
http.Handle(staticResource, http.StripPrefix(staticResource, fs))
} else {
if UrlExist(clearPath) {
if strings.HasSuffix(path, "/raw") {
pasteContent := getContent(clearPath)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err := io.WriteString(w, pasteContent)
if err != nil {
log.Println(err)
}
} else {
pasteContent := getContent(path)
s := pasteView{Content: pasteContent, Key: strings.TrimPrefix(path, "/")}
t, err := template.ParseFiles("templates/paste.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, s)
if err != nil {
log.Println(err)
}
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
case "POST":
if path == "/" {
secret := GenerateSecret()
url := "/" + GenerateUrl()
content := r.FormValue("content")
rawExpiration := r.FormValue("exp")
expiration, err := ParseExpiration(rawExpiration)
if err != nil {
log.Println(err)
} else if expiration == 0 {
insertPaste(url, content, secret, -1)
} else if expiration == -1 {
w.WriteHeader(http.StatusBadRequest)
} else {
insertPaste(url, content, secret, time.Duration(expiration*int(time.Second)))
}
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
case "DELETE":
if UrlExist(path) {
secret := r.URL.Query().Get("secret")
if VerifySecret(path, secret) {
DeleteContent(path)
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusForbidden)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
}
func main() { func main() {
db = ConnectDB() initConfig := config.GetConfig()
currentConfig = GetConfig() dbConfig := database.InitDB(initConfig.RedisAddress, initConfig.RedisUser, initConfig.RedisPassword, initConfig.RedisDB)
listen := currentConfig.host + ":" + currentConfig.port db := database.ConnectDB(dbConfig)
http.HandleFunc("/", handleRequest)
if currentConfig.host == "" { serverConfig := httpServer.ServerConfig{
fmt.Println("Listening on port " + listen) HTTPServer: httpServer.Config(initConfig.ListenAddress),
} else { UrlLength: initConfig.UrlLength,
fmt.Println("Listening on " + listen) DB: db,
} }
err := http.ListenAndServe(listen, nil) serverConfig.Server()
if err != nil {
log.Fatal(err)
}
} }

View file

@ -7,9 +7,8 @@
name="description"> name="description">
<meta content="Plakken" name="author"> <meta content="Plakken" name="author">
<meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>New plak • Plakken</title> <title>New plak • Plakken</title><script async src="/static/app.js"></script>
<link href="/static/style.css" rel="stylesheet"> <link href="/static/style.css" rel="stylesheet">
<script async src="/static/app.js"></script>
</head> </head>
<body> <body>
<form method="post"> <form method="post">
@ -19,19 +18,22 @@
</div> </div>
<div> <div>
<label for="content"></label> <label for="content"></label>
<textarea autofocus id="content" name="content" placeholder="Your paste here"></textarea> <textarea autofocus id="content" name="content" placeholder="Type your paste here"></textarea>
<nav> <nav>
<ul> <ul>
<li> <li>
<label for="password">Password?</label> <label for="password">
<input id="password" type="text"> <input id="password" placeholder="Password" type="text">
</label>
</li> </li>
<li><label for="exp">Expiration?</label>
<input id="exp" name="exp" type="text" placeholder="vide, 0 ou 1d1h1m1s"></li>
<li> <li>
<label for="type">Type</label> <label for="exp">
<input id="exp" name="exp" placeholder="Expiration (1d1h1m1s)" type="text">
</label>
</li>
<li>
<label for="type">
<select id="type" name="type"> <select id="type" name="type">
<option value="auto">Auto Detect</option>
<option value="c">C</option> <option value="c">C</option>
<option value="cpp">C++</option> <option value="cpp">C++</option>
<option value="csharp">C#</option> <option value="csharp">C#</option>
@ -50,12 +52,12 @@
<option value="xml">XML</option> <option value="xml">XML</option>
<option value="yml">YAML</option> <option value="yml">YAML</option>
</select> </select>
</label>
</li> </li>
</ul> </ul>
<button title="Save plak" type="submit"> <button title="Save plak" type="submit">
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<polyline points="9 11 12 14 22 4"></polyline> <path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425z"></path>
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
</svg> </svg>
</button> </button>
</nav> </nav>

View file

@ -1,8 +1,9 @@
:root { :root {
--accent: #be0560; --accent: #be0560;
--background: #141414; --background: #121212;
--border: #333; --border: #333;
--text: #e9e9e9; --text: #e6e6e6;
--placeholder: #666;
} }
body { body {
@ -17,6 +18,32 @@ form {
flex-flow: row wrap; flex-flow: row wrap;
} }
#lines {
color: var(--placeholder);
font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 29px);
overflow-y: hidden;
padding: 8px 0;
text-align: center;
user-select: none;
width: 26px;
}
input, select {
background-color: var(--background);
border: 2px solid var(--border);
border-radius: 2px;
color: var(--text);
font-size: 13px;
outline: none;
padding: 6px 8px;
transition: border .15s ease;
}
input:hover, select:hover {
border-color: var(--text);
}
button, textarea { button, textarea {
background-color: inherit; background-color: inherit;
border: none; border: none;
@ -24,36 +51,20 @@ button, textarea {
resize: none; resize: none;
} }
#lines {
color: #999;
font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 3rem);
overflow-y: hidden;
padding: 10px 0;
text-align: center;
user-select: none;
width: 26px;
}
#content { #content {
color: var(--text); color: var(--text);
font: 400 14px/1.6 "JetBrains Mono", monospace; font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 3rem); height: calc(100vh - 29px);
padding: 10px 10px 10px 6px; padding: 8px;
width: calc(100vw - 42px); width: calc(100vw - 45px);
}
pre {
margin: 15px;
} }
nav { nav {
align-items: end; top: 1rem;
bottom: 1rem;
display: flex; display: flex;
flex-flow: row wrap; flex-flow: row wrap;
position: absolute; position: absolute;
right: 1rem; right: 12px;
} }
ul { ul {
@ -65,33 +76,12 @@ ul {
padding: 0 1.9rem; padding: 0 1.9rem;
} }
label {
display: block;
}
input, select {
background-color: var(--background);
border: 2px solid var(--border);
border-radius: 2px;
color: var(--text);
font-size: 15px;
outline: none;
padding: 6px 8px;
transition: border .15s ease;
}
input:hover, select:hover {
border-color: var(--text);
}
svg { svg {
fill: none; cursor: pointer;
height: 26px; height: 24px;
stroke: var(--text); fill: var(--text);
stroke-width: 2;
stroke-linecap: round;
transition: .15s ease; transition: .15s ease;
width: 26px; width: 24px;
} }
svg:hover { svg:hover {
@ -102,10 +92,6 @@ input:focus-visible, select:focus-visible {
border: 2px solid var(--text); border: 2px solid var(--text);
} }
button:focus-visible {
outline: none;
}
::selection { ::selection {
background-color: var(--accent); background-color: var(--accent);
color: #fff; color: #fff;

81
test/utils/utils_test.go Normal file
View file

@ -0,0 +1,81 @@
package utils_test
import (
"errors"
"testing"
"git.gnous.eu/gnouseu/plakken/internal/utils"
)
func TestCheckCharNotRedundantTrue(t *testing.T) { // Test CheckCharRedundant with redundant char
want := true
got := utils.CheckCharRedundant("2d1h3md4h7s", "h")
if got != want {
t.Fatal("Error in parseExpirationFull, want : ", want, "got : ", got)
}
}
func TestCheckCharNotRedundantFalse(t *testing.T) { // Test CheckCharRedundant with not redundant char
want := false
got := utils.CheckCharRedundant("2d1h3m47s", "h")
if got != want {
t.Fatal("Error in parseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("2d1h3m47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("1h47s")
correctValue := 3647
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationWithCaps(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("2D1h3M47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("0")
correctValue := 0
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want: ", correctValue, "got: ", result)
}
}
func TestParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("-42h1m4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("8h42h1m1d4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("8h42h1m1h4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}

View file

@ -1,43 +0,0 @@
package main
import "testing"
func TestParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := ParseExpiration("2d1h3m47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := ParseExpiration("1h47s")
correctValue := 3647
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("0")
correctValue := 0
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("-42h1m4s")
correctValue := -1
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("8h42h1m1d4s")
correctValue := -1
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}