19 Commits

Author SHA1 Message Date
434c804b08 Added license 2025-01-11 13:11:52 -06:00
50d9126f2b Updated config file to recognize include headers 2024-09-02 23:18:56 -04:00
6b4d131f4f Updated README and TODO 2024-08-25 15:35:48 -04:00
51b4029a79 Changed project name to include repo path 2024-08-25 15:30:40 -04:00
a1f804ac38 Used absolute import path 2024-08-25 15:30:23 -04:00
eb32ec1027 Added link to releases 2024-08-15 12:55:32 -05:00
2625239dba Added note describing where to obtain releases 2024-08-15 12:53:24 -05:00
44de668546 Updated README 2024-08-15 12:46:01 -05:00
20cb665b33 Updated README 2024-08-15 12:45:43 -05:00
9a6fc3475a Added comment to function 2024-08-15 12:42:50 -05:00
d15a771e89 Removed references to Windows support
The program doesn't seem to work on Windows, and I don't have the time
right now to debug it. So, at the moment, the program isn't supported on Windows.
2024-08-15 12:37:01 -05:00
f8cb03bf88 Wrote script to create release builds 2024-08-15 12:28:12 -05:00
b65cef96c3 Replaced the relative path on Windows with an absolute path 2024-08-15 12:27:48 -05:00
b511c14cc3 Updated gitignore 2024-08-15 12:27:33 -05:00
122cd5ed04 Fixed typo 2024-08-15 11:38:00 -05:00
3b8bcb4c8a Updated README 2024-08-15 11:37:13 -05:00
e7e7a247d8 Updated README 2024-08-15 10:19:52 -05:00
eb2a0a9122 If the color config file exists, load colors from it 2024-08-15 10:19:43 -05:00
46e3e9da85 Added function to load colors from a config file 2024-08-15 10:19:21 -05:00
10 changed files with 180 additions and 34 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
ccat
*.zip

8
LICENSE.md Normal file
View File

@@ -0,0 +1,8 @@
Copyright 2025 Aadhavan Srinivasan
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.

View File

