Поиск по этому блогу

пятница, 20 января 2023 г.

Small utils on golang

 // filelist project main.go


// filelist project main.go
package main

import (
	"crypto/sha256"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	//	"path"
	//"path/filepath"
)

const sitemapHeader = `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`

var dirSlice []string
var Depth int

//var pathWork []string
func test(slice1 []string) {
	fmt.Println("test function")
	fmt.Println(slice1)
	fmt.Println(&slice1[0])
}

func remove(s []int, i int) []int {
	s[i] = s[len(s)-1]
	return s[:len(s)-1]
	// usage To remove the first element, call remove(s, 0)
}

func getSha256(fname string) string {
	f, err := os.Open(fname)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		log.Fatal(err)
	}
	s := fmt.Sprintf("%x", h.Sum(nil))
	s = strings.ToUpper(s)
	return s
	//fmt.Printf("%x", h.Sum(nil))
}

func WalkDir(dirName string) {
	counter := 0
	dir := dirName
	fmt.Println("open file")
	f, err := os.Open(dirName) // E:/www/glava01 pathWork[0]
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	files, err := f.Readdir(0)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, v := range files {
		fmt.Println(v.Name(), v.IsDir())

		if v.IsDir() {
			counter++
			dir := dirName + "/" + v.Name()
			///WalkDir(dirName string)
			fmt.Println(counter, " is dir recurse", dir)
			depthcntr := strings.Count(dir, "/")
			if depthcntr >= Depth {
				log.Println("Depth more than ", Depth)
				continue
			}
			WalkDir(dir) // recurse

		} else {
			fmt.Println(v.Name(), v.Size(), v.ModTime(), v.Mode(), v.IsDir())

			fullName := dir + "/" + v.Name()
			fSha256 := getSha256(fullName)
			s := fmt.Sprintf("<url>\n<loc></loc>\n<absloc>%s</absloc>\n
               <sha>%s</sha><lastmod>%s</lastmod>\n<size>%d</size><fmode>%s</fmode>\n</url>",
               fullName, fSha256, v.ModTime(), v.Size(), v.Mode())
			s = s + "\n"
			createSiteMap("sitemap.xml", s)

		}
	}
}

func createSiteMap(fname string, content string) {

	f, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND, 0644)

	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	_, err2 := f.WriteString(content)
	if err2 != nil {
		log.Fatal(err2)
	}

	//f.Sync()
}

func main() {
	// default
	Depth = 5
	fmt.Println(Depth)
	pathWork := []string{"./"}
	//pathWork := make([]string, 3)
	pathWork[0] = "./"
	fmt.Println(pathWork)
	argsWithProg := os.Args
	argsStdIn := os.Args[1:]

	fmt.Println(len(argsStdIn))
	test(pathWork)
	if len(argsStdIn) > 0 {

		fmt.Println(os.Args[1])
		fmt.Println(argsWithProg)
		fmt.Println(argsStdIn)
	}
	createSiteMap("sitemap.xml", sitemapHeader)
	WalkDir("E:/www/glava01")

}