/*
 Creates the named tagfile and writes key value pairs to it, with indented
 formatting as indicated in the BagIt spec.
*/
772141
func (tf *TagFile) Create() error {
	// Create directory if needed.
	if err := os.MkdirAll(filepath.Dir(tf.name), 0777); err != nil {
		return err
	}

	// Create the tagfile.
	fileOut, err := os.Create(tf.Name())
	if err != nil {
		return err
	}
	defer fileOut.Close()

	// Write fields and data to the file.
	for _, f := range tf.Data.Fields() {
		field, err := formatField(f.Label(), f.Value())
		if err != nil {
			return err
		}
		_, err = fmt.Fprintln(fileOut, field)
		if err != nil {
			return err
		}
	}

	return nil
}
536687
func writeTaggedField(bufferBase32 *bytes.Buffer, dataType byte, data []byte) error {
	// Length must be exactly 10 bits, so add leading zero groups if
	// needed.
	lenBase32 := uint64ToBase32(uint64(len(data)))
	for len(lenBase32) < 2 {
		lenBase32 = append([]byte{0}, lenBase32...)
	}

	if len(lenBase32) != 2 {
		return fmt.Errorf("data length too big to fit within 10 bits: %d",
			len(data))
	}

	err := bufferBase32.WriteByte(dataType)
	if err != nil {
		return fmt.Errorf("unable to write to buffer: %v", err)
	}
	_, err = bufferBase32.Write(lenBase32)
	if err != nil {
		return fmt.Errorf("unable to write to buffer: %v", err)
	}
	_, err = bufferBase32.Write(data)
	if err != nil {
		return fmt.Errorf("unable to write to buffer: %v", err)
	}

	return nil
}
174596
func TagFilename(name, tag string) string {
	dir, file := filepath.Dir(name), filepath.Base(name)
	ext := filepath.Ext(file)
	withoutExt := file[:len(file)-len(ext)]
	return filepath.Join(dir, withoutExt+"~"+tag+ext)
}
1017880
func (p IndexFiles) writeTagsetTo(w io.Writer, name []byte, info *indexCompactInfo, n *int64) error {
	var seriesIDs []tsdb.SeriesID

	// Check for cancellation.
	select {
	case <-info.cancel:
		return ErrCompactionInterrupted
	default:
	}

	// Ensure block is word aligned.
	// if offset := (*n) % 8; offset != 0 {
	// 	if err := writeTo(w, make([]byte, 8-offset), n); err != nil {
	// 		return err
	// 	}
	// }

	kitr, err := p.TagKeyIterator(name)
	if err != nil {
		return err
	}

	enc := NewTagBlockEncoder(w)
	for ke := kitr.Next(); ke != nil; ke = kitr.Next() {
		// Encode key.
		if err := enc.EncodeKey(ke.Key(), ke.Deleted()); err != nil {
			return err
		}

		// Iterate over tag values.
		vitr := ke.TagValueIterator()
		for ve := vitr.Next(); ve != nil; ve = vitr.Next() {
			seriesIDs = seriesIDs[:0]

			// Merge all series together.
			if err := func() error {
				ss, err := p.TagValueSeriesIDSet(name, ke.Key(), ve.Value())
				if err != nil {
					return err
				}
				return enc.EncodeValue(ve.Value(), ve.Deleted(), ss)
			}(); err != nil {
				return nil
			}
		}
	}

	// Save tagset offset to measurement.
	pos := info.tagSets[string(name)]
	pos.offset = *n

	// Flush data to writer.
	err = enc.Close()
	*n += enc.N()
	if err != nil {
		return err
	}

	// Save tagset size to measurement.
	pos.size = *n - pos.offset

	info.tagSets[string(name)] = pos

	return nil
}
449162
func (f *IndexFile) TagKeyIterator(name []byte) TagKeyIterator {
	blk := f.tblks[string(name)]
	if blk == nil {
		return nil
	}
	return blk.TagKeyIterator()
}
189590
func (f *LogFile) DeleteTagKey(name, key []byte) error {
	f.mu.Lock()
	defer f.mu.Unlock()

	e := LogEntry{Flag: LogEntryTagKeyTombstoneFlag, Name: name, Key: key}
	if err := f.appendEntry(&e); err != nil {
		return err
	}
	f.execEntry(&e)

	// Flush buffer and sync to disk.
	return f.FlushAndSync()
}
979433
func (f *LogFile) TagKeyN() (n uint64) {
	f.mu.RLock()
	defer f.mu.RUnlock()
	for _, mm := range f.mms {
		n += uint64(len(mm.tagSet))
	}
	return n
}
471008
func (r *Row) tagsKeys() []string {
	a := make([]string, 0, len(r.Tags))
	for k := range r.Tags {
		a = append(a, k)
	}
	sort.Strings(a)
	return a
}
751662
func (c *Manager) CreateTag(ctx context.Context, tag *Tag) (string, error) {
	// create avoids the annoyance of CreateTag requiring a "description" key to be included in the request,
	// even though the field value can be empty.
	type create struct {
		Name        string `json:"name"`
		Description string `json:"description"`
		CategoryID  string `json:"category_id"`
	}
	spec := struct {
		Tag create `json:"create_spec"`
	}{
		Tag: create{
			Name:        tag.Name,
			Description: tag.Description,
			CategoryID:  tag.CategoryID,
		},
	}
	if isName(tag.CategoryID) {
		cat, err := c.GetCategory(ctx, tag.CategoryID)
		if err != nil {
			return "", err
		}
		spec.Tag.CategoryID = cat.ID
	}
	url := internal.URL(c, internal.TagPath)
	var res string
	return res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
}
1139443
func (e *tagElement) write(bf *bytes.Buffer, indent int) {
	if Condense {
		l := len(e.children)
		if l == 0 {
			writeLine(bf, indent, e.startTagRaw, e.endTagRaw)
			return
		} else if l == 1 && e.endTagRaw != "" {
			if c, ok := e.children[0].(*textElement); ok {
				writeLine(bf, indent, e.startTagRaw, c.text, e.endTagRaw)
				return
			}
		}
	}

	writeLine(bf, indent, e.startTagRaw)
	for _, c := range e.children {
		var childIndent int
		if e.endTagRaw != "" {
			childIndent = indent + 1
		} else {
			childIndent = indent
		}
		c.write(bf, childIndent)
	}
	if e.endTagRaw != "" {
		writeLine(bf, indent, e.endTagRaw)
	}
}
276110
func (s *ResourcetagsService) CreateTags(p *CreateTagsParams) (*CreateTagsResponse, error) {
	resp, err := s.cs.newRequest("createTags", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r CreateTagsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
699217
func Create(file string) *IndexWriter {
	return &IndexWriter{
		trigram:   sparse.NewSet(1 << 24),
		nameData:  bufCreate(""),
		nameIndex: bufCreate(""),
		postIndex: bufCreate(""),
		main:      bufCreate(file),
		post:      make([]postEntry, 0, npost),
		inbuf:     make([]byte, 16384),
	}
}
169235
func TagWrite(ctx formatter.Context, signedTagInfoList []SignedTagInfo) error {
	render := func(format func(subContext formatter.SubContext) error) error {
		for _, signedTag := range signedTagInfoList {
			if err := format(&trustTagContext{s: signedTag}); err != nil {
				return err
			}
		}
		return nil
	}
	trustTagCtx := trustTagContext{}
	trustTagCtx.Header = formatter.SubHeaderContext{
		"SignedTag": signedTagNameHeader,
		"Digest":    trustedDigestHeader,
		"Signers":   signersHeader,
	}
	return ctx.Write(&trustTagCtx, render)
}
438370
func (d *Dataset) AppendTagged(row []interface{}, tags ...string) error {
	if err := d.Append(row); err != nil {
		return err
	}
	d.tags[d.rows-1] = tags[:]
	return nil
}
863502
func (i *Index) TagKeyIterator(name []byte) (tsdb.TagKeyIterator, error) {
	a := make([]tsdb.TagKeyIterator, 0, len(i.partitions))
	for _, p := range i.partitions {
		itr, err := p.TagKeyIterator(name)
		if err != nil {
			for _, itr := range a {
				itr.Close()
			}
			return nil, err
		} else if itr != nil {
			a = append(a, itr)
		}
	}
	return tsdb.MergeTagKeyIterators(a...), nil
}
1323337
func (b *Builder) TagOpen(tag dwarf.Tag, name string) dwarf.Offset {
	if len(b.tagStack) > 0 {
		b.tagStack[len(b.tagStack)-1].children = true
	}
	ts := &tagState{off: dwarf.Offset(b.info.Len())}
	ts.tag = tag
	b.info.WriteByte(0)
	b.tagStack = append(b.tagStack, ts)
	b.Attr(dwarf.AttrName, name)

	return ts.off
}
474815
func (b *Bag) BagInfo() (*TagFile, error) {
	tf, err := b.TagFile("bag-info.txt")
	if err != nil {
		return nil, err
	}
	return tf, nil
}