summaryrefslogtreecommitdiffstats
path: root/cmd/ship/init.go
diff options
context:
space:
mode:
authorClawd <ai@clawd.bot>2026-02-17 07:54:26 -0800
committerClawd <ai@clawd.bot>2026-02-17 07:54:26 -0800
commit6b2c04728cd914f27ae62c1df0bf5df24ac9a628 (patch)
tree8a103ac79194a05fae438b0da105589aaa6b78d9 /cmd/ship/init.go
parent5e5de4ea1aa98f75d470e4a61644d4b9f100c4b0 (diff)
Remove v1 code, simplify state to just base_domain
- Delete all v1 commands (deploy, init, list, status, remove, etc.) - Delete v1 env/ and host/ subcommand directories - Simplify state.go: remove NextPort, Apps, AllocatePort, etc. - Local state now only tracks default_host + base_domain per host - Ports and deploys are tracked on the server (/etc/ship/ports/) - host init now creates minimal state.json
Diffstat (limited to 'cmd/ship/init.go')
-rw-r--r--cmd/ship/init.go268
1 files changed, 0 insertions, 268 deletions
diff --git a/cmd/ship/init.go b/cmd/ship/init.go
deleted file mode 100644
index b495702..0000000
--- a/cmd/ship/init.go
+++ /dev/null
@@ -1,268 +0,0 @@
1package main
2
3import (
4 "fmt"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strconv"
9
10 "github.com/bdw/ship/internal/ssh"
11 "github.com/bdw/ship/internal/state"
12 "github.com/bdw/ship/internal/templates"
13 "github.com/spf13/cobra"
14)
15
16var initCmd = &cobra.Command{
17 Use: "init <name>",
18 Short: "Initialize a git-deployed project",
19 Long: `Create a bare git repo on the VPS and generate local .ship/ config files.
20
21Pushing to the remote triggers an automatic docker build and deploy (for apps)
22or a static file checkout (for static sites). If no Dockerfile is present in an
23app repo, pushes are accepted without triggering a deploy.
24
25Examples:
26 # Initialize an app (Docker-based)
27 ship init myapp
28
29 # Initialize with a custom domain
30 ship init myapp --domain custom.example.com
31
32 # Initialize a static site
33 ship init mysite --static
34
35 # Initialize a public repo (cloneable via go get / git clone over HTTPS)
36 ship init mylib --public`,
37 Args: cobra.ExactArgs(1),
38 RunE: runInit,
39}
40
41func init() {
42 initCmd.Flags().Bool("static", false, "Initialize as static site")
43 initCmd.Flags().Bool("public", false, "Make repo publicly cloneable over HTTPS (for go get)")
44 initCmd.Flags().String("domain", "", "Custom domain (default: name.basedomain)")
45}
46
47func runInit(cmd *cobra.Command, args []string) error {
48 name := args[0]
49 if err := validateName(name); err != nil {
50 return err
51 }
52 static, _ := cmd.Flags().GetBool("static")
53 public, _ := cmd.Flags().GetBool("public")
54 domain, _ := cmd.Flags().GetString("domain")
55
56 st, err := state.Load()
57 if err != nil {
58 return fmt.Errorf("error loading state: %w", err)
59 }
60
61 host := hostFlag
62 if host == "" {
63 host = st.GetDefaultHost()
64 }
65 if host == "" {
66 return fmt.Errorf("--host is required")
67 }
68
69 hostState := st.GetHost(host)
70 if !hostState.GitSetup {
71 return fmt.Errorf("git deployment not set up on %s (run 'ship host init --base-domain example.com' first)", host)
72 }
73
74 // Check if app already exists
75 if _, err := st.GetApp(host, name); err == nil {
76 return fmt.Errorf("app %s already exists", name)
77 }
78
79 appType := "git-app"
80 if static {
81 appType = "git-static"
82 }
83
84 // Resolve domain
85 if domain == "" && hostState.BaseDomain != "" {
86 domain = name + "." + hostState.BaseDomain
87 }
88 if domain == "" {
89 return fmt.Errorf("--domain required (or configure base domain)")
90 }
91
92 // Allocate port for apps only
93 port := 0
94 if !static {
95 port = st.AllocatePort(host)
96 }
97
98 fmt.Printf("Initializing %s: %s\n", appType, name)
99
100 client, err := ssh.Connect(host)
101 if err != nil {
102 return fmt.Errorf("error connecting to VPS: %w", err)
103 }
104 defer client.Close()
105
106 // Create bare repo
107 fmt.Println("-> Creating bare git repo...")
108 repo := fmt.Sprintf("/srv/git/%s.git", name)
109 if _, err := client.RunSudo(fmt.Sprintf("sudo -u git git init --bare -b main %s", repo)); err != nil {
110 return fmt.Errorf("error creating bare repo: %w", err)
111 }
112
113 if public {
114 if _, err := client.RunSudo(fmt.Sprintf("sudo -u git touch %s/git-daemon-export-ok", repo)); err != nil {
115 return fmt.Errorf("error setting repo public: %w", err)
116 }
117 }
118
119 if static {
120 // Create web root
121 fmt.Println("-> Creating web root...")
122 if _, err := client.RunSudo(fmt.Sprintf("mkdir -p /var/www/%s", name)); err != nil {
123 return fmt.Errorf("error creating web root: %w", err)
124 }
125 if _, err := client.RunSudo(fmt.Sprintf("chown git:git /var/www/%s", name)); err != nil {
126 return fmt.Errorf("error setting web root ownership: %w", err)
127 }
128
129 // Write post-receive hook
130 fmt.Println("-> Writing post-receive hook...")
131 hookContent, err := templates.PostReceiveHookStatic(map[string]string{
132 "Name": name,
133 })
134 if err != nil {
135 return fmt.Errorf("error generating hook: %w", err)
136 }
137 if err := writeHook(client, repo, hookContent); err != nil {
138 return err
139 }
140 } else {
141 // Create env file
142 fmt.Println("-> Creating environment file...")
143 envContent := fmt.Sprintf("PORT=%d\nDATA_DIR=/data\n", port)
144 envPath := fmt.Sprintf("/etc/ship/env/%s.env", name)
145 if err := client.WriteSudoFile(envPath, envContent); err != nil {
146 return fmt.Errorf("error creating env file: %w", err)
147 }
148
149 // Write post-receive hook (handles dir creation on first push)
150 fmt.Println("-> Writing post-receive hook...")
151 hookContent, err := templates.PostReceiveHook(map[string]string{
152 "Name": name,
153 })
154 if err != nil {
155 return fmt.Errorf("error generating hook: %w", err)
156 }
157 if err := writeHook(client, repo, hookContent); err != nil {
158 return err
159 }
160 }
161
162 // Save state
163 st.AddApp(host, name, &state.App{
164 Type: appType,
165 Domain: domain,
166 Port: port,
167 Repo: repo,
168 Public: public,
169 })
170 if err := st.Save(); err != nil {
171 return fmt.Errorf("error saving state: %w", err)
172 }
173
174 // Generate local .ship/ files
175 fmt.Println("-> Generating local .ship/ config...")
176 if err := os.MkdirAll(".ship", 0755); err != nil {
177 return fmt.Errorf("error creating .ship directory: %w", err)
178 }
179
180 if static {
181 caddyContent, err := templates.DefaultStaticCaddy(map[string]string{
182 "Domain": domain,
183 "Name": name,
184 })
185 if err != nil {
186 return fmt.Errorf("error generating Caddyfile: %w", err)
187 }
188 if err := os.WriteFile(filepath.Join(".ship", "Caddyfile"), []byte(caddyContent), 0644); err != nil {
189 return fmt.Errorf("error writing Caddyfile: %w", err)
190 }
191 } else {
192 caddyContent, err := templates.DefaultAppCaddy(map[string]string{
193 "Domain": domain,
194 "Port": strconv.Itoa(port),
195 })
196 if err != nil {
197 return fmt.Errorf("error generating Caddyfile: %w", err)
198 }
199 if err := os.WriteFile(filepath.Join(".ship", "Caddyfile"), []byte(caddyContent), 0644); err != nil {
200 return fmt.Errorf("error writing Caddyfile: %w", err)
201 }
202
203 serviceContent, err := templates.DockerService(map[string]string{
204 "Name": name,
205 "Port": strconv.Itoa(port),
206 })
207 if err != nil {
208 return fmt.Errorf("error generating service file: %w", err)
209 }
210 if err := os.WriteFile(filepath.Join(".ship", "service"), []byte(serviceContent), 0644); err != nil {
211 return fmt.Errorf("error writing service file: %w", err)
212 }
213 }
214
215 // Initialize local git repo if needed
216 if _, err := os.Stat(".git"); os.IsNotExist(err) {
217 fmt.Println("-> Initializing git repo...")
218 gitInit := exec.Command("git", "init")
219 gitInit.Stdout = os.Stdout
220 gitInit.Stderr = os.Stderr
221 if err := gitInit.Run(); err != nil {
222 return fmt.Errorf("error initializing git repo: %w", err)
223 }
224 }
225
226 // Add origin remote (replace if it already exists)
227 sshHost := host
228 remoteURL := fmt.Sprintf("git@%s:%s", sshHost, repo)
229 exec.Command("git", "remote", "remove", "origin").Run() // ignore error if not exists
230 addRemote := exec.Command("git", "remote", "add", "origin", remoteURL)
231 if err := addRemote.Run(); err != nil {
232 return fmt.Errorf("error adding git remote: %w", err)
233 }
234
235 fmt.Printf("\nProject initialized: %s\n", name)
236 fmt.Println("\nGenerated:")
237 fmt.Println(" .ship/Caddyfile — Caddy config (edit to customize routing)")
238 if !static {
239 fmt.Println(" .ship/service — systemd unit (edit to customize resources, ports)")
240 }
241 fmt.Println("\nNext steps:")
242 if static {
243 fmt.Println(" git add .ship/")
244 } else {
245 fmt.Println(" git add .ship/ Dockerfile")
246 }
247 fmt.Println(" git commit -m \"initial deploy\"")
248 fmt.Println(" git push origin main")
249 if !static {
250 fmt.Println("\n (No Dockerfile? Just push — deploy is skipped until one is added.)")
251 }
252
253 return nil
254}
255
256func writeHook(client *ssh.Client, repo, content string) error {
257 hookPath := fmt.Sprintf("%s/hooks/post-receive", repo)
258 if err := client.WriteSudoFile(hookPath, content); err != nil {
259 return fmt.Errorf("error writing hook: %w", err)
260 }
261 if _, err := client.RunSudo(fmt.Sprintf("chmod +x %s", hookPath)); err != nil {
262 return fmt.Errorf("error making hook executable: %w", err)
263 }
264 if _, err := client.RunSudo(fmt.Sprintf("chown git:git %s", hookPath)); err != nil {
265 return fmt.Errorf("error setting hook ownership: %w", err)
266 }
267 return nil
268}