/
main.go
398 lines (352 loc) · 10.6 KB
/
main.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/spf13/cobra"
)
// The following gets set with a build flat during compilation (-ldflags "-X
// main.Version=...")
var Version string
func main() {
cmd := func() *cobra.Command {
// create the root cobra command: this is the one we will attach all of the
// subcommands to
cmd := &cobra.Command{
Use: "mpr",
RunE: func(cmd *cobra.Command, args []string) error {
version, _ := cmd.PersistentFlags().GetBool("version")
if version {
fmt.Println("mpr version", Version)
return nil
}
err := cmd.Help()
os.Exit(1)
return err
},
}
cmd.PersistentFlags().BoolP("version", "V", false, "print version information and exit")
cmd.AddCommand(&cobra.Command{
Use: "build <pkg>",
Short: "Builds a package",
Long: `Builds a package. This is equivalent to running "makedeb" in the package's directory.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
pkgName := args[0]
return runBuild(pkgName)
})
},
})
cmd.AddCommand(&cobra.Command{
Use: "clean [pkgs ...]",
Short: "Cleans a package's src/ & pkg/ directories",
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
return runClean(args)
})
},
})
cmd.AddCommand(&cobra.Command{
Use: "check-stale",
Short: "Checks for stale packages",
Long: `Checks for stale packages. A package is considered stale if it's version is behind repology's record.`,
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(runCheckStale)
},
})
cmd.AddCommand(&cobra.Command{
Use: "clone <package-url>",
Short: "Clones a package",
Long: `Clones a package. This is equivalent to running "git clone" in the packages directory.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
packageURL := args[0]
return runClone(packageURL)
})
},
})
cmd.AddCommand(&cobra.Command{
Use: "each ...",
Short: "Runs a command in each package's directory",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("expected at least 1 argument, got 0")
}
runFallibleCommand(func() error {
return runEach(args)
})
return nil
},
})
cmd.AddCommand(&cobra.Command{
Use: "edit <package-name>",
Short: "Edits a package's PKGBUILD",
Long: `Edits a package's PKGBUILD. This is equivalent to running "$EDITOR PKGBUILD" in the package's directory.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
pkgName := args[0]
return runEdit(pkgName)
})
},
})
cmd.AddCommand(func() *cobra.Command {
// this subcommand will have its own flags, so we set it up inside of a
// closure to avoid polluting the global flag set
cmd := &cobra.Command{
Use: "install <package-url>",
Short: "Installs a package",
Long: `Installs a package. This is equivalent to cloning and running "makepkg ..." in the package's directory.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
packageURL := args[0]
noConfirm, _ := cmd.Flags().GetBool("no-confirm")
return runInstall(installArgs{
packageURL: packageURL,
confirm: !noConfirm,
})
})
},
}
cmd.Flags().Bool("no-confirm", false, "do not ask for confirmation")
return cmd
}())
cmd.AddCommand(&cobra.Command{
Use: "list",
Short: "Lists all packages",
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(runList)
},
})
cmd.AddCommand(&cobra.Command{
Use: "outdated",
Short: "Lists all outdated packages",
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(runOutdated)
},
})
cmd.AddCommand(&cobra.Command{
Use: "reinstall <pkg>",
Short: "Reinstalls a package",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
pkgName := args[0]
return runReinstall(pkgName)
})
},
})
cmd.AddCommand(func() *cobra.Command {
cmd := cobra.Command{
Use: "update [pkgs]",
Short: "Updates all/specified packages (runs `git pull`)",
Long: `Updates all/specified packages. This is equivalent to running "git fetch" in each package's directory.`,
Run: func(cmd *cobra.Command, args []string) {
upgrade, _ := cmd.Flags().GetBool("upgrade")
noConfirm, _ := cmd.Flags().GetBool("no-confirm")
runFallibleCommand(func() error {
return runUpdate(updateArgs{
packagesToUpdate: args,
upgrade: upgrade,
confirm: !noConfirm,
})
})
},
}
cmd.Flags().BoolP("upgrade", "u", false, "run `upgrade` following an update")
cmd.Flags().Bool("no-confirm", false, "do not ask for confirmation")
return &cmd
}())
cmd.AddCommand(&cobra.Command{
Use: "recompute-sums <pkg>",
Args: cobra.ExactArgs(1),
Short: "Updates the checksums of a package",
Run: func(cmd *cobra.Command, args []string) {
pkgName := args[0]
runFallibleCommand(func() error {
edit, _ := cmd.Flags().GetBool("edit")
return runRecomputeSums(pkgName, edit)
})
cmd.PersistentFlags().BoolP("edit", "e", false, "edit the PKGBUILD after a successful update")
},
})
cmd.AddCommand(func() *cobra.Command {
cmd := cobra.Command{
Use: "update-version <pkg> [new-version]",
Short: "Updates the version of a package in a PKGBUILD file",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("expected at 1 argument, got %d", len(args))
}
runFallibleCommand(func() error {
pkgName := args[0]
newVersion, _ := cmd.Flags().GetString("version")
edit, _ := cmd.Flags().GetBool("edit")
return runUpdateVersion(pkgName, newVersion, edit)
})
return nil
},
}
cmd.PersistentFlags().StringP("version", "v", "", "new version")
cmd.PersistentFlags().BoolP("edit", "e", false, "edit the PKGBUILD after a successful update")
return &cmd
}())
cmd.AddCommand(&cobra.Command{
Use: "uninstall <pkg>",
Short: "Uninstalls a package",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
pkgName := args[0]
return runUninstall(pkgName)
})
},
})
cmd.AddCommand(&cobra.Command{
Use: "info <pkg>",
Args: cobra.ExactArgs(1),
Short: "Shows information about a package",
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
pkgName := args[0]
return runPkgInfo(pkgName)
})
},
})
cmd.AddCommand(func() *cobra.Command {
cmd := cobra.Command{
Use: "upgrade [pkgs]",
Short: "Installs newly available versions",
Long: `Upgrades all/selected packages. This is equivalent to running "makedeb ..." in each package's directory.`,
Run: func(cmd *cobra.Command, args []string) {
runFallibleCommand(func() error {
noConfirm, _ := cmd.Flags().GetBool("no-confirm")
return runUpgrade(upgradeArgs{
packages: args,
confirm: !noConfirm,
})
})
},
}
cmd.Flags().Bool("no-confirm", false, "do not ask for confirmation")
return &cmd
}())
// return the root command
return cmd
}()
// run the command
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
func mprDir(segments ...string) string {
mprDirEnv := os.Getenv("MPR_DIR")
if mprDirEnv != "" {
return filepath.Join(append([]string{mprDirEnv}, segments...)...)
}
userCacheDir, err := os.UserCacheDir()
if err != nil {
panic(err)
}
userCacheDir = filepath.Join(userCacheDir, "mpr-packages")
err = os.MkdirAll(userCacheDir, 0755)
if err != nil {
panic(err)
}
return filepath.Join(append([]string{userCacheDir}, segments...)...)
}
func mkcmd(loud bool, name string, arg ...string) *exec.Cmd {
if loud {
fmt.Printf("[#] %s ", name)
for _, a := range arg {
fmt.Printf("%s ", a)
}
fmt.Println()
}
cmd := exec.Command(name, arg...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
cmd.Dir = mprDir() // by default, commands are run in the mpr directory
return cmd
}
func installMakedeb() error {
_, err := exec.LookPath("makedeb")
if err == nil {
return nil
}
cmd := mkcmd(true, "bash", "-c", "wget -qO - 'https://shlink.makedeb.org/install' | MAKEDEB_RELEASE=makedeb bash -")
if err := cmd.Run(); err != nil {
return err
}
return nil
}
func listPackages() ([]string, error) {
// find all sub-directories in the mpr directory that:
// 1. Contain a PKGBUILD file
// 2. Contain a ".git" directory
packages := make([]string, 0)
candidateFiles, err := ioutil.ReadDir(mprDir())
if err != nil {
return packages, err
}
for _, entry := range candidateFiles {
// the entry must be a directory:
if !entry.IsDir() {
continue
}
// the directory must itself contain a PKGBUILD file:
if _, err := os.Stat(filepath.Join(mprDir(entry.Name()), "PKGBUILD")); err != nil {
continue
}
// the directory must itself contain a .git directory:
if _, err := os.Stat(filepath.Join(mprDir(entry.Name()), ".git")); err != nil {
continue
}
// now read the PKGBUILD file and check if it contains a "pkgname" variable:
pkgbuild := NewPKGBUILD(mprDir(entry.Name()))
pkgname, err := pkgbuild.getSingleVariable("pkgname")
if err != nil {
continue
}
packages = append(packages, pkgname)
}
sort.Strings(packages)
return packages, nil
}
func getPkgHEADCommitHash(pkg string) (string, error) {
var sbout, sberr strings.Builder
cmd := exec.Command("git", "rev-parse", "HEAD")
cmd.Stdout = &sbout
cmd.Stderr = &sberr
cmd.Dir = mprDir(pkg)
err := cmd.Run()
if err != nil {
if strings.Contains(sberr.String(), "not a git repository") {
return "NOT_A_GIT_REPOSITORY", nil
}
return "", fmt.Errorf("could not get HEAD commit hash for package %s: %w", pkg, err)
}
return strings.TrimSpace(string(sbout.String())), nil
}
func getPackageURL(spec string) string {
// if the spec is in USER/REPO format, assume it's a GitHub repo:
matched, _ := regexp.MatchString(`^([^/:]+)/([^/:]+)$`, spec)
if matched {
return "https://github.com/" + spec
}
// if the spec is ID (case insensitive), assume it's an MPR package:
matched, _ = regexp.MatchString(`(?i)^[a-z0-9_-]+$`, spec)
if matched {
return "https://mpr.makedeb.org/" + spec
}
return spec
}