Example #1
0
func TestUndraftContent(t *testing.T) {
	tests := []struct {
		fm          string
		expectedErr string
	}{
		{jsonFM, "not a Draft: nothing was done"},
		{jsonDraftFM, ""},
		{tomlFM, "not a Draft: nothing was done"},
		{tomlDraftFM, ""},
		{yamlFM, "not a Draft: nothing was done"},
		{yamlDraftFM, ""},
	}

	for _, test := range tests {
		r := bytes.NewReader([]byte(test.fm))
		p, _ := parser.ReadFrom(r)
		res, err := undraftContent(p)
		if test.expectedErr != "" {
			if err == nil {
				t.Error("Expected error, got none")
				continue
			}
			if err.Error() != test.expectedErr {
				t.Errorf("Expected %q, got %q", test.expectedErr, err)
				continue
			}
		} else {
			r = bytes.NewReader(res.Bytes())
			p, _ = parser.ReadFrom(r)
			meta, err := p.Metadata()
			if err != nil {
				t.Errorf("unexpected error %q", err)
				continue
			}
			for k, v := range meta.(map[string]interface{}) {
				if k == "draft" {
					if v.(bool) {
						t.Errorf("Expected %q to be \"false\", got \"true\"", k)
						continue
					}
				}
				if k == "date" {
					if !strings.HasPrefix(v.(string), time.Now().Format("2006-01-02")) {
						t.Errorf("Expected %v to start with %v", v.(string), time.Now().Format("2006-01-02"))
					}
				}
			}
		}
	}
}
Example #2
0
// Publish publishes the specified content by setting its draft status
// to false and setting its publish date to now. If the specified content is
// not a draft, it will log an error.
func Undraft(cmd *cobra.Command, args []string) {
	InitializeConfig()

	if len(args) < 1 {
		cmd.Usage()
		jww.FATAL.Fatalln("a piece of content needs to be specified")
	}

	location := args[0]
	// open the file
	f, err := os.Open(location)
	if err != nil {
		jww.ERROR.Print(err)
		return
	}

	// get the page from file
	p, err := parser.ReadFrom(f)
	f.Close()
	if err != nil {
		jww.ERROR.Print(err)
		return
	}

	w, err := undraftContent(p)
	if err != nil {
		jww.ERROR.Printf("an error occurred while undrafting %q: %s", location, err)
		return
	}

	f, err = os.OpenFile(location, os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		jww.ERROR.Printf("%q not be undrafted due to error opening file to save changes: %q\n", location, err)
		return
	}
	defer f.Close()
	_, err = w.WriteTo(f)
	if err != nil {
		jww.ERROR.Printf("%q not be undrafted due to save error: %q\n", location, err)
	}
	return
}
Example #3
0
func convertContents(mark rune) (err error) {
	InitializeConfig()
	site := &hugolib.Site{}

	if err := site.Initialise(); err != nil {
		return err
	}

	if site.Source == nil {
		panic(fmt.Sprintf("site.Source not set"))
	}
	if len(site.Source.Files()) < 1 {
		return fmt.Errorf("No source files found")
	}

	jww.FEEDBACK.Println("processing", len(site.Source.Files()), "content files")
	for _, file := range site.Source.Files() {
		jww.INFO.Println("Attempting to convert", file.LogicalName())
		page, err := hugolib.NewPage(file.LogicalName())
		if err != nil {
			return err
		}

		psr, err := parser.ReadFrom(file.Contents)
		if err != nil {
			jww.ERROR.Println("Error processing file:", file.Path())
			return err
		}
		metadata, err := psr.Metadata()
		if err != nil {
			jww.ERROR.Println("Error processing file:", file.Path())
			return err
		}

		// better handling of dates in formats that don't have support for them
		if mark == parser.FormatToLeadRune("json") || mark == parser.FormatToLeadRune("yaml") || mark == parser.FormatToLeadRune("toml") {
			newmetadata := cast.ToStringMap(metadata)
			for k, v := range newmetadata {
				switch vv := v.(type) {
				case time.Time:
					newmetadata[k] = vv.Format(time.RFC3339)
				}
			}
			metadata = newmetadata
		}

		page.SetDir(filepath.Join(helpers.AbsPathify(viper.GetString("ContentDir")), file.Dir()))
		page.SetSourceContent(psr.Content())
		page.SetSourceMetaData(metadata, mark)

		if outputDir != "" {
			page.SaveSourceAs(filepath.Join(outputDir, page.FullFilePath()))
		} else {
			if unsafe {
				page.SaveSource()
			} else {
				jww.FEEDBACK.Println("Unsafe operation not allowed, use --unsafe or set a different output path")
			}
		}
	}
	return
}
Example #4
0
func NewContent(kind, name string) (err error) {
	jww.INFO.Println("attempting to create ", name, "of", kind)

	location := FindArchetype(kind)

	var by []byte

	if location != "" {
		by, err = ioutil.ReadFile(location)
		if err != nil {
			jww.ERROR.Println(err)
		}
	}
	if location == "" || err != nil {
		by = []byte("+++\n title = \"title\"\n draft = true \n+++\n")
	}

	psr, err := parser.ReadFrom(bytes.NewReader(by))
	if err != nil {
		return err
	}
	metadata, err := psr.Metadata()
	if err != nil {
		return err
	}
	newmetadata, err := cast.ToStringMapE(metadata)
	if err != nil {
		jww.ERROR.Println("Error processing archetype file:", location)
		return err
	}

	for k := range newmetadata {
		switch strings.ToLower(k) {
		case "date":
			newmetadata[k] = time.Now()
		case "title":
			newmetadata[k] = helpers.MakeTitle(helpers.Filename(name))
		}
	}

	caseimatch := func(m map[string]interface{}, key string) bool {
		for k := range m {
			if strings.ToLower(k) == strings.ToLower(key) {
				return true
			}
		}
		return false
	}

	if newmetadata == nil {
		newmetadata = make(map[string]interface{})
	}

	if !caseimatch(newmetadata, "date") {
		newmetadata["date"] = time.Now()
	}

	if !caseimatch(newmetadata, "title") {
		newmetadata["title"] = helpers.MakeTitle(helpers.Filename(name))
	}

	page, err := hugolib.NewPage(name)
	if err != nil {
		return err
	}

	if x := parser.FormatSanitize(viper.GetString("MetaDataFormat")); x == "json" || x == "yaml" || x == "toml" {
		newmetadata["date"] = time.Now().Format(time.RFC3339)
	}

	//page.Dir = viper.GetString("sourceDir")
	page.SetSourceMetaData(newmetadata, parser.FormatToLeadRune(viper.GetString("MetaDataFormat")))
	page.SetSourceContent(psr.Content())
	if err = page.SafeSaveSourceAs(filepath.Join(viper.GetString("contentDir"), name)); err != nil {
		return
	}
	jww.FEEDBACK.Println(helpers.AbsPathify(filepath.Join(viper.GetString("contentDir"), name)), "created")

	editor := viper.GetString("NewContentEditor")

	if editor != "" {
		jww.FEEDBACK.Printf("Editing %s in %s.\n", name, editor)

		cmd := exec.Command(editor, path.Join(viper.GetString("contentDir"), name))
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

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

	return nil
}