Exemple #1
0
func Discover() ([]DiscoverInfo, error) {

	var devs []string

	s1, _ := filepath.Glob("/dev/ttyS*")
	s2, _ := filepath.Glob("/dev/ttyUSB*")
	devs = append(devs, s1...)
	devs = append(devs, s2...)

	var infos []DiscoverInfo

	for _, d := range devs {
		info := DiscoverInfo{
			PortName: d,
		}
		name := filepath.Base(d)
		subsystem := ""
		devpath := fmt.Sprintf("/sys/class/tty/%s/device", name)
		if _, err := os.Lstat(devpath); err == nil {
			devpath, _ = realpath.Realpath(devpath)
			subsystem = filepath.Join(devpath, "subsystem")
			subsystem, _ = realpath.Realpath(subsystem)
			subsystem = filepath.Base(subsystem)
		}

		usbpath := ""
		switch subsystem {
		case "usb-serial":
			usbpath = filepath.Dir(filepath.Dir(devpath))
			info.Type = PortTypeUsb
		case "usb":
			usbpath = filepath.Dir(devpath)
			info.Type = PortTypeUsb
		case "pnp":
			info.Type = PortTypeIntegrated
		case "platform":
			// Not a real serial port, just exposed by the driver
			continue
		default:
			fmt.Println("unknown subsystem", subsystem)
		}

		switch info.Type {
		case PortTypeUsb:
			info.Description = readLine(filepath.Join(usbpath, "product"))
			idvendor, _ := strconv.Atoi(readLine(filepath.Join(usbpath, "idVendor")))
			info.UsbVendorId = idvendor
			idproduct, _ := strconv.Atoi(readLine(filepath.Join(usbpath, "idProduct")))
			info.UsbProductId = idproduct
			info.UsbSerialNo = readLine(filepath.Join(usbpath, "serial"))
		}

		infos = append(infos, info)
	}

	return infos, nil
}
Exemple #2
0
func MustRealPath(path string) string {
	out, err := realpath.Realpath(path)
	if err != nil {
		panic(err)
	}
	return out
}
Exemple #3
0
func send_file(filename string) {
	var identifier string = generate_id()
	realpath, _ := realpath.Realpath(filename)
	filename = path.Base(filename)
	var hfn string = make_hash(filename)
	var host string = "local.dev"
	encrypt_file(realpath, hfn)
	fmt.Println(host, identifier)
}
Exemple #4
0
// Same as 'filepath.walk' but the 'path' is changed to its 'realpath' to
// resolve symbolic links and avoid loops.
func realPathWalk(path string, info os.FileInfo, walkFn filepath.WalkFunc, visited map[string]bool) error {
	realPath, err := realpath.Realpath(path)
	if err == nil {

		path = realPath
		if visited[path] {
			return nil
		}
		visited[path] = true

		var realInfo os.FileInfo
		realInfo, err = os.Lstat(path)
		if err == nil {
			info = realInfo
		}
	}

	err = walkFn(path, info, err)
	if err != nil {
		if info.IsDir() && err == filepath.SkipDir {
			return nil
		}
		return err
	}

	if !info.IsDir() {
		return nil
	}

	names, err := readDirNames(path)
	if err != nil {
		return walkFn(path, info, err)
	}

	for _, name := range names {
		filename := filepath.Join(path, name)
		fileInfo, err := os.Lstat(filename)
		if err != nil {
			if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
				return err
			}
		} else {
			err = realPathWalk(filename, fileInfo, walkFn, visited)
			if err != nil {
				if !fileInfo.IsDir() || err != filepath.SkipDir {
					return err
				}
			}
		}
	}
	return nil
}
Exemple #5
0
func fnRealpath(L *lua.LState) int {
	filep := L.CheckString(1)

	real, err := realpath.Realpath(filep)
	if err != nil {
		L.Push(lua.LNil)
		L.Push(lua.LString(err.Error()))
		return 2
	}
	L.Push(lua.LString(real))

	return 1
}
Exemple #6
0
func main() {
	// print the realpath result for each targets
	for _, target := range targets {
		p, err := realpath.Realpath(target)
		if err != nil {
			// output error
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}

		// normal output
		fmt.Fprintln(os.Stdout, p)
	}
}
Exemple #7
0
func (w *walker) Run(fr *FileRecord) error {
	if !options.Extensions[strings.ToLower(Ext(fr.input.path))] {
		fr.debug.Printf("Unknown extension '%v'", Ext(fr.input.path))
		return errInputFile
	}
	rpath, err := realpath.Realpath(fr.input.path)
	if err != nil {
		fr.error.Print("Cannot get real path:", err)
		return errInputFile
	}
	if w.visited[rpath] {
		fr.debug.Print("Duplicate file")
		return errInputFile
	}

	w.visited[rpath] = true
	return nil
}
Exemple #8
0
func fetchDir(fp string, fi os.FileInfo, err error) error {
	// can't walk here,
	// but continue walking elsewhere
	if err != nil {
		return nil
	}
	if !!fi.IsDir() && fp != "." {
		oldPath, _ := realpath.Realpath(".")
		matched, _ := filepath.Match("*/.git", fp)
		if matched {
			dirs := strings.Split(fp, ".")
			fmt.Println("Enter in :", dirs[0])
			fmt.Println("Trying to pull...")
			os.Chdir(dirs[0])
			pull()
			os.Chdir(oldPath)
			fmt.Println()
		}
	}
	return nil
}
Exemple #9
0
func (a *analyzer) RunAllScripts(fr *FileRecord, track int, defaultTags map[string]string) error {
	input := &fr.input
	output := &fr.output[track]

	prepareTrackTags(input, track)

	if o, ok := cache.index[input.path]; ok && len(o) > track {
		*output = cache.index[input.path][track]
		options.Gettags = false
	} else {

		// Default tags.
		output.Tags = make(map[string]string)
		for k, v := range input.tags {
			output.Tags[k] = v
		}
		for k, v := range defaultTags {
			output.Tags[k] = v
		}

		// Default codec options.
		output.Format = fr.Format.FormatName
	}

	// Create a Lua sandbox containing input and output, then run scripts.
	a.scriptLog.SetOutput(&fr.logBuf)
	for _, script := range cache.scripts {
		err := RunScript(a.L, script.name, input, output)
		if err != nil {
			fr.error.Printf("Script %s: %s", script.name, err)
			return err
		}
	}

	// Foolproofing.
	// -No format: use input.format.
	// -No parameters: use "-c:a copy".
	// -Empty output basename: use input path.
	// -Remove empty tags to avoid storing empty strings in FFmpeg.
	// -Do not remove source when file has multiple tracks.

	foolproof := func() {
		if output.Format == "" {
			output.Format = fr.Format.FormatName
		}

		if len(output.Parameters) == 0 {
			output.Parameters = []string{"-c:a", "copy"}
		}

		if Basename(output.Path) == "" {
			output.Path = input.path
		}

		var err error
		output.Path, err = filepath.Abs(output.Path)
		if err != nil {
			fr.warning.Print("Cannot get absolute path:", err)
		}

		for tag, value := range output.Tags {
			if value == "" {
				delete(output.Tags, tag)
			}
		}

		if input.trackCount > 1 {
			output.Rmsrc = false
		}
	}

	foolproof()
	// 'output.Write' should not be set from scripts.
	output.Write = existWriteSuffix

	// Check for existence.
	_, err := os.Stat(output.Path)
	if err == nil || !os.IsNotExist(err) {
		fr.status[track] = statusExist
		if cache.actions[actionExist] != "" {
			// 'output.Path' exists.
			// The realpath is required to see if transformation is inplace.
			output.Path, err = realpath.Realpath(output.Path)
			if err != nil {
				// The realpath can only be expanded when the parent folder exists.
				fr.error.Print(err)
				return err
			}
			fr.exist.path = output.Path

			err := prepareInput(fr, &fr.exist)
			if err != nil {
				fr.error.Print(err)
				return err
			}
			// Save output.Path to guarantee no action will change it.
			savedPath := output.Path
			prepareTrackTags(&fr.exist, track)
			err = RunAction(a.L, actionExist, input, output, &fr.exist)
			if err != nil {
				fr.error.Printf("Exist action: %s", err)
				return err
			}
			output.Path = savedPath
			foolproof()
		} else {
			// If no exist action is run, append a suffix.
			output.Write = existWriteSuffix
		}

		switch output.Write {
		case existWriteOver:
			if output.Path == input.path {
				if output.Rmsrc {
					fr.warning.Println("write file in-place:", output.Path)
				} else {
					fr.error.Print("cannot overwrite and keep source file at the same time:", input.path)
				}
			} else {
				fr.warning.Println("overwrite existing destination:", output.Path)
				if output.Rmsrc {
					fr.warning.Println("remove source:", input.path)
				}
			}
		case existWriteSkip:
			if output.Path == input.path && output.Rmsrc {
				fr.warning.Println("write file in-place:", output.Path)
			} else {
				fr.warning.Println("skip existing destination:", output.Path)
				if output.Rmsrc {
					fr.warning.Println("remove source:", input.path)
				}
			}

		default:
			output.Write = existWriteSuffix
			if output.Path == input.path && output.Rmsrc {
				fr.warning.Println("write file in-place:", output.Path)
			} else {
				fr.warning.Println("append suffix to existing destination:", output.Path)
				if output.Rmsrc {
					fr.warning.Println("remove source:", input.path)
				}
			}
		}
	} else {
		// Destination does not exist.
		if output.Rmsrc {
			fr.warning.Println("remove source:", input.path)
		}
	}

	return nil
}
Exemple #10
0
func splitGoPath() ([]string, error) {
	goPath_s := os.Getenv("GOPATH")
	if goPath_s == "" {
		//		fmt.Fprintln(os.Stderr, "GOPATH env var must be set")
		errMsg := fmt.Sprint("GOPATH environment variable must be set")
		return nil, errors.New(errMsg)
	}

	var err error
	wd := [3]string{}
	//	rwd, err := os.Getwd()
	wd[0], err = os.Getwd()
	if err != nil {
		panic(err)
	}
	//	xwd, err := filepath.Abs(rwd)
	wd[1], err = filepath.Abs(wd[0])
	if err != nil {
		panic(err)
	}
	//	awd, err := realpath.Realpath(xwd)
	wd[2], err = realpath.Realpath(wd[1])
	if err != nil {
		panic(err)
	}

	ret := make([]string, 0, 2)
	goPath := ""
	goPath_l := strings.Split(goPath_s, ":")
	awd := ""
gopathLoop:
	for _, goPath = range goPath_l {
		goPathPrefix := filepath.Join(goPath, "src")
		for i := range wd {
			//			if strings.HasPrefix(awd, goPathPrefix) {
			if strings.HasPrefix(wd[i], goPathPrefix) {
				if *debug {
					log.Printf("gopath='%s'\n", goPath)
				}
				ret = append(ret, goPath)
				awd = wd[i]
				break gopathLoop
			}
		}
	}
	if *debug {
		log.Printf("wd=%q, awd='%s', gopaths=%q, goPath='%s', len(goPath)=%d\n",
			wd, awd, goPath_l, goPath, len(goPath))
		//		log.Printf("wd='%s', awd='%s', len(awd)=%d, goPath='%s', len(goPath)=%d\n",
		//			rwd, awd, len(awd), goPath, len(goPath))
	}

	if len(ret) == 0 {
		//		fmt.Fprintln(os.Stderr, "not in a subfolder of $GOPATH/src")
		errMsg := fmt.Sprint("not in a subfolder of $GOPATH/src")
		return nil, errors.New(errMsg)
	}
	goPathBaseLen := len(goPath) + 1 + 4
	if len(awd) <= goPathBaseLen {
		//		fmt.Fprintln(os.Stderr, "not in a subfolder of $GOPATH/src")
		//		return ret
		errMsg := fmt.Sprint("not in a subfolder of $GOPATH/src")
		return ret, errors.New(errMsg)
	}

	goPkg := awd[goPathBaseLen:]
	ret = append(ret, goPkg)
	return ret, nil
}
Exemple #11
0
// Create a new destination file 'dst'. See makeTrackDst.
// As a special case, if the checksums match in input and dst, return "", nil.
// TODO: Test how memoization scales with visitedDstCovers.
func makeCoverDst(fr *FileRecord, dst string, inputPath string, checksum string) (string, error) {
	if st, err := os.Stat(dst); err == nil || !os.IsNotExist(err) {
		// 'dst' exists.

		// Realpath is required for cache key uniqueness.
		dst, err = realpath.Realpath(dst)
		if err != nil {
			return "", err
		}

		visitedDstCovers.RLock()
		visited := visitedDstCovers.v[dstCoverKey{path: dst, checksum: checksum}]
		visitedDstCovers.RUnlock()
		if visited {
			return "", nil
		}
		visitedDstCovers.Lock()
		visitedDstCovers.v[dstCoverKey{path: dst, checksum: checksum}] = true
		visitedDstCovers.Unlock()

		// Compute checksum of existing cover and early-out if equal.
		fd, err := os.Open(dst)
		if err != nil {
			return "", err
		}
		defer fd.Close()

		// TODO: Cache checksums.
		hi := st.Size()
		if hi > coverChecksumBlock {
			hi = coverChecksumBlock
		}

		buf := [coverChecksumBlock]byte{}
		_, err = (*fd).ReadAt(buf[:hi], 0)
		if err != nil && err != io.EOF {
			return "", err
		}
		dstChecksum := fmt.Sprintf("%x", md5.Sum(buf[:hi]))

		if checksum == dstChecksum {
			return "", nil
		}

		// If not inplace, create a temp file.
		f, err := TempFile(filepath.Dir(dst), StripExt(filepath.Base(dst))+"_", "."+Ext(dst))
		if err != nil {
			return "", err
		}
		dst = f.Name()
		f.Close()

	} else {
		// 'dst' does not exist.
		st, err := os.Stat(inputPath)
		if err != nil {
			return "", err
		}

		fd, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL, st.Mode())
		if err != nil {
			// Either the parent folder is not writable, or a race condition happened:
			// file was created between existence check and file creation.
			return "", err
		}
		fd.Close()

		// Save to cache.
		dst, err = realpath.Realpath(dst)
		if err != nil {
			return "", err
		}
		visitedDstCovers.Lock()
		visitedDstCovers.v[dstCoverKey{path: dst, checksum: checksum}] = true
		visitedDstCovers.Unlock()
	}

	return dst, nil
}