Created
July 10, 2019 13:58
-
-
Save SebDeclercq/0b6c8e2195f12e2fae377d654e2ef321 to your computer and use it in GitHub Desktop.
Golang : files, directories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//usr/bin/env go run $0 $@ ; exit | |
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
type DirParser struct { | |
path string | |
extensionsToParse []string | |
totalCharToPrint int | |
outputFile *os.File | |
} | |
func (d DirParser) ReadDir() (files []os.FileInfo) { | |
files, err := ioutil.ReadDir(d.path) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return | |
} | |
func (d DirParser) ParseDir() { | |
for _, file := range d.ReadDir() { | |
d.PrintFileContent(file) | |
} | |
d.End() | |
} | |
func (d DirParser) PrintFileContent(file os.FileInfo) { | |
go_on := false | |
for _, allowedExt := range d.extensionsToParse { | |
if filepath.Ext(file.Name()) == allowedExt { | |
go_on = true | |
break | |
} | |
} | |
if !(go_on) { | |
log.Printf("Skipping \"%s\"", file.Name()) | |
return | |
} | |
log.Printf("Parsing \"%s\"", file.Name()) | |
fileContent, err := ioutil.ReadFile(file.Name()) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, line := range strings.Split(string(fileContent), "\n") { | |
var fmtLine string | |
if len(line) > d.totalCharToPrint { | |
fmtLine = fmt.Sprintf("> %s(...)\n", line[:d.totalCharToPrint]) | |
} else { | |
fmtLine = fmt.Sprintf("> %s\n", line) | |
} | |
if d.outputFile != nil { | |
if _, err := d.outputFile.Write([]byte(fmtLine)); err != nil { | |
log.Fatal(err) | |
} | |
} else { | |
fmt.Print(fmtLine) | |
} | |
} | |
} | |
func (d DirParser) End() { | |
if d.outputFile != nil { | |
if err := d.outputFile.Close(); err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
func ParseArgs() *os.File { | |
if len(os.Args) > 1 { | |
f, err := os.OpenFile(os.Args[1], os.O_CREATE|os.O_WRONLY, 0644) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return f | |
} else { | |
return nil | |
} | |
} | |
func main() { | |
parser := DirParser{".", []string{".go", ".txt"}, 30, ParseArgs()} | |
parser.ParseDir() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment