8356
Wx
www-xonecas-io / files
www-xonecas-io / cmd / site / shell.go
2.3 KB
1package main 2 3import ( 4 "errors" 5 "fmt" 6 "log" 7 "os" 8 "os/exec" 9 "path/filepath" 10 "slices" 11 "strings" 12 "syscall" 13 14 "xonecas.io/site/internal/store" 15) 16 17// shell runs one SSH command that the login shell from make login-shell hands the site (site -c <command>). 18// git push to <name>.git creates the repo on its first push, git clone and fetch read it, and remote 19// manages the repos, as site remote does. A path with a / or one that exists in the user's home isn't 20// the site's, so git gets it as sshd would have. 21func shell(cmd string) error { 22 args := strings.Fields(cmd) 23 if len(args) == 2 && (args[0] == "git-receive-pack" || args[0] == "git-upload-pack") { 24 path := strings.Trim(args[1], "'") 25 if rel := strings.TrimPrefix(path, "~/"); strings.Contains(rel, "/") || exists(rel) { 26 return execGit(args[0], path) 27 } 28 if err := chdirSite(); err != nil { 29 return err 30 } 31 const sources, root, meta = "sources.txt", "repos", "data/meta.json" 32 name := strings.TrimSuffix(strings.TrimPrefix(path, "~/"), ".git") 33 url := hostedURL(name) 34 urls, err := store.Sources(sources) 35 if err != nil { 36 return err 37 } 38 if !slices.Contains(urls, url) { 39 if args[0] == "git-upload-pack" { 40 return fmt.Errorf("there is no repo %s.git", name) 41 } 42 if err := newRepo(name, urls, sources, root, meta); err != nil { 43 return err 44 } 45 log.Printf("created %s; each push updates the site", url) 46 } 47 return execGit(args[0], store.Dir(root, url)) 48 } 49 if len(args) > 0 && args[0] == "remote" { 50 if err := chdirSite(); err != nil { 51 return err 52 } 53 return remote(args[1:], "sources.txt", "repos", "data/meta.json") 54 } 55 return errors.New("usage: git push <user>@<host>:<name>.git, git clone it, or ssh <user>@<host> remote list | new <name> | add <path or url> | rm <path or url>") 56} 57 58func exists(path string) bool { _, err := os.Stat(path); return err == nil } 59 60// chdirSite moves to the site folder, bin/site's parent. 61func chdirSite() error { 62 exe, err := os.Executable() 63 if err != nil { 64 return err 65 } 66 return os.Chdir(filepath.Dir(filepath.Dir(exe))) 67} 68 69// execGit replaces site with git-receive-pack or git-upload-pack on dir. 70func execGit(verb, dir string) error { 71 git, err := exec.LookPath("git") 72 if err != nil { 73 return err 74 } 75 return syscall.Exec(git, []string{"git", strings.TrimPrefix(verb, "git-"), dir}, os.Environ()) 76}