<commit_before>package readline

/*
// IMPORTANT: choose one
#cgo LDFLAGS: -ledit
//#cgo LDFLAGS: -lreadline // NOTE: libreadline is GPL

// free()
#include <stdlib.h>
// readline()
#include <readline/readline.h>
// add_history()
#include <readline/history.h>
*/
import "C"

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unsafe"
)

var HISTORY_FILE = ".mal-history"

var rl_history_loaded = false

func Readline(prompt string) (string, error) {
	history_path := filepath.Join(os.Getenv("HOME"), "/", HISTORY_FILE)

	if !rl_history_loaded {
		rl_history_loaded = true
		content, e := ioutil.ReadFile(history_path)
		if e != nil {
			return "", e
		}

		for _, add_line := range strings.Split(string(content), "\n") {
			if add_line == "" {
				continue
			}
			c_add_line := C.CString(add_line)
			C.add_history(c_add_line)
			C.free(unsafe.Pointer(c_add_line))
		}
	}

	c_prompt := C.CString(prompt)
	defer C.free(unsafe.Pointer(c_prompt))

	c_line := C.readline(c_prompt)
	defer C.free(unsafe.Pointer(c_line))
	line := C.GoString(c_line)

	if c_line == nil {
		return "", errors.New("C.readline call failed")
	}<commit_msg>readline works even when ~/.mal-history does not exist<commit_after>package readline

/*
// IMPORTANT: choose one
#cgo LDFLAGS: -ledit
//#cgo LDFLAGS: -lreadline // NOTE: libreadline is GPL

// free()
#include <stdlib.h>
// readline()
#include <stdio.h> // FILE *
#include <readline/readline.h>
// add_history()
#include <readline/history.h>
*/
import "C"

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"unsafe"
)

var HISTORY_FILE = ".mal-history"
var history_path string

func loadHistory(filename string) error {
	content, err := ioutil.ReadFile(history_path)
	if err != nil {
		return err
	}

	for _, add_line := range strings.Split(string(content), "\n") {
		if add_line == "" {
			continue
		}
		c_add_line := C.CString(add_line)
		C.add_history(c_add_line)
		C.free(unsafe.Pointer(c_add_line))
	}

	return nil
}

func init() {
	history_path = filepath.Join(os.Getenv("HOME"), HISTORY_FILE)
	loadHistory(history_path)
}

func Readline(prompt string) (string, error) {
	c_prompt := C.CString(prompt)
	defer C.free(unsafe.Pointer(c_prompt))

	c_line := C.readline(c_prompt)
	defer C.free(unsafe.Pointer(c_line))
	line := C.GoString(c_line)

	if c_line == nil {
		return "", errors.New("C.readline call failed")
	}
{'fraction_non_alphanumeric': 0.15763135946622187, 'fraction_numerical': 0.0, 'mean_word_length': 4.050526315789473, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, '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': '1976066', 'n_tokens_mistral': 1011, 'n_tokens_neox': 942, 'n_words': 193}