Skip to content

Commit

Permalink
déplace le code de conversion dans des packages adequats
Browse files Browse the repository at this point in the history
  • Loading branch information
Raphaël Squelbut committed Nov 23, 2023
1 parent e8f4a3b commit 6a41a80
Show file tree
Hide file tree
Showing 11 changed files with 305 additions and 143 deletions.
13 changes: 13 additions & 0 deletions tools/altares/concat_2.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
echo "stock"
go run main.go resources/SF_DATA_20230706.txt resources/S_202011095834-3_202311010315.csv resources/S_202011095834-3_202310020319.csv output_2.csv
#echo "increment 1"
#go run convert_increment.go resources/S_202011095834-3_202311010315.csv >> output.csv
#echo "increment 2"
#go run convert_increment.go resources/S_202011095834-3_202310020319.csv >> output.csv
echo "résultat"
head output_2.csv
echo "."
echo "."
echo "."
tail output_2.csv
#tar -czf altares_2.tar.gz output_2.csv
97 changes: 0 additions & 97 deletions tools/altares/convert_increment.go

This file was deleted.

60 changes: 60 additions & 0 deletions tools/altares/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"io"
"log/slog"
"os"

"opensignauxfaibles/tools/altares/pkg/altares"
"opensignauxfaibles/tools/altares/pkg/utils"
)

var loglevel *slog.LevelVar

func main() {
inputs, o := readArgs()
output, err := os.Create(o)
utils.ManageError(err, "erreur à la création du fichier de sortie")
slog.Debug("fichier de sortie créé", slog.String("filename", output.Name()))
defer utils.CloseIt(output, "fermeture du fichier de sortie : "+os.Args[1])
convertAndConcat(inputs, output)
}

func convertAndConcat(altaresFiles []string, outputCsv io.Writer) {
slog.Debug("démarrage de la conversion et de la concaténation", slog.Any("inputs", altaresFiles))
altares.ConvertStock(altaresFiles[0], outputCsv)
if len(altaresFiles) == 1 {
slog.Info("terminé, pas de fichier incrément")
}
for _, filename := range altaresFiles[1:] {
altares.ConvertIncrement(filename, outputCsv)
}
}

func readArgs() (inputs []string, output string) {
slog.Debug("lecture des arguments", slog.String("status", "start"), slog.Any("all", os.Args))
if len(os.Args) <= 2 {
slog.Warn("rien à faire, car pas de fichiers altares ou pas de fichier source")
os.Exit(0)
}
output = os.Args[len(os.Args)-1]
inputs = os.Args[1 : len(os.Args)-1]
if len(inputs) == 0 {
slog.Warn("rien à faire, car pas de fichiers altares")
os.Exit(0)
}
slog.Debug("lecture des arguments", slog.String("status", "end"), slog.String("output", output), slog.Any("inputs", inputs))
return inputs, output
}

func init() {
loglevel = new(slog.LevelVar)
loglevel.Set(slog.LevelDebug)
handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: loglevel,
})

logger := slog.New(
handler)
slog.SetDefault(logger)
}
48 changes: 48 additions & 0 deletions tools/altares/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package main

import (
"os"
"reflect"
"runtime"
"testing"

"github.com/stretchr/testify/require"
)

func Test_convertAndConcat(t *testing.T) {
output, err := os.CreateTemp(t.TempDir(), "output_*.csv")
require.NoError(t, err)
convertAndConcat(
[]string{"resources/SF_DATA_20230706.txt", "resources/S_202011095834-3_202310020319.csv", "resources/S_202011095834-3_202311010315.csv"},
output,
)
}

func Test_readArgs(t *testing.T) {
_, here, _, _ := runtime.Caller(0)
tests := []struct {
name string
args []string
wantInputs []string
wantOutput string
}{
{
name: "tout va bien",
args: []string{here, "stock", "increment1", "increment2", "output"},
wantInputs: []string{"stock", "increment1", "increment2"},
wantOutput: "output",
},
}
for _, tt := range tests {
os.Args = tt.args
t.Run(tt.name, func(t *testing.T) {
gotInputs, gotOutput := readArgs()
if !reflect.DeepEqual(gotInputs, tt.wantInputs) {
t.Errorf("readArgs() gotInputs = %v, want %v", gotInputs, tt.wantInputs)
}
if gotOutput != tt.wantOutput {
t.Errorf("readArgs() gotOutput = %v, want %v", gotOutput, tt.wantOutput)
}
})
}
}
110 changes: 110 additions & 0 deletions tools/altares/pkg/altares/convertIncrement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package altares

