Last active
February 11, 2023 22:14
-
-
Save blacknon/702470838196e120f24edab429616bae to your computer and use it in GitHub Desktop.
goでfile path walkするための検証コード
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
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"os" | |
"path/filepath" | |
"regexp" | |
"strings" | |
) | |
func FilePathWalkDir(dir string) (files []string, err error) { | |
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { | |
if info.IsDir() { | |
path = path + "/" | |
} | |
files = append(files, path) | |
return nil | |
}) | |
return | |
} | |
func printScpWord(baseDir string, path string, toName string) (scpWord string) { | |
buf := []string{} | |
relPath, _ := filepath.Rel(baseDir, path) | |
dir := filepath.Dir(relPath) | |
if len(dir) > 0 && dir != "." { | |
dirList := strings.Split(dir, "/") | |
for _, dirName := range dirList { | |
buf = append(buf, fmt.Sprintln("D0755", 0, dirName)) | |
} | |
} | |
fInfo, _ := os.Stat(path) | |
if !fInfo.IsDir() { | |
content, err := ioutil.ReadFile(path) | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
} | |
buf = append(buf, fmt.Sprintln("C0644", len(content), toName)) | |
buf = append(buf, fmt.Sprintf(string(content))) | |
buf = append(buf, fmt.Sprintf("\x00")) | |
} | |
if len(dir) > 0 && dir != "." { | |
buf = append(buf, fmt.Sprintln("E")) | |
} | |
scpWord = strings.Join(buf, "") | |
return | |
} | |
func main() { | |
baseDir := "./123/test_dir" | |
lists, _ := FilePathWalkDir(baseDir) | |
for _, i := range lists { | |
fmt.Printf(printScpWord(baseDir, i, filepath.Base(i))) | |
} | |
fmt.Println("E") | |
base := "/tmp/123/" | |
fmt.Println(filepath.Base(base)) | |
fmt.Println(filepath.Dir(base)) | |
fmt.Println(regexp.MatchString("/$", base)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment