func dirList(w http.ResponseWriter, f *os.File) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if dirs, err := f.Readdir(-1); err == nil {
		files := make([]map[string]string, len(dirs)+1)
		files[0] = map[string]string{
			"name": "..", "href": "..", "size": "-", "mtime": "-",
		}
		for i, d := range dirs {
			href := d.Name()
			if d.IsDir() {
				href += "/"
			}
			files[i+1] = map[string]string{
				"name":  d.Name(),
				"href":  href,
				"size":  formatSize(d),
				"mtime": d.ModTime().Format("2006-01-02 15:04:05"),
			}
		}
		reloadCfg.dirListTmpl.Execute(w, map[string]interface{}{
			"dir":   f.Name(),
			"files": files,
		})
	}
}
Example #2
0
func dmndBlastXFine(queries *os.File, outFilename, fineFilename string) error {

	cmd := exec.Command(
		flagDmnd,
		"blastx",
		"--sensitive",
		"-d", fineFilename,
		"-q", queries.Name(),
		"--threads", s(flagGoMaxProcs),
		"-a", outFilename,
		"--compress", "0",
		"-c", "1",
		"--top", s(flagFineDmndMatch))
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout

	err := mica.Exec(cmd)
	if err != nil {
		return fmt.Errorf("Error using diamond to blast coarse db: %s\n", err)
	}
	if !flagDmndOutput {
		daaFile, err := os.Open(outFilename)
		if err != nil {
			return fmt.Errorf("Error opening diamond output: %s\n", err)
		}
		tabularFile, err := convertDmndToBlastTabular(daaFile)
		if err != nil {
			return fmt.Errorf("Error converting diamond output: %s\n", err)
		}
		os.Rename(tabularFile.Name(), outFilename)

	}

	return nil
}
Example #3
0
// CreatePool is the programmatic example of "dmsetup create".
// It creates a device with the specified poolName, data and metadata file and block size.
func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error {
	task, err := TaskCreateNamed(deviceCreate, poolName)
	if task == nil {
		return err
	}

	size, err := GetBlockDeviceSize(dataFile)
	if err != nil {
		return fmt.Errorf("devicemapper: Can't get data size %s", err)
	}

	params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize)
	if err := task.addTarget(0, size/512, "thin-pool", params); err != nil {
		return fmt.Errorf("devicemapper: Can't add target %s", err)
	}

	var cookie uint
	var flags uint16
	flags = DmUdevDisableSubsystemRulesFlag | DmUdevDisableDiskRulesFlag | DmUdevDisableOtherRulesFlag
	if err := task.setCookie(&cookie, flags); err != nil {
		return fmt.Errorf("devicemapper: Can't set cookie %s", err)
	}
	defer UdevWait(&cookie)

	if err := task.run(); err != nil {
		return fmt.Errorf("devicemapper: Error running deviceCreate (CreatePool) %s", err)
	}

	return nil
}
Example #4
0
func tree_cat_recursive(files []os.FileInfo, dir *os.File) {

	for _, fileInfo := range files {

		if fileInfo.IsDir() {

			sourcedir := dir.Name() + "/" + fileInfo.Name()
			fmt.Println(sourcedir)

			new_dir, err := os.Open(sourcedir)
			checkerror(err)
			defer new_dir.Close()

			// Grab the files (list)
			new_files, err := new_dir.Readdir(0)
			checkerror(err)

			//() Recursive
			tree_cat_recursive(new_files, new_dir)

		} else {

			filename := dir.Name() + "/" + fileInfo.Name()
			//fmt.Println( filename , "\t", fileInfo.Size(), "\t", fileInfo.Mode(), fileInfo.ModTime() )
			fmt.Println(filename)

			//() cat the filecontent
			cat_file(filename)
		}
	}
}
Example #5
0
func (v *Volume) load(alsoLoadIndex bool) error {
	var e error
	fileName := path.Join(v.dir, v.Id.String())
	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
		return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
	} else if !exists || canWrite {
		v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
	} else if exists && canRead {
		glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
		v.dataFile, e = os.Open(fileName + ".dat")
		v.readOnly = true
	} else {
		return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
	}
	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaType == CopyNil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
			}

			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
			if indexFile != nil {
				glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
				if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
					glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
				} else {
					indexFile.Close()
					os.Remove(indexFile.Name())
					indexFile = nil
				}
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
Example #6
0
func (s *staticDB) Put(file *os.File, size int) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if _, ok := s.assets[file.Name()]; ok {
		return fmt.Errorf("file already known, %q", file.Name())
	}

	buf := bytes.NewBuffer(nil)

	_, err := io.Copy(buf, file)
	if err != nil {
		return err
	}

	data := buf.Bytes()

	mimetype := mime.TypeByExtension(filepath.Ext(file.Name()))
	if mimetype == "" {
		log.Printf("[INFO] Couldn't detect mimetype from exntension, sniffing content: %q", file.Name())
		mimetype = http.DetectContentType(data)
	}
	log.Printf("[INFO] Mimetype of %q: %q", file.Name(), mimetype)

	h := md5.New()
	_, _ = h.Write(data)

	s.assets[file.Name()] = &asset{
		md5hex:   hex.EncodeToString(h.Sum(nil)),
		content:  data,
		mimetype: mimetype,
	}

	return nil
}
Example #7
0
func (c *client) startUpload(id uint64, inPath string) (cancel func()) {
	killChan := make(chan bool, 1)
	go func() {
		var detachment *pond.Message_Detachment
		var tmp *os.File
		var err error
		if tmp, err = ioutil.TempFile("" /* default tmp dir */, "pond-upload-"); err != nil {
			err = errors.New("failed to create temp file: " + err.Error())
		} else {
			os.Remove(tmp.Name())
			defer tmp.Close()
			detachment, err = saveEncrypted(c.rand, c.backgroundChan, tmp, id, inPath, killChan)
			if err == nil {
				err = c.uploadDetachment(c.backgroundChan, tmp, id, killChan)
			}
		}
		if err == nil {
			detachment.Url = proto.String(c.buildDetachmentURL(id))
			c.log.Printf("Finished upload of %s", *detachment.Url)
			c.backgroundChan <- DetachmentComplete{id, detachment}
		} else {
			c.backgroundChan <- DetachmentError{id, err}
		}
		tmp.Close()
	}()
	return func() {
		killChan <- true
	}
}
func addFileToTar(fileWriter *os.File, tarWriter *tar.Writer, info os.FileInfo, relativePath, fullPath string) error {
	if relativePath == fileWriter.Name() || relativePath == "." || relativePath == ".." {
		return nil
	}

	if h, err := tar.FileInfoHeader(info, fullPath); err == nil {
		h.Name = relativePath
		if err := tarWriter.WriteHeader(h); err != nil {
			return err
		}
	}

	if info.IsDir() {
		return nil
	}

	li, err := os.Lstat(fullPath)
	if err != nil {
		return err
	}
	if li.Mode()&os.ModeSymlink == os.ModeSymlink {
		return nil
	}

	fr, err := os.Open(fullPath)
	if err != nil {
		return err
	}
	defer fr.Close()
	if _, err := io.Copy(tarWriter, fr); err != nil {
		return err
	}

	return nil
}
Example #9
0
func NewSlowLogParser(file *os.File, stopChan <-chan bool, opt Options) *SlowLogParser {
	// Seek to the offset, if any.
	// @todo error if start off > file size
	if opt.StartOffset > 0 {
		// @todo handle error
		file.Seek(int64(opt.StartOffset), os.SEEK_SET)
	}

	if opt.Debug {
		l.SetFlags(l.Ltime | l.Lmicroseconds)
		fmt.Println()
		l.Println("parsing " + file.Name())
	}

	p := &SlowLogParser{
		stopChan:    stopChan,
		opt:         opt,
		file:        file,
		EventChan:   make(chan *log.Event),
		inHeader:    false,
		inQuery:     false,
		headerLines: 0,
		queryLines:  0,
		bytesRead:   opt.StartOffset,
		lineOffset:  0,
		event:       log.NewEvent(),
	}
	return p
}
Example #10
0
File: gg.go Project: zbq/gg
func SendFile(file *os.File, fileLen int64) bool {
	var laddr = &net.TCPAddr{}
	var raddr = &net.TCPAddr{IP: Server.Nets[0].IP, Port: Server.Port}
	conn, err := net.DialTCP("tcp4", laddr, raddr)
	if err != nil {
		return false
	}
	conn.SetTimeout(2 * SECOND)
	defer conn.Close()

	pkt := make([]byte, MAX_TCP_PKT)
	if !responseServerAuth(conn, pkt) {
		return false
	}

	contentLen := int64(0)
	if fileLen%int64(Cipher.BlockSize()) == 0 {
		contentLen = fileLen
	} else {
		contentLen = (fileLen/int64(Cipher.BlockSize()) + 1) * int64(Cipher.BlockSize())
	}

	pktlen := 0
	pktlen += pktAddHeader(pkt[pktlen:], PACKET_TYPE_TAG, PACKET_TYPE_SEND_FILE)
	pktlen += pktAddHeader(pkt[pktlen:], USERNAME_TAG, Self.Name)
	pktlen += pktAddHeader(pkt[pktlen:], HOSTNAME_TAG, Self.Hostname)
	pktlen += pktAddHeader(pkt[pktlen:], FILE_NAME_TAG, filepath.Base(file.Name()))
	pktlen += pktAddHeader(pkt[pktlen:], CONTENT_LEN_TAG, strconv.Itoa64(contentLen))
	pktlen += pktAddHeader(pkt[pktlen:], PADDING_LEN_TAG, strconv.Itoa64(contentLen-fileLen))
	pktlen += pktAddHeaderEndMark(pkt[pktlen:])

	if writeBuf(conn, pkt[:pktlen]) != pktlen {
		return false
	}
	encrypter := NewCBCEncrypter()
	for {
		if fileLen < int64(cap(pkt)) {
			pkt = pkt[:fileLen]
		} else {
			pkt = pkt[:cap(pkt)]
		}
		if n, _ := fullRead(file, pkt); n != len(pkt) {
			return false
		}
		fileLen -= int64(len(pkt))
		if len(pkt)%Cipher.BlockSize() != 0 {
			//at file end
			n := (len(pkt)/Cipher.BlockSize() + 1) * Cipher.BlockSize()
			pkt = pkt[:n]
		}
		encrypter.CryptBlocks(pkt, pkt)
		if writeBuf(conn, pkt) != len(pkt) {
			return false
		}
		if fileLen <= 0 {
			break
		}
	}
	return true
}
Example #11
0
File: html.go Project: achanda/go
// htmlOutput reads the profile data from profile and generates an HTML
// coverage report, writing it to outfile. If outfile is empty,
// it writes the report to a temporary file and opens it in a web browser.
func htmlOutput(profile, outfile string) error {
	profiles, err := ParseProfiles(profile)
	if err != nil {
		return err
	}

	var d templateData

	for _, profile := range profiles {
		fn := profile.FileName
		if profile.Mode == "set" {
			d.Set = true
		}
		file, err := findFile(fn)
		if err != nil {
			return err
		}
		src, err := ioutil.ReadFile(file)
		if err != nil {
			return fmt.Errorf("can't read %q: %v", fn, err)
		}
		var buf bytes.Buffer
		err = htmlGen(&buf, src, profile.Boundaries(src))
		if err != nil {
			return err
		}
		d.Files = append(d.Files, &templateFile{
			Name:     fn,
			Body:     template.HTML(buf.String()),
			Coverage: percentCovered(profile),
		})
	}

	var out *os.File
	if outfile == "" {
		var dir string
		dir, err = ioutil.TempDir("", "cover")
		if err != nil {
			return err
		}
		out, err = os.Create(filepath.Join(dir, "coverage.html"))
	} else {
		out, err = os.Create(outfile)
	}
	err = htmlTemplate.Execute(out, d)
	if err == nil {
		err = out.Close()
	}
	if err != nil {
		return err
	}

	if outfile == "" {
		if !browser.Open("file://" + out.Name()) {
			fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
		}
	}

	return nil
}
Example #12
0
func (r *Relay) setLogFile(logFile string) {
	r.status.Update("log-relay", "Setting log file: "+logFile)

	if logFile == "" {
		r.logger = nil
		r.logFile = ""
		r.status.Update("log-file", "")
		return
	}

	var file *os.File
	if logFile == "STDOUT" {
		file = os.Stdout
	} else if logFile == "STDERR" {
		file = os.Stderr
	} else {
		if !filepath.IsAbs(logFile) {
			logFile = filepath.Join(pct.Basedir.Path(), logFile)
		}
		var err error
		file, err = os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
		if err != nil {
			r.internal(err.Error())
			return
		}
	}
	logger := golog.New(file, "", golog.Ldate|golog.Ltime|golog.Lmicroseconds)
	r.logger = logger
	r.logFile = file.Name()
	r.status.Update("log-file", logFile)
}
Example #13
0
func saveAttachment(contact contactInfo, attachment io.Reader, name string, msg *textsecure.Message) (err error) {
	var output *os.File

	attachmentPath := contact.AttachmentDir

	err = os.MkdirAll(attachmentPath, 0700)

	if err != nil {
		return
	}

	if name == "" {
		output, err = ioutil.TempFile(attachmentPath, "attachment_")
	} else {
		outputPath := filepath.Join(attachmentPath, name)
		output, err = os.OpenFile(outputPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_TRUNC, 0600)
	}

	if err != nil {
		return
	}
	defer output.Close()

	io.Copy(output, attachment)
	status.Log(syslog.LOG_NOTICE, "saved attachment from %s %s\n", contact.Name, contact.Number)

	name = relativePath(output.Name())
	updateHistory(contact, "["+name+"]", "<", msg.Timestamp())

	return
}
Example #14
0
func convertDmndToBlastTabular(daa *os.File) (*os.File, error) {
	dmndOutFile, err := ioutil.TempFile(".", "dmnd-out-tab-")
	if err != nil {
		return nil, fmt.Errorf("Could not build temporary file for diamond output: %s", err)
	}

	cmd := exec.Command(
		flagDmnd,
		"view",
		"-o", dmndOutFile.Name(),
		"-a", daa.Name())

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout

	err = mica.Exec(cmd)
	if err != nil {
		return nil, fmt.Errorf("Error converting daa file to blast tabular: %s", err)
	}
	// err = os.Remove(daa.Name())
	// if err != nil {
	// 	return nil, fmt.Errorf("Error destroying .daa file: %s", err)
	// }
	return dmndOutFile, nil
}
Example #15
0
File: rpc.go Project: Jirai/gohn
func extractM4A(file *os.File, offset string, duration string, output string) error {
	path, err := exec.LookPath("ffmpeg")
	if err != nil {
		return err
	}

	if offset == "" {
		offset = "0"
	}

	args := []string{"-ss", offset}

	if duration != "" {
		args = append(args, "-t", duration)
	}

	args = append(args, "-i", file.Name(), "-vn", "-y", "-acodec", "copy", output)

	cmd := exec.Command(path, args...)
	log.Println(cmd.Args)

	err = cmd.Run()
	if err != nil {
		return err
	}

	return nil
}
Example #16
0
// walks through the index file, calls fn function with each key, offset, size
// stops with the error returned by the fn function
func WalkIndexFile(r *os.File, fn func(key uint64, offset, size uint32) error) error {
	var readerOffset int64
	bytes := make([]byte, 16*RowsToRead)
	count, e := r.ReadAt(bytes, readerOffset)
	glog.V(3).Infoln("file", r.Name(), "readerOffset", readerOffset, "count", count, "e", e)
	readerOffset += int64(count)
	var (
		key          uint64
		offset, size uint32
		i            int
	)

	for count > 0 && e == nil || e == io.EOF {
		for i = 0; i+16 <= count; i += 16 {
			key, offset, size = idxFileEntry(bytes[i : i+16])
			if e = fn(key, offset, size); e != nil {
				return e
			}
		}
		if e == io.EOF {
			return nil
		}
		count, e = r.ReadAt(bytes, readerOffset)
		glog.V(3).Infoln("file", r.Name(), "readerOffset", readerOffset, "count", count, "e", e)
		readerOffset += int64(count)
	}
	return e
}
Example #17
0
File: main.go Project: bbhoss/slug
func main() {
	fmt.Printf("Initializing slug for %s...", workingDir)
	s := slug.NewSlug(*fApiKey, *fAppName, workingDir)
	fmt.Printf("done\nArchiving %s...", workingDir)
	var tarFile *os.File
	if *fTar != "" {
		var err error
		tarFile, err = os.Open(*fTar)
		if err != nil {
			log.Println(err)
			return
		}
		s.SetArchive(tarFile)
	} else {
		tarFile = s.Archive()
	}

	fmt.Printf("done\nPushing %s...", tarFile.Name())
	err := s.Push()
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Printf("done\n")
	if *fRelease {
		fmt.Printf("Releasing...")
		release := s.Release()
		fmt.Printf("done (v%d)", release.Version)
	}
}
func addFileToTar(fileWriter *os.File, tarWriter *tar.Writer, info os.FileInfo, containingPath string, fullPath string) error {
	var (
		relpath string
		err     error
	)

	if relpath, err = filepath.Rel(containingPath, fullPath); err != nil {
		return err
	}

	if relpath == fileWriter.Name() || relpath == "." || relpath == ".." {
		return nil
	}

	if h, _ := tar.FileInfoHeader(info, fullPath); h != nil {
		h.Name = relpath
		if err := tarWriter.WriteHeader(h); err != nil {
			return err
		}
	}

	if !info.IsDir() {
		fr, err := os.Open(fullPath)
		if err != nil {
			return err
		}
		defer fr.Close()
		if _, err := io.Copy(tarWriter, fr); err != nil {
			return err
		}
	}

	return nil
}
Example #19
0
func (c *client) startDownload(id uint64, outPath string, detachment *pond.Message_Detachment) (cancel func()) {
	killChan := make(chan bool, 1)
	go func() {
		var tmp *os.File
		var err error
		if tmp, err = ioutil.TempFile("" /* default tmp dir */, "pond-download-"); err != nil {
			err = errors.New("failed to create temp file: " + err.Error())
		} else {
			os.Remove(tmp.Name())
			defer tmp.Close()
			err = c.downloadDetachment(c.backgroundChan, tmp, id, *detachment.Url, killChan)
			if err == nil {
				_, err := tmp.Seek(0, 0 /* from start */)
				if err == nil {
					err = saveDecrypted(c.backgroundChan, outPath, id, tmp, detachment, killChan)
				}
			}
		}
		if err == nil {
			c.backgroundChan <- DetachmentComplete{id, nil}
		} else {
			c.backgroundChan <- DetachmentError{id, err}
		}
		tmp.Close()
	}()
	return func() {
		killChan <- true
	}
}
Example #20
0
func testFuzz(t *testing.T, srcname, start string) {
	var err error
	var grammar ebnf.Grammar
	var tempfile *os.File

	grammar, err = rebnf.Parse(srcname, nil)
	if err != nil {
		t.Error(err)
	}
	dst := new(bytes.Buffer)
	ctx := rebnf.NewCtx(20, 20, " ", false)
	err = ctx.Random(dst, grammar, start)
	if err != nil {
		t.Error(err)
	}
	dstbytes := dst.Bytes()

	// Test gofmt.
	testFmt(t, "-", bytes.NewBuffer(dstbytes))

	// Test go build.
	tempfile, err = ioutil.TempFile("test", "tmp_")
	if err != nil {
		t.Error(err)
	}
	tempfile.Close()
	testBuild(t, tempfile.Name(), "-", bytes.NewBuffer(dstbytes))
}
Example #21
0
File: fs.go Project: cnhup/httpmq
func (h *fsHandler) newFSFile(f *os.File, fileInfo os.FileInfo, compressed bool) (*fsFile, error) {
	n := fileInfo.Size()
	contentLength := int(n)
	if n != int64(contentLength) {
		f.Close()
		return nil, fmt.Errorf("too big file: %d bytes", n)
	}

	// detect content-type
	ext := fileExtension(fileInfo.Name(), compressed)
	contentType := mime.TypeByExtension(ext)
	if len(contentType) == 0 {
		data, err := readFileHeader(f, compressed)
		if err != nil {
			return nil, fmt.Errorf("cannot read header of the file %q: %s", f.Name(), err)
		}
		contentType = http.DetectContentType(data)
	}

	lastModified := fileInfo.ModTime()
	ff := &fsFile{
		h:               h,
		f:               f,
		contentType:     contentType,
		contentLength:   contentLength,
		compressed:      compressed,
		lastModified:    lastModified,
		lastModifiedStr: AppendHTTPDate(nil, lastModified),

		t: time.Now(),
	}
	return ff, nil
}
Example #22
0
func load_config(
	config string,
	rules string,
	c *C) (conf *FileConfig, cleanup func()) {
	var fconf, rconf *os.File
	var err error

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	cleanup = func() {
		fconf.Close()
		rconf.Close()
	}

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString(
		"[Settings]\n" + config + "\n" + "rules=" + rconf.Name() + "\n")
	fconf.Sync()
	rconf.WriteString(rules + "\n")
	rconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Assert(conf, Not(Equals), nil)
	c.Assert(err, Equals, nil)
	return
}
Example #23
0
func downloadFile(URL string) (fileName string, err error) {
	var file *os.File
	if file, err = ioutil.TempFile(os.TempDir(), "torrent-imageviewer"); err != nil {
		return
	}

	defer func() {
		if err := file.Close(); err != nil {
			log.Printf("Error closing torrent file: %s", err)
		}
	}()

	response, err := http.Get(URL)
	if err != nil {
		return
	}

	defer func() {
		if err := response.Body.Close(); err != nil {
			log.Printf("Error closing torrent file: %s", err)
		}
	}()

	_, err = io.Copy(file, response.Body)

	return file.Name(), err
}
Example #24
0
func (t *FileConfigTest) TestRulesFileDoesNotExist(c *C) {
	var fconf, rconf *os.File
	var err error
	var conf Config

	fconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	rconf, err = ioutil.TempFile("", "")
	if err != nil {
		panic(err)
	}
	defer (func() {
		fconf.Close()
		rconf.Close()
	})()

	// Trailing \n is required by go-config issue #3.
	fconf.WriteString("[Settings]\nloglevel=debug\nrules=\n")
	fconf.Sync()

	conf, err = NewFileConfig(fconf.Name())
	c.Check(conf, Equals, (*FileConfig)(nil))
	c.Check(err, Not(Equals), nil)
}
Example #25
0
// UploadReleaseAsset creates an asset by uploading a file into a release repository.
// To upload assets that cannot be represented by an os.File, call NewUploadRequest directly.
//
// GitHub API docs : http://developer.github.com/v3/repos/releases/#upload-a-release-asset
func (s *RepositoriesService) UploadReleaseAsset(owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) {
	u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id)
	u, err := addOptions(u, opt)
	if err != nil {
		return nil, nil, err
	}

	stat, err := file.Stat()
	if err != nil {
		return nil, nil, err
	}
	if stat.IsDir() {
		return nil, nil, errors.New("the asset to upload can't be a directory")
	}

	mediaType := mime.TypeByExtension(filepath.Ext(file.Name()))
	req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType)
	if err != nil {
		return nil, nil, err
	}

	asset := new(ReleaseAsset)
	resp, err := s.client.Do(req, asset)
	if err != nil {
		return nil, resp, err
	}
	return asset, resp, err
}
Example #26
0
func removeTemporaryFile(f *os.File) {
	_ = f.Close() // no point checking error on close here
	err := os.Remove(f.Name())
	if err != nil && !os.IsNotExist(err) {
		log.Printf("failed to remove temporary file: %s\n", err)
	}
}
Example #27
0
// signFile will search for the file and sign it
// it always returns nil as an error
func signFile(c *cli.Context) error {
	if c.Args().First() == "" {
		log.Fatal("Please give the file to sign", 1)
	}
	fileName := c.Args().First()
	groupToml := c.String(optionGroup)
	file, err := os.Open(fileName)
	log.ErrFatal(err, "Couldn't read file to be signed:")

	sig, err := sign(file, groupToml)
	log.ErrFatal(err, "Couldn't create signature:")

	log.Lvl3(sig)
	var outFile *os.File
	outFileName := c.String("out")
	if outFileName != "" {
		outFile, err = os.Create(outFileName)
		log.ErrFatal(err, "Couldn't create signature file:")
	} else {
		outFile = os.Stdout
	}
	writeSigAsJSON(sig, outFile)
	if outFileName != "" {
		log.Lvl2("Signature written to: %s", outFile.Name())
	} // else keep the Stdout empty
	return nil
}
Example #28
0
// This is the programmatic example of "dmsetup create"
func createPool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error {
	task, err := createTask(DeviceCreate, poolName)
	if task == nil {
		return err
	}

	size, err := GetBlockDeviceSize(dataFile)
	if err != nil {
		return fmt.Errorf("Can't get data size %s", err)
	}

	params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize)
	if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil {
		return fmt.Errorf("Can't add target %s", err)
	}

	var cookie uint = 0
	if err := task.SetCookie(&cookie, 0); err != nil {
		return fmt.Errorf("Can't set cookie %s", err)
	}

	if err := task.Run(); err != nil {
		return fmt.Errorf("Error running DeviceCreate (createPool) %s", err)
	}

	UdevWait(cookie)

	return nil
}
func fileWriter(t *testing.T, file *os.File, logs []string) {
	filename := file.Name()
	time.Sleep(1 * time.Second) // wait for start Tail...

	for _, line := range logs {
		if strings.Index(line, RotateMarker) != -1 {
			log.Println("fileWriter: rename file => file.old")
			os.Rename(filename, filename+".old")
			file.Close()
			file, _ = os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)
			log.Println("fileWriter: re-opened file")
		} else if strings.Index(line, TruncateMarker) != -1 {
			time.Sleep(1 * time.Second)
			log.Println("fileWriter: truncate(file, 0)")
			os.Truncate(filename, 0)
			file.Seek(int64(0), os.SEEK_SET)
		}
		_, err := file.WriteString(line)
		log.Print("fileWriter: wrote ", line)
		if err != nil {
			log.Println("write failed", err)
		}
		time.Sleep(1 * time.Millisecond)
	}
	file.Close()
}
Example #30
0
func ReadAllOrWarn(in *os.File) ([]byte, error) {
	content, err := ioutil.ReadAll(in)
	if err != nil {
		statLog.Printf("error reading %s: %s\n", in.Name(), err)
	}
	return content, err
}