import (
"encoding/csv"
"fmt"
"io"
"log/slog"
"os"
"regexp"

"github.com/pkg/errors"
"golang.org/x/text/encoding/charmap"

"opensignauxfaibles/tools/altares/pkg/utils"
)

var FIELDS = []int{
1,
18,
21,
21,
22,
23,
24,
26,
27,
30,
}

var END_OF_FILE_REGEXP = regexp.MustCompile("Fin du fichier : total (?P<nblines>\\d+) ligne\\(s\\)")

func ConvertIncrement(incrementFilename string, output io.Writer) {
slog.Info("démarrage de la conversion du fichier incrémental", slog.String("filename", incrementFilename))
inputFile, err := os.Open(incrementFilename)
if err != nil {
panic(err)
}
defer func() {
closeErr := inputFile.Close()
if closeErr != nil {
panic(errors.Wrap(closeErr, "erreur à la fermeture du fichier"))
}
}()

fromISO8859_15toUTF8 := charmap.ISO8859_15.NewDecoder()
convertReader := fromISO8859_15toUTF8.Reader(inputFile)
reader := csv.NewReader(convertReader)
reader.Comma = ';'

w := csv.NewWriter(output)
defer w.Flush()

// discard headers
headers, err := reader.Read()
utils.ManageError(err, "erreur lors de la lecture des headers")
slog.Debug("description des headers", slog.Any("headers", headers))

for {
record, err := reader.Read()
if err, ok := err.(*csv.ParseError); ok && err.Err != csv.ErrFieldCount {
slog.Warn("prbleme", slog.Any("error", err))
continue
}
//if err == io.EOF {
// return
//}
if isIncrementalEndOfFile(record) {
return
}
out := selectFields(record)

if out != nil {
err = w.Write(out)
if err != nil {
panic(err)
}
}
}
}

func selectFields(record []string) []string {
var data []string
for _, field := range FIELDS {
//if field > len(record)-1 {
// if
// slog.Error(
// "erreur de longueur de ligne",
// slog.Any("record", record),
// )
// utils.ManageError(fmt.Errorf("erreur de longueur de ligne, attendu : %d, obtenu %d", field, len(record)-1), "mais que se passe t il ?"))
// return nil
//}
data = append(data, record[field])
}
return data
}

func isIncrementalEndOfFile(record []string) bool {
if len(record) > 2 {
return false
}
//names := END_OF_FILE_REGEXP.SubexpNames()
//slog.Info("les captures", slog.Any("names", names))
line := END_OF_FILE_REGEXP.FindStringSubmatch(record[0])
if len(line) != 2 {
utils.ManageError(fmt.Errorf("erreur de fin de fichier : %+v", record), "problème avec la fin de fichier")
}
slog.Info("fin du fichier incrémental", slog.Any("expectedLines", line[1]))
return true
}
32 changes: 32 additions & 0 deletions tools/altares/pkg/altares/convertIncrement_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package altares

import (
"encoding/csv"
"strings"
"testing"

"github.com/stretchr/testify/require"
)

func Test_isIncrementalEndOfFile(t *testing.T) {
recordEOF, err := csv.NewReader(strings.NewReader("Fin du fichier : total 122909 ligne(s);")).Read()
t.Log("match -> ", END_OF_FILE_REGEXP.MatchString(recordEOF[0]))
require.NoError(t, err)
type args struct {
record []string
}
tests := []struct {
name string
args args
want bool
}{
{"ok", args{recordEOF}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isIncrementalEndOfFile(tt.args.record); got != tt.want {
t.Errorf("isIncrementalEndOfFile() = %v, want %v", got, tt.want)
}
})
}
}
Loading

0 comments on commit 6a41a80

Please sign in to comment.