remote_stat.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package procutils
  15. import (
  16. "os"
  17. "runtime"
  18. "strings"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. )
  23. type sFileStat struct {
  24. FileSize int64 `json:"file_size"`
  25. FileType string `json:"file_type"`
  26. FileName string `json:"file_name"`
  27. LastModAt time.Time `json:"last_mod_at"`
  28. }
  29. func (s *sFileStat) Name() string {
  30. return s.FileName
  31. }
  32. func (s *sFileStat) Size() int64 {
  33. return s.FileSize
  34. }
  35. func (s *sFileStat) Mode() os.FileMode {
  36. if s.IsDir() {
  37. return os.ModeDir
  38. }
  39. return os.FileMode(0)
  40. }
  41. func (s *sFileStat) ModTime() time.Time {
  42. return s.LastModAt
  43. }
  44. func (s *sFileStat) IsDir() bool {
  45. return s.FileType == "directory"
  46. }
  47. func (s *sFileStat) Sys() interface{} {
  48. return nil
  49. }
  50. func RemoteStat(filename string) (os.FileInfo, error) {
  51. args := []string{}
  52. switch runtime.GOOS {
  53. case "darwin":
  54. args = []string{"-f", `{"file_size":%z,"file_name":"%N","file_type":"%T"}`, filename}
  55. default:
  56. args = []string{"-c", `{"file_size":%s,"file_name":"%n","file_type":"%F"}`, filename}
  57. }
  58. output, err := NewRemoteCommandAsFarAsPossible("stat", args...).Output()
  59. if err != nil {
  60. if strings.Contains(strings.ToLower(string(output)), "no such file or directory") {
  61. return nil, os.ErrNotExist
  62. }
  63. return nil, errors.Wrapf(err, "NewRemoteCommandAsFarAsPossible with stat %v: %s", args, output)
  64. }
  65. json, err := jsonutils.Parse(output)
  66. if err != nil {
  67. return nil, errors.Error(output)
  68. }
  69. fs := &sFileStat{}
  70. err = json.Unmarshal(fs)
  71. if err != nil {
  72. return nil, errors.Wrap(err, "json.Unmarshal")
  73. }
  74. return fs, nil
  75. }