@@ -5,27 +5,47 @@ ccat is a file printing tool (like 'cat') which uses Regular Expressions to enab
---
### Features
- Support for 11 colors: Red, Blue, Green, Magenta, Cyan, Black, White, Yellow, Gray, Orange and Dark Blue.
- Adding more colors involves adding a line of code, then recompiling.
- 11 colors are defined out-of-the-box: RED, BLUE, GREEN, MAGENTA, CYAN, BLACK, WHITE, YELLOW, GRAY, ORANGE and DARKBLUE.
- Support for defining custom colors via the `ccat.colors` file.
- Regex-color mappings are stored in configuration files.
- Uses the file extension to determine which configuration file to use.
- Highly extensible - to add a config file for an specific file type, name the file `<extension>.conf`.
- Support for printing line numbers with the `-n` flag.
- Statically linked Go binary - no runtime dependencies, config files are distributed along with the binary.
- Cross-platform
- Linux and MacOS supported.
---
### Installing
Download the appropriate zip-file from the 'Releases' section. Place the executable in your PATH.
NOTE: The releases are not available on the GitHub repo (which is a mirror of https://gitea.twomorecents.org/Rockingcool/ccat). Obtain the [releases](https://gitea.twomorecents.org/Rockingcool/ccat/releases) from there instead.
---
### Building from source
If you have the `go` command installed, run `make` after cloning the repository.
---
### Supported Languages
The following languages have config files included by default:
- C
- Go
---
### Getting Started
The config files are embedded within the binary. They will automatically be installed to the correct location (`%APPDATA/ccat` on Windows, `~/.config/ccat` on UNIX) when the program is first run.
The config files are embedded within the binary. They will automatically be installed to the correct location (`~/.config/ccat` on UNIX) when the program is first run.
As written above, if provided a file with extension `.example`, the program will look for the config file named `example.conf`. If such a file doesn't exist, the file is printed out without any highlighting.
For example, if you want to create syntax highlighting for Java, create a file named `java.conf` in your config directory. In this file, include regular-expressions for each of the langauges's keywords, and provide a corresponding color. Use the provided `c.conf` and `go.conf` files as a starting point.
---
### Config Files
@@ -38,7 +58,16 @@ Note that the regex must be enclosed in double quotes, and the color must be cap
---
### Custom Colors
To define a color of your own, create a file named `ccat.colors` in the config directory (mentioned above). The syntax of this file is the following:
`COLOR: <red> <green> <blue>`
Note that the color name must be capitalized (and shouldn't contain spaces). The RGB values must each be from 0 to 255.
---
### TODO:
- Allow user to define colors at runtime by reading RGB values from a config file.
- Windows support.
- Allow users to provide a config file in the command-line, overriding the extension-based config file.
- Provide releases.

View File

@@ -2,8 +2,12 @@ package main
import (
"fmt"
"os"
"strconv"
"strings"
colorData "github.com/fatih/color"
"gopkg.in/yaml.v2"
)
// A color represents a possible color, which text can be printed out in.
@@ -14,6 +18,14 @@ type color struct {
colorObj *colorData.Color
}
// A RGB represents a Red, Blue, Green trio of values. Each value is represented as
// an int.
type RGB struct {
red int
blue int
green int
}
// The following is a list of all possible colors, stored in a map.
var possibleColors map[string]color = map[string]color{
"BLACK": {"BLACK", colorData.New(colorData.FgBlack)},
@@ -59,3 +71,89 @@ func newColorMust(colorString string) color {
return clr
}
}
// isValidColorName returns true if the given string only contains uppercase alphabetic
// characters.
func isValidColorName(colorName string) bool {
for _, ch := range colorName {
if ch > 'Z' || ch < 'A' {
return false
}
}
return true
}
// stringToRGB takes a string representing an RGB trio. It constructs and RGB type and
// returns it. Any errors encountered are returned. If an error is returned, it is safe to
// assume that the string doesn't represent an RGB trio.
func stringToRGB(rgbString string) (*RGB, error) {
values := strings.Split(rgbString, " ")
// There must be three space-separated strings.
if len(values) != 3 {
// TODO: Instead of ignoring these errors and returning a generic error (as I do in the
// callee), wrap the error returned from this function, inside the error returned by the callee.
return nil, fmt.Errorf("Error parsing RGB trio.")
}
// If any of the strings doesn't represent an integer (or is out of bounds), return an error.
// WARNING: LAZY CODE INCOMING
var toReturn RGB
var err error
toReturn.red, err = strconv.Atoi(values[0])
if err != nil {
return nil, fmt.Errorf("Error parsing RED integer: Invalid value.")
}
if toReturn.red < 0 || toReturn.red > 255 {
return nil, fmt.Errorf("Error parsing RED integer: Out-of-bounds.")
}
toReturn.blue, err = strconv.Atoi(values[1])
if err != nil {
return nil, fmt.Errorf("Error parsing BLUE integer: Invalid value.")
}
if toReturn.blue < 0 || toReturn.blue > 255 {
return nil, fmt.Errorf("Error parsing BLUE integer: Out-of-bounds.")
}
toReturn.green, err = strconv.Atoi(values[2])
if err != nil {
return nil, fmt.Errorf("Error parsing GREEN integer: Invalid value.")
}
if toReturn.green < 0 || toReturn.green > 255 {
return nil, fmt.Errorf("Error parsing GREEN integer: Out-of-bounds.")
}
return &toReturn, nil
}
// loadColorsFromFile loads the colors defined in the given config file, and adds them to
// the possibleColors map. This allows the user to define custom colors at run-time.
// The colors config file has the following syntax:
// COLOR: <RED> <GREEN> <BLUE>
//
// Note that the color must be capitalized (and not contain spaces), and the R, G and B
// values must be from 0 to 255.
func loadColorsFromFile(filepath string) error {
data, err := os.ReadFile(filepath)
if err != nil {
panic(err)
}
// Read color config file into a MapSlice
tempMapSlice := yaml.MapSlice{}
if err := yaml.Unmarshal(data, &tempMapSlice); err != nil {
return fmt.Errorf("Unable to read color config file: %s", filepath)
}
for _, item := range tempMapSlice {
if !(isValidColorName(item.Key.(string))) {
return fmt.Errorf("Invalid color name: %s", item.Key.(string))
}
var rgb *RGB
if rgb, err = stringToRGB(item.Value.(string)); err != nil {
return fmt.Errorf("Invalid RGB trio: %s", item.Value.(string))
}
// If we haven't returned an error yet, the color must be valid.
// Add it to the map. colorData.New() expects values of type colorData.Attribute,
// so we must cast our RGB values accordingly.
possibleColors[item.Key.(string)] = color{item.Key.(string), colorData.New(38, 2, colorData.Attribute(rgb.red), colorData.Attribute(rgb.blue), colorData.Attribute(rgb.green))}
}
return nil
}

View File

@@ -1,12 +1,11 @@
package main
import (
"ccat/stack"
"embed"
"errors"
"gitea.twomorecents.org/Rockingcool/ccat/stack"
"io/fs"
"os"
"os/user"
"path/filepath"
"regexp"
"runtime"
@@ -18,27 +17,18 @@ import (
//go:embed config
var storedConfigs embed.FS // Embed the folder containing config files
// runningOnWindows: At the moment this function isn't used. When Window support is added,
// it will be used to determine if the program is being run on Windows.
func runningOnWindows() bool {
return runtime.GOOS == "windows"
}
// generateDefaultConfigs is used to generate a folder of default config files
// for common languages. These default config files are embedded into the program, and will
// be outputted into a directory.
// be outputted into the given directory.
//
// If there is an error encountered, the error is returned.
func generateDefaultConfigs() error {
var configOutputPath string // Location of config files, depends on OS
if runningOnWindows() {
configOutputPath = "%APPDATA%\\ccat"
} else {
currentUser, err := user.Current()
if err != nil {
panic(err)
}
configOutputPath = filepath.Join("/home/" + currentUser.Username + "/.config/ccat/")
}
func generateDefaultConfigs(configOutputPath string) error {
err := os.MkdirAll(configOutputPath, 0755)
if err != nil {
if os.IsExist(err) {

View File

@@ -10,11 +10,13 @@
# Strings in double quotes and single quotes
'"(.*?)"': BLUE
"'(.)'": BLUE
# Text inside angle-brackets (used in 'include' statements)
'\<(.*?)\>': BLUE
# Assignments and comparisons
# TODO: Add less than, greater than, not equal to, and struct pointer member access
'(?:\s|\b)(=|==|!=|<=|>=|\->)(\s|\b)' : CYAN
# Keywords
'\b(if|else|while|do|for|return)\b': CYAN
'^(#ifdef|#ifndef|#define|#include)\b': CYAN
'(\n|^)(#ifdef|#ifndef|#define|#include)\b': CYAN
# Data Types
'\b(int|char|float|double|void|long|short|unsigned|signed|bool)\b': YELLOW

17
create_release_builds.sh Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
set -euo pipefail
POSSIBLE_GOOS=( "linux" "darwin" )
POSSIBLE_GOARCH=( "amd64" "arm64" )
for OS in "${POSSIBLE_GOOS[@]}"; do
for ARCH in "${POSSIBLE_GOARCH[@]}"; do
FOLDER_NAME="ccat-$OS-$ARCH"
mkdir "${FOLDER_NAME}"
GOOS=$OS GOARCH=$ARCH go build -o "${FOLDER_NAME}/"
zip -r "${FOLDER_NAME}" "${FOLDER_NAME}"
rm -r "${FOLDER_NAME}"
done
done

2
go.mod
View File

@@ -1,4 +1,4 @@
module ccat
module gitea.twomorecents.org/Rockingcool/ccat
go 1.22.5

22
main.go
View File

@@ -78,18 +78,13 @@ func main() {
flag.Parse()
// Check if config exists. If it doesn't, generate the config files.
var configPath string // Location of config files, depends on OS
if runningOnWindows() {
configPath = "%APPDATA%\\ccat"
} else {
currentUser, err := user.Current()
if err != nil {
panic(err)
}
configPath = filepath.Join("/home/" + currentUser.Username + "/.config/ccat/")
currentUser, err := user.Current() // Get current user, to determine config path
if err != nil {
panic(err)
}
configPath := filepath.Join("/home/" + currentUser.Username + "/.config/ccat/")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
generateDefaultConfigs()
generateDefaultConfigs(configPath)
}
// Check if user has provided a file name
@@ -120,6 +115,13 @@ func main() {
}
// Assuming the file is not empty...
// If a ccat.colors file exists in the config directory, load all the colors in it
if fileExists(filepath.Join(configPath, "ccat.colors")) {
err := loadColorsFromFile(filepath.Join(configPath, "ccat.colors"))
if err != nil {
printErrAndExit(err.Error())
}
}
// If the given file has a config, load the config into a stack of regColors.
regColorStack, err := loadConfig(configFilename)
if err != nil {

View File

@@ -1,5 +1,4 @@
1. Man page
2. README for GitHub Repo
2. Logging
3. Coloring functions
4. Flag to list all available colors for your terminal - some terminals will only support the predefined colors.