-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
100 lines (87 loc) · 2.45 KB
/
main.go
File metadata and controls
100 lines (87 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
srd - generates structured home source directory
Copyright (C) 2023 Lars Lehtonen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
)
type ErrShortURL struct{}
func (e ErrShortURL) Error() string {
return fmt.Sprint("a forge URL should have at least a user and a project")
}
func paths(u *url.URL) (*url.URL, string, error) {
cleanPath := path.Clean(u.Path)
pathSlice := strings.Split(cleanPath, "/")
if len(pathSlice) < 3 {
return u, "", ErrShortURL{}
}
user := pathSlice[1]
project := pathSlice[2]
cleanUser := strings.ToLower(strings.TrimPrefix(user, "~"))
cleanProject := strings.ToLower(project)
gitDir := path.Join(u.Host, cleanUser, cleanProject)
var nu url.URL
nu.Scheme = u.Scheme
nu.Host = u.Host
nu.Path = path.Join(user, project)
return &nu, gitDir, nil
}
func main() {
var root string
flag.StringVar(
&root, "root",
path.Join(os.Getenv("HOME"), "src"),
"root path to clone projects",
)
flag.Parse()
if len(flag.Args()) < 1 {
log.Fatal("requires a git URL as an argument")
}
arg := flag.Args()[0]
u, err := url.Parse(arg)
if err != nil {
log.Fatalf("error %T parsing url: %v", err, err)
}
gitUrl, relPath, err := paths(u)
if err != nil {
log.Fatal(err)
}
dir := path.Join(root, relPath)
err = os.MkdirAll(filepath.Dir(dir), 0755)
if err != nil {
log.Fatalf("error %T creating directory: %v", err, err)
}
err = os.Chdir(filepath.Dir(dir))
if err != nil {
log.Fatalf("error changing to directory %q: %v", dir, err)
}
clone := exec.Command("git", "clone", gitUrl.String(), strings.ToLower(path.Base(dir)))
// the only thing we want to go to stdout is the full path of
// the git repo
clone.Stdout = os.Stderr
clone.Stderr = os.Stderr
err = clone.Run()
if err != nil {
log.Fatalf("error %T cloning repo %q: %v", err, arg, err)
}
fmt.Println(dir)
}