| 🛟 Updated. 28d5985 k33g 17h ago | 1 | package snippets |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | |
| 7 | "codeberg.org/turbo-editors/turbo-core/profile" |
| 8 | "codeberg.org/turbo-editors/turbo-core/projectfile" |
| 9 | ) |
| 10 | |
| 11 | // template returns the starter file: the profile's Templates.Snippets with the |
| 12 | // name of the ungrouped group and the user's own snippets path filled into its |
| 13 | // comments, in that order. |
| 14 | func template(p profile.Profile) string { |
| 15 | return fmt.Sprintf(p.Templates.Snippets, ungroupedName, userPathComment(p)) |
| 16 | } |
| 17 | |
| 18 | // userPathComment returns the user's snippets path for the template's comment, |
| 19 | // or a plain description when there is nowhere to put one. |
| 20 | func userPathComment(p profile.Profile) string { |
| 21 | if path := UserPath(p); path != "" { |
| 22 | return path |
| 23 | } |
| 24 | return "(no configuration directory on this system)" |
| 25 | } |
| 26 | |
| 27 | // Create writes a starter snippets file for a project and returns its path. |
| 28 | // |
| 29 | // A project that already has one gives ErrExists and is left untouched: a file |
| 30 | // somebody has been editing is never overwritten by a menu item. |
| 31 | // |
| 32 | // path, err := snippets.Create(p, ".") |
| 33 | // if errors.Is(err, snippets.ErrExists) { |
| 34 | // // already there; open it instead |
| 35 | // } |
| 36 | func Create(p profile.Profile, projectDir string) (string, error) { |
| 37 | path := ProjectPath(p, projectDir) |
| 38 | if exists(path) { |
| 39 | return path, fmt.Errorf("%w: %s", ErrExists, path) |
| 40 | } |
| 41 | |
| 42 | if err := projectfile.Write(path, []byte(template(p))); err != nil { |
| 43 | return path, err |
| 44 | } |
| 45 | return path, nil |
| 46 | } |
| 47 | |
| 48 | // Exists reports whether a project has a snippets file that can be read. |
| 49 | func Exists(p profile.Profile, projectDir string) bool { |
| 50 | return exists(ProjectPath(p, projectDir)) |
| 51 | } |
| 52 | |
| 53 | // exists reports whether a path is a regular file. A directory in its place |
| 54 | // counts as absent: it is not something Load could have read. |
| 55 | func exists(path string) bool { |
| 56 | info, err := os.Stat(path) |
| 57 | return err == nil && info.Mode().IsRegular() |
| 58 | } |