NewBufferFromFileWithCommand opens a new buffer with a given command If cmd.StartCursor is {-1, -1} the location does not overwrite what the cursor location would otherwise be (start of file, or saved cursor position if `savecursor` is enabled)
(path string, btype BufType, cmd Command)
| 273 | // would otherwise be (start of file, or saved cursor position if `savecursor` is |
| 274 | // enabled) |
| 275 | func NewBufferFromFileWithCommand(path string, btype BufType, cmd Command) (*Buffer, error) { |
| 276 | var err error |
| 277 | filename := path |
| 278 | if config.GetGlobalOption("parsecursor").(bool) && cmd.StartCursor.X == -1 && cmd.StartCursor.Y == -1 { |
| 279 | var cursorPos []string |
| 280 | filename, cursorPos = util.GetPathAndCursorPosition(filename) |
| 281 | cmd.StartCursor, err = ParseCursorLocation(cursorPos) |
| 282 | if err != nil { |
| 283 | cmd.StartCursor = Loc{-1, -1} |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | filename, err = util.ReplaceHome(filename) |
| 288 | if err != nil { |
| 289 | return nil, err |
| 290 | } |
| 291 | |
| 292 | fileInfo, serr := os.Stat(filename) |
| 293 | if serr != nil && !errors.Is(serr, fs.ErrNotExist) { |
| 294 | return nil, serr |
| 295 | } |
| 296 | if serr == nil && fileInfo.IsDir() { |
| 297 | return nil, errors.New("Error: " + filename + " is a directory and cannot be opened") |
| 298 | } |
| 299 | if serr == nil && !fileInfo.Mode().IsRegular() { |
| 300 | return nil, errors.New("Error: " + filename + " is not a regular file and cannot be opened") |
| 301 | } |
| 302 | |
| 303 | f, err := os.OpenFile(filename, os.O_WRONLY, 0) |
| 304 | readonly := errors.Is(err, fs.ErrPermission) |
| 305 | f.Close() |
| 306 | |
| 307 | file, err := os.Open(filename) |
| 308 | if err == nil { |
| 309 | defer file.Close() |
| 310 | } |
| 311 | |
| 312 | var buf *Buffer |
| 313 | if errors.Is(err, fs.ErrNotExist) { |
| 314 | // File does not exist -- create an empty buffer with that name |
| 315 | buf = NewBufferFromString("", filename, btype) |
| 316 | } else if err != nil { |
| 317 | return nil, err |
| 318 | } else { |
| 319 | buf = NewBuffer(file, util.FSize(file), filename, btype, cmd) |
| 320 | if buf == nil { |
| 321 | return nil, errors.New("could not open file") |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | if readonly && prompt != nil { |
| 326 | prompt.Message(fmt.Sprintf("Warning: file is readonly - %s will be attempted when saving", config.GlobalSettings["sucmd"].(string))) |
| 327 | // buf.SetOptionNative("readonly", true) |
| 328 | } |
| 329 | |
| 330 | return buf, nil |
| 331 | } |
| 332 |
no test coverage